iterating values of a vector under conditions

I have a for loop to make the elements of vector v. I want to do iteration i+1 only for the elements with zero value in iteration i. (meaning that if I get v=[0,1,0,1] with i=1, I want to do iteration i=2 only for the 1st and 3rd elements.I need to break the loop whenever all the elements of v are filled with non zero values.
v=[0;0;0;0] for i=1:maxit
v=[process1(i)...;process2(i)...;process3(i)...;process4(i)...]
end

 Akzeptierte Antwort

Matt Tearle
Matt Tearle am 12 Sep. 2012
Bearbeitet: Matt Tearle am 12 Sep. 2012

0 Stimmen

If I understand you correctly, you have a procedure you want to iteratively apply to a vector, but only to the elements of that vector that are 0.
Here's some code that applies the "3n+1" procedure to the elements of a vector that are greater than 1:
% starting vector
v = 1:10;
% iterate
for k = 1:8
% exclusion criterion
idx = v>1;
% extract just the elements that satisfy the criterion
w = v(idx);
% and do something to them
isodd = (mod(w,2)==1);
w(~isodd) = 0.5*w(~isodd);
w(isodd) = 3*w(isodd) + 1;
% update just the altered values
v(idx) = w
end
Obviously, you would change the test to idx = v==0 and the "do something" section would be whatever you want.

Weitere Antworten (2)

Matt Fig
Matt Fig am 12 Sep. 2012
Bearbeitet: Matt Fig am 12 Sep. 2012

1 Stimme

I am not quite sure what you want, but perhaps you should look at the CONTINUE keyword. If this isn't what you need, you should come up with an example input and an expected output...

3 Kommentare

FATEMEH
FATEMEH am 12 Sep. 2012
thanks a lot Matt for your time. I tried to make a simple example.
for i=1:10
v=[i-1;i-2;i-3;i-4]
end
with i=1 , v=[0,-1,-2,-3]. The last 3 elements are ok. I want to do the next iteration only for v(1,1) and so the final output that I need is v=[1;-1;-2;-3] and I break the loop....
Matt Fig
Matt Fig am 12 Sep. 2012
Bearbeitet: Matt Fig am 12 Sep. 2012
What are you trying to achieve by this in general? This is silly to do in a loop, because you know what values of the index will make v give a zero.
v = [0;0;0;0];
ii = 1;
while all(~v)
v = [ii-1;ii-2;ii-3;ii-4];
end
FATEMEH
FATEMEH am 12 Sep. 2012
The thing is that I don't want to update non zero elements.
This is a simple example. I need the loop actually. In the real code for each i, I read a separate file to get the v values.

Melden Sie sich an, um zu kommentieren.

Azzi Abdelmalek
Azzi Abdelmalek am 12 Sep. 2012
Bearbeitet: Azzi Abdelmalek am 12 Sep. 2012

0 Stimmen

v=[0,1,0,1]
idx=find(v==0)
p=process(idx)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-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