MATLAB Answers

0

Multiple Variable For Loop

Asked by Adam Parry on 31 Jul 2012
Hi
I have so far written this for loop
for i = 1:VgStep
for start = 1:VgStep:endPoint-VgStep+1
for step = VgStep:VgStep:endPoint
Vd{j}{i} = x(start:step);
Id{j}{i} = y(start:step);
end
end
end
I appologise for not explaining what all the terms are, but what I need is combine all those for's into one, because I end up just getting the same value for all my Vd{j}{i} terms
I'll explain better if it is needed

  4 Comments

Show 1 older comment
Can you give an example of what you want? All we have to go on is your code, which doesn't do what you want so we have to just guess. also, start and step are reserved words.
Adam Parry on 31 Jul 2012
ah ok.
so here is some data
x y Vg
0 1 0
-1 2 0
-2 3 0
0 4 -1
-1 5 -1
-2 6 -1
0 7 -2
-1 8 -2
-2 9 -2
I need to split the data into three separate arrays
so I want
Vd{1}{1} = [0,-1,-2] Id{1}{1} = [1,2,3]
Vd{1}{2} = [0,-1,-2] Id{1}{2} = [4,5,6]
etc.
but i realised that the inside loops all finish before i can loop over to start a new cell.
How can I prevent this?
Walter Roberson
on 31 Jul 2012
John, neither start nor step are reserved words. See http://www.mathworks.com/help/techdoc/ref/iskeyword.html

Sign in to comment.

1 Answer

Answer by Albert Yam
on 31 Jul 2012
 Accepted Answer

In the code posted, you do not have 'j' (this might be elsewhere in your code), in your example, not even sure why you need it.
Since you know what your step size is, you don't need to loop it, the way it is now, seems incorrect. This is what I see from your start:stop. When start > stop , you will get an empty index.
1:3, 1:6, 1:9, 4:3, 4:6, 4:9, 7:3 (error), 7:6 (error), 7:9
Do you understand how the following works?
i = 1;
for start = 1:VgStep:length(Vg) %what does this count?
Vd{i} = x(start:start+2); %try to understand the indexing here
Id{i} = y(start:start+2);
i=i+1; %how is this affected by 'start'?
end

  1 Comment

Adam Parry on 31 Jul 2012
Thank you
This is exactly what i was looking for

Sign in to comment.