# How to make sure a line executes only after another line is finished?

1 view (last 30 days)
Thomas Nell on 26 Apr 2021
Edited: Jan on 26 Apr 2021
Hey guys,
I have this code below:
i = 1;
duration = rand(length(inverse2),1);
for j = 1:length(duration)
if inverse2(j) ~= 0
i = i + 1;
duration(j) = 0;
else
duration(j) = i;
i = 1;
end
end
essentially i acts as a counter and what I want to happen is when a 0 value approaches in the 'inverse2' array, the value of i is put in the duration array and the counter is reset. And for all other times where inverse2 is a positive/negative number, duration should show up as 0, if that makes sense. What I get is a problem where duration is constantly 1 when all values in inverse2 are 0. I think the reason behind this is that both lines in the else loop execute at the same time, so duration just shows up as the value of 1. Is there any way I can get them to execute sequentially?
Thanks!!

Jan on 26 Apr 2021
Edited: Jan on 26 Apr 2021
"both lines in the else loop execute at the same time" - no, this is not the way Matlab works. The lines are processed one after the other.
Use the debugger to check, what's going on: Set a breakpoint in the first line and step through the code line by line.
The purpose of your code is not clear. Why to you create duration as random array, when you overwrite all values?
inverse2 = [1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1];
i = 1;
duration = zeros(size(inverse2));
for j = 1:numel(duration)
if inverse2(j) ~= 0
i = i + 1;
duration(j) = 0;
else
duration(j) = i;
i = 1;
end
end
duration
duration = 1×14
0 0 0 4 0 0 0 4 1 0 0 0 4 0
A more Matlab'ish approach:
inverse2 = [1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1];
duration = zeros(size(inverse2));
is0 = (inverse2 == 0);
duration(is0) = diff(find([true, is0]))
duration = 1×14
0 0 0 4 0 0 0 4 1 0 0 0 4 0

R2019a

### Community Treasure Hunt

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

Start Hunting!