Clear Filters
Clear Filters

How to adjust counters for multiple for loops

5 views (last 30 days)
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 Comment
DGM
DGM on 2 Apr 2021
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?

Sign in to comment.

Answers (2)

Steven Lord
Steven Lord on 2 Apr 2021
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 on 2 Apr 2021
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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!