フィルターのクリア

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!

21 ビュー (過去 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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by