multiple loop and produce infinite loop

hi, i have trouble using while loop. Where should i put the j inrement? i try fews times but infinite loop. Thanks in advance.
k = 4
j = 1
i=1
while j <= k
for n = i:40
if (G(i,11)) == j
mean = sum(G(i:10))/length(G)
i=i+1
break
end
%j=j+1
end
%j=j+1
end

1 commentaire

Guillaume
Guillaume le 25 Oct 2019
Modifié(e) : Guillaume le 25 Oct 2019
What is the code meant to be doing?
Note that using length on a 2D matrix is asking for a lot of trouble. Is that length supposed to return the number of rows or the number of columns (note that it can return either depending on the actual size of G)
And naming a variable mean is also a very bad idea since it prevents you from using the mean function.
Is the switching from 2D indexing (in G(i, 11)) to linear indexing (in G(i:10)) on purpose or a major error?

Connectez-vous pour commenter.

Réponses (1)

adeq123
adeq123 le 25 Oct 2019
This one works for me:
G = 100:1:1000;
k = 4;
j = 1;
i = 1
while j <= k
for n = i:40
if G(i,11) == j
mean = sum(G(i:10))/length(G)
i = i+1
break
end
%j=j+1
end
j=j+1
end

3 commentaires

Khairul Nur
Khairul Nur le 25 Oct 2019
oh.. it no more infinite loop, however seems have logic error here. The j value should increment after finishing doing for loop.
k =
4
j =
1
i =
1
j = <------- why the j had been add up.. supposely at the end of for loop
2
j = <------- the j keep incerement
3
mean =
3.3750
i =
2
j =
4
j =
5
adeq123
adeq123 le 25 Oct 2019
The j is incremaneting at the end of while loop. During the last iteration it is increament to 5 but the loop is not executed since entrance criteria is not met.
You can also do this one:
G = 100:1:1000;
k = 4;
j = 0;
i = 1
while j < k
j=j+1
for n = i:40
if G(i,11) == j
mean = sum(G(i:10))/length(G)
i = i+1
break
end
%j=j+1
end
end
But the result is the same as previous.
Khairul Nur
Khairul Nur le 25 Oct 2019
thanks for the explainantion, if i want to make j=2 is execute within for loop for the 2nd iteration..where should i put the j=j+1

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Commenté :

le 25 Oct 2019

Community Treasure Hunt

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

Start Hunting!

Translated by