MATLAB: Can you please explain me this for loop in this code,How this is running

MATLAB

idx = EV > 0;
if iscolumn(idx), idx = idx'; end;
idx2 = [0, idx, 0];
prePt = []; postPt = [];
for i = 2 : length(idx2)-1
if idx2(i-1) == 0 & idx2(i) == 1 & idx2(i+1) == 1
prePt = [prePt, i-1];
end
if idx2(i-1) == 1 & idx2(i) == 1 & idx2(i+1) == 0
postPt = [postPt,i-1];
end
end

Best Answer

Explanation: that code is very inefficient way to find the indices of "runs of ones" in the variable idx. Basically it detects where 1 (or true) occurs more than once consecutively, and finds the start and the end indices of those runs. However it is very poorly written, using a for loop, multiple logical relations, and expanding the output arrays inside the loop. Do not learn MATLAB from this bad code!
For a more efficient solution using much neater MATLAB code, use this:
idy = [false;idx] & [idx;false];
idz = diff(idy);
preV = find(idz==1)
posV = find(idz==-1)
Yes, it gives the same results as the original (badly written) code.