Nested for loop not working

4 views (last 30 days)
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 Comment
Daniel Pollard
Daniel Pollard on 18 Aug 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?

Sign in to comment.

Accepted Answer

Bjorn Gustavsson
Bjorn Gustavsson on 18 Aug 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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!