필터 지우기
필터 지우기

How to adjust counters for multiple for loops

조회 수: 5 (최근 30일)
Kaylee Cornish
Kaylee Cornish 2021년 4월 2일
답변: William Rose 2021년 4월 2일
I'm trying to create two seperate arrays using different for loops:
for k=1:2*layers
for j=2:2*layers+1
ztop(k)=pt*(layers-(k-1));
zbot(j)=pt*(layers-(j-1));
end
end
Essentially I want counter k to be from 1 to 2 times the layers and counter j to be from 2 to 2 times the layers plus one.The j array keeps entering as a 1x5 instead of 4. How can I fix this?
  댓글 수: 1
DGM
DGM 2021년 4월 2일
Your problem description is ambiguous. I don't know what your code is trying to do conceptually. I know you tried to explain the indexing you're looking for, but sometimes conversational language is more ambiguous than we'd like to admit.
Let's start with what you've got already. I'm going to assume some value for layers:
layers=5;
k=1:2*layers
j=2:2*layers+1
This gives us:
k =
1 2 3 4 5 6 7 8 9 10
j =
2 3 4 5 6 7 8 9 10 11
In terms of endpoints or spacing, how do these vectors differ from what you're trying to achieve?

댓글을 달려면 로그인하십시오.

답변 (2개)

Steven Lord
Steven Lord 2021년 4월 2일
Compare:
layers = 5;
x1 = 2:2*layers+1
x1 = 1×10
2 3 4 5 6 7 8 9 10 11
x2 = (2:2*layers)+1
x2 = 1×9
3 4 5 6 7 8 9 10 11
The operator precedence matters. The colon operator : is at level 7, right after the plus operator + at level 6.
x1 computes (2*layers+1) and uses it as the second input to colon.
x2 creates the array using colon then adds 1 to each element.

William Rose
William Rose 2021년 4월 2일
You can use two non-nested for loops.
The second foor loop fills up the vector zbot.
zbot will be 1x4.
layers=2;
pt=1;
for k=1:2*layers
ztop(k)=pt*(layers-(k-1));
end
for j=2:2*layers+1
zbot(j-1)=pt*(layers-(j-1));
end
Then you just have to remember later that zbot(1) goes with j=2, zbot(4) goes with j=5, etc.

카테고리

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