Solve the problem by while loop

1 visualización (últimos 30 días)
sss dzu
sss dzu el 15 de Oct. de 2012
Comentada: Image Analyst el 6 de Sept. de 2023
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 comentarios
Niraj
Niraj el 2 de Sept. de 2023
i=5;
sum=0;
while i<=18
sum=sum+i;
i = i + 1;
end
display(sum)
Image Analyst
Image Analyst el 6 de Sept. de 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.

Iniciar sesión para comentar.

Respuestas (1)

Image Analyst
Image Analyst el 15 de Oct. de 2012
Editada: Image Analyst el 15 de Oct. de 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 comentarios
sss dzu
sss dzu el 15 de Oct. de 2012
Thank you. I got the answer.
Image Analyst
Image Analyst el 6 de Sept. de 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

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by