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 次查看(过去 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 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by