Problem with while loop, index is set back
Mostrar comentarios más antiguos
I try to compare two line vectors in a way that the following is supposed to happen:
As long as a "0" is detected in vector1, then the index in the result-vector u is also "0". As soon as a "1" is detected, the value of vector2 is to be written to "u" until another "1" is detected in vector1.
The following example should illustrate what I mean:
vector1 = [0 0 0 0 1 0 0 0 0 0 1 0 0 0 0];
vector2 = [0 0 1 1 1 1 1 1 0 1 1 1 1 0 0];
The result should be:
u = [0 0 0 0 1 1 1 1 0 1 1 0 0 0 0]
Instead I get:
u = [0 0 0 0 1 0 0 0 0 0 1 1 1 0 0]
My code:
u = zeros(1,size(vector1,2));
for i = 1:size(vector1,2)
if vector1(1,i) == 0
u(1,i) = 0;
else
u(1,i) = 1;
i = i+1;
while vector1(1,i) <1
u(1,i) = vector2(1,i);
i = i+1;
end
u(1,i) = 1;
end
end
I ran the debugger and the following happens: At i = 5 the first "1" is detected and the else statement with while loop starts. As soon as it enters the while loop, i is increased correctly. When the second "1" is detected in vector1, it exists the while loop correctly. u looks like this:
u = [0 0 0 0 1 1 1 1 0 1 1 0 0 0 0]
i = 11
But then, on the next turn, starting with the next "if" statement at the beginning, i is set back to i = 6 as if the while loop was never entered. Then the already existing spots are overwritten by "0" again. Probably something simple with overwriting i , but I have been trying to figure it out for the past 2 hrs and just couldn't solve it.
Thank you for your help!
Respuesta aceptada
Más respuestas (1)
You can't overwrite i. for loops in matlab do not work like that. At each iteration of the for, i takes the next value in the vector [1 2 3 ... size(vector1, 2)].
If you do want to your computation with a for loop, I would just use a flag to tell me whether to copy or not the element at each iteration. You toggle the flag whenever you encounter a one in vector1:
u = zeros(size(vector1));
docopy = false;
for idx = 1 : numel(vector1)
if vector1(idx) == 1
u(idx) = vector2(idx); %always copy when 1
docopy = ~docopy; %toggle flag
else
u(idx) = docopy & vector2(idx); %will always be 0 if docopy is false
end
end
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!