Nested for loop not working

7 次查看(过去 30 天)
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 个评论
Daniel Pollard
Daniel Pollard 2021-8-18
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?

请先登录,再进行评论。

采纳的回答

Bjorn Gustavsson
Bjorn Gustavsson 2021-8-18
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

更多回答(0 个)

类别

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