Solve the problem by while loop
1 回表示 (過去 30 日間)
古いコメントを表示
FIND THE SUM OF ALL ELEMENTS THE BETWEEN 5 AND 18 in the matrix BY WHILE LOOP. I know how to solve it by for loop, but when I try it by while loop, it does not run. Can anyone help me to correct it. Thank you. This is what I got
a=[10 18 12 8;
1 8 115 9;
35 12 21 13;
25 0 16 5];
Re=0;
i=1:4;
j=1:4
a (i,j)=5
while (a(i,j)<=18)
Re= Re+ a(i,j);
end
Re
2 件のコメント
Image Analyst
2023 年 9 月 6 日
@Niraj, don't use "sum" as the name of your variable since it's the name of a built-in function that you don't want to overwrite. Also don't use i since it's the imaginary constant.
Anyway, your solution totally ignores "a" and so it doesn't work. Try again, or see my solution below.
回答 (1 件)
Image Analyst
2012 年 10 月 15 日
編集済み: Image Analyst
2012 年 10 月 15 日
Try
logicalIndex = 1;
while logicalIndex <= numel(a)
Re = Re + a(logicalIndex);
logicalIndex = logicalIndex + 1;
end
This is a good time/opportunity for you to learn about logical indexes versus regular indexes.
2 件のコメント
Image Analyst
2023 年 9 月 6 日
If this Answer solves your original question, then could you please click the "Accept this answer" link to award the answerer with "reputation points" for their efforts in helping you? They'd appreciate it. Thanks in advance. 🙂 Note: you can only accept one answer (so pick the best one) but you can click the "Vote" icon for as many Answers as you want. Voting for an answer will also award reputation points.
Since it's been 11 years, here is how you can do it via two different ways:
a=[10 18 12 8;
1 8 115 9;
35 12 21 13;
25 0 16 5];
% Method 1: using logical index as a map for numbers in range:
logicalIndex = (a >= 5) & (a <= 18)
index = 1;
theSum1 = 0;
while index <= numel(a)
if logicalIndex(index)
% If it's in range, add it in.
theSum1 = theSum1 + a(index);
fprintf('Added in %d to the sum. Current sum = %d.\n', a(index), theSum1)
end
index = index + 1;
end
theSum1
% Method 2: using lines index for numbers in range:
index = 1;
theSum2 = 0;
while index <= numel(a)
inRange = (a(index) >= 5) & (a(index) <= 18);
if inRange
% If it's in range, add it in.
theSum2 = theSum2 + a(index);
fprintf('Added in %d to the sum. Current sum = %d.\n', a(index), theSum2)
end
index = index + 1;
end
theSum2
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!