Nested for loop not working

7 vues (au cours des 30 derniers jours)
Nethravathi S
Nethravathi S le 18 Août 2021
Hello,
I code below is not working when i put first for loop statement. i.e. for kk=1:1:7
Not able to figure it out where is the issue.
I have attached the files.
ii=1;
jj=1;
k=1;
n=1;
for kk=1:1:7
for i=1:1:9
for j=1:1:18
% for kk=1:1:9
if AC2(k)==0
wt2(ii)=wt1(ii)-1.815;
else
wt2(ii)=wt1(ii);
end
ii=ii+9;
% end
% jj=jj+9;
% if jj>=162
% break
% end
n=n+1;
end
k=k+1;
ii=k;
end
ii=n;
end
  1 commentaire
Daniel Pollard
Daniel Pollard le 18 Août 2021
The way that ii index is used is very strange and could throw issues. You use it to index a vector, then you add 9 to it with every loop of j, you set it equal to k with every loop of i and set it equal to n with every loop of kk. This is very unusual and makes it difficult to understand what it's trying to do.
You loop over a variable i which runs from 1 to 9. Why do this if you never use the i? The same can be asked of j.
Please format the code properly in the question, and explain the problem. You said it doesn't work - if you get an error message, what does it say? If not, what does the code do, and what did you expect it to do?

Connectez-vous pour commenter.

Réponse acceptée

Bjorn Gustavsson
Bjorn Gustavsson le 18 Août 2021
You seem to have two for-loops with kk as index. That is not going to work in any robust way. For clarity I've learnt that to avoid these types of problems I am better off numbering my indices: i1, i2, i3 etc (or "naming" them if they correspond to some real quantity like position in x-direction i_x, i_t etc). That way I have reduced (almost removed) the risk of reusing the loop-variable-name in nested loops.
HTH

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by