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!