Solve the problem by while loop

7 次查看(过去 30 天)
sss dzu
sss dzu 2012-10-15
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 个评论
Niraj
Niraj 2023-9-2
i=5;
sum=0;
while i<=18
sum=sum+i;
i = i + 1;
end
display(sum)
Image Analyst
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
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 个评论
sss dzu
sss dzu 2012-10-15
Thank you. I got the answer.
Image Analyst
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 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