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!

조회 수: 4 (최근 30일)
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?

답변 (3개)

Raj
Raj 2020년 2월 14일
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 2020년 2월 14일
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 2022년 3월 21일
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'})

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by