Nested for loop not working

조회 수: 6 (최근 30일)
Nethravathi S
Nethravathi S 2021년 8월 18일
답변: Bjorn Gustavsson 2021년 8월 18일
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