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!

13 vues (au cours des 30 derniers jours)
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?

Réponses (3)

Raj
Raj le 14 Fév 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 le 14 Fév 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 le 21 Mar 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'})

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by