Write a program that calculates the length of hypotenuse c for all (!) combinations of legs a and b and do so using a for loop!

6 visualizaciones (últimos 30 días)
Dear all,
I need some help with the following:
Write a program that calculates the length of hypotenuse c for all (!) combinations of legs
a and b (a=(3;5;1;3;2) and b=(1;3;2;7;2)) - and do so using a for loop!
Im a total beginner and i have no idea how to do this for all the possible combinations. Thats what im having right now:
for i=1:5
a(i)= input ('Enter a')
b(i)= input ('Enter b')
end
C=sqrt(a.^2+b.^2)
disp (C)
Can someone help?

Respuestas (3)

Raj
Raj el 14 de Feb. de 2020
You already know 'a' and 'b' from your problem statement. Just declare them as vectors directly. No need to enter the values one by one. Use proper indexing to compute 'C' for each value of 'a' and 'b' like this:
a=[3;5;1;3;2]
b=[1;3;2;7;2]
C=zeros(length(a),1); % Pre allocate 'C'
for ii=1:length(a)
C(ii,1)=sqrt(a(ii).^2+b(ii).^2);
end
C

Stephen23
Stephen23 el 14 de Feb. de 2020
The easiest way to get all combinations is to use two loops:
a = [3;5;1;3;2];
b = [1;3;2;7;2];
for ii = 1:numel(a)
for jj = 1:numel(b)
c = sqrt(a(ii).^2 + b(jj).^2);
fprintf('a=%g b=%g c=%g\n',a(ii),b(jj),c)
end
end

Mohammed Hamaidi
Mohammed Hamaidi el 21 de Mzo. de 2022
An other way without loop
a = [3;5;1;3;2];
b = [1;3;2;7;2];
[A B]=meshgrid(a,b);
C=[A(:),B(:)];
c=sqrt(C(:,1).^2+C(:,2).^2);
%displaying
disp([repmat('a=',length(c),1) num2str(A(:)) repmat(', b=',length(c),1) num2str(B(:)) repmat(', c=',length(c),1) num2str(c(:))])
%or
table(A(:),B(:),c,'VariableNames',{'a' 'b' 'c'})

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by