Solve the problem by while loop
3 views (last 30 days)
Show older comments
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 Comments
Image Analyst
on 6 Sep 2023
@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.
Answers (1)
Image Analyst
on 15 Oct 2012
Edited: Image Analyst
on 15 Oct 2012
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 Comments
Image Analyst
on 6 Sep 2023
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
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!