# How to find pythagorean triangle's hypotenuse in a matrix?

5 views (last 30 days)
Ashfaq Ahmed on 8 Nov 2021
Answered: Sean de Wolski on 8 Nov 2021
Hey guys,
I have two 4x4 matrices a and b. I want a third c matrix of 4x4 size where all the values will be c = sqrt(a.^2+b.^2).
For example, the first row of c will be [13 10 13 5];
How can I do this using a for loop?
a = [5 8 12 3; 8 12 63 20; 9 84 144 20; 24 11 15 180];
b = [12 6 5 4; 15 35 16 21; 40 13 17 99; 7 60 112 19];
##### 0 CommentsShow -2 older commentsHide -2 older comments

Sign in to comment.

### Accepted Answer

C B on 8 Nov 2021
a = [5 8 12 3; 8 12 63 20; 9 84 144 20; 24 11 15 180];
b = [12 6 5 4; 15 35 16 21; 40 13 17 99; 7 60 112 19];
c=[];
for i =1 : size(a,1)
c(i,:) = sqrt(a(i,:).^2+b(i,:).^2)
end
c = 1×4
13 10 13 5
c = 2×4
13 10 13 5 17 37 65 29
c = 3×4
13 10 13 5 17 37 65 29 41 85 145 101
c = 4×4
13 10 13 5 17 37 65 29 41 85 145 101 25 61 113 181
##### 0 CommentsShow -2 older commentsHide -2 older comments

Sign in to comment.

### More Answers (2)

Sean de Wolski on 8 Nov 2021
This will be the most numrically stable.
a = [5 8 12 3; 8 12 63 20; 9 84 144 20; 24 11 15 180];
b = [12 6 5 4; 15 35 16 21; 40 13 17 99; 7 60 112 19];
hypot(a,b)
ans = 4×4
13 10 13 5 17 37 65 29 41 85 145 101 25 61 113 181
##### 0 CommentsShow -2 older commentsHide -2 older comments

Sign in to comment.

Chunru on 8 Nov 2021
Edited: Chunru on 8 Nov 2021
a = [5 8 12 3; 8 12 63 20; 9 84 144 20; 24 11 15 180];
b = [12 6 5 4; 15 35 16 21; 40 13 17 99; 7 60 112 19];
c = sqrt(a.^2 + b.^2)
c = 4×4
13 10 13 5 17 37 65 29 41 85 145 101 25 61 113 181
% Using for loops should be avoid for such problem in matlab
c = zeros(size(a));
for i=1:size(a,1)
for j=1:size(a, 2)
c(i,j) = sqrt(a(i,j)^2 + b(i,j)^2);
end
end
c
c = 4×4
13 10 13 5 17 37 65 29 41 85 145 101 25 61 113 181
##### 2 CommentsShow NoneHide None
Ashfaq Ahmed on 8 Nov 2021
Thank you so much. But is there any specific reason why should I avoid for loop?
Chunru on 8 Nov 2021
MATLAB excels on the matrix computations. "c = sqrt(a.^2 + b.^2)" is much neater and more efficient that the codes with loops.

Sign in to comment.

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!