How to adjust counters for multiple for loops
5 ビュー (過去 30 日間)
古いコメントを表示
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
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
2021 年 4 月 2 日
Compare:
layers = 5;
x1 = 2:2*layers+1
x2 = (2:2*layers)+1
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.
0 件のコメント
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.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!