How to make sure a line executes only after another line is finished?
1 view (last 30 days)
Show older comments
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!!
0 Comments
Answers (1)
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
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]))
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!