Filter löschen
Filter löschen

indexing in nested loop

14 Ansichten (letzte 30 Tage)
Nicolas
Nicolas am 13 Apr. 2011
Hi,
I have nested loops in a code and I create files that increased for every loop which works like that: data1 gives me the number of lines created in the loop for the para meters 'a' and 'b', data2 gives me for each lines created its orientation/angle.
for a=1:20
...
for b=1:20
if
...
data1(a,b)=data1(a,b)+1
data2(data1(a,b),b)= tan(x/y)
end
end
end
But when I try with non-successive values, it doesn't works.
for a=1:5:101
...
for b=1:20
if
...
data1(a(i),b)=data1(a(i),b)+1
data2(data1(a(i),b),b)= tan(x/y)
end
end
end
I thought I needed to use the index value (i) of 'a' but it doesn't work like that I supposed or I'm making a mistake somewhere.
Looking forward your advices.
Cheers,
n.

Akzeptierte Antwort

Matt Fig
Matt Fig am 14 Apr. 2011
You might consider a loop counter or two:
cnt1 = 0;
cnt2 = 0;
for a=1:5:101
cnt1 = cnt1 + 1;
for b=1:20
cnt2 = cnt2 + 1;
data1(cnt1,cnt2) = ...
end
end
Now you can use the counters where you want and the a and b where you want. The alternative is to set your loop variables to integers (say ii and jj), then index into pre-existing vectors a and b (created before the loop). Such as:
a = 1:5:101
b = b=1:20
for ii = 1:length(a)
for jj = 1:length(b)
data1(ii,jj) = ... % Now index into a and b. a(ii),b(jj)
end
end
Note that it doesn't really make much sense to index into your loop variables (a and b) as you had it since they are scalar.
  1 Kommentar
Nicolas
Nicolas am 14 Apr. 2011
I like the loop counter ! thanks

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Robert Cumming
Robert Cumming am 13 Apr. 2011
in your first example in each loop a is:
1 2 3 4 5 6 7 8 9 10 11 ... 20
In your second it is:
1 6 11 16 21 26 31 .... 101
what were you expecting a(i) to do? If your confused on the value of a in each loop - print it to the screen (or check in the debug)
The answer to this question will depend on what you want to do with your data variables.
  1 Kommentar
Nicolas
Nicolas am 13 Apr. 2011
I would like to have data1 and data2 increasing by 1 in every loop, which is ok for the first example, but not for the second example because a=1 6 11 16 ... so the having a(i) give me the position instead of the value.. a(1)= 1; a(2)=6; a(3)=11.
basically, I want data1(a,b) to increase by one column (21*20), to avoid having a matrix (101:20).
i hope it is a bit clearer
cheers

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by