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

1 次查看(过去 30 天)
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!!

回答(1 个)

Jan
Jan 2021-4-26
编辑:Jan 2021-4-26
"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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by