Solve the problem by while loop

조회 수: 1 (최근 30일)
sss dzu
sss dzu 2012년 10월 15일
댓글: Image Analyst 2023년 9월 6일
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에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by