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

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

2 Comments

According to your other question this code is not running, but generating an error. How do you expect us to explain what code does, if it only generates an error?
Thanks a lot sir as per your given solution it is now running now can u pls explain me this for loop

Sign in to comment.

 Accepted 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.

1 Comment

idy = [false; idx(:); false];
preV = strfind(idy, [0 1 1]);
posV = strfind(idy, [1 1 0]);
Might be off by 1 on the outputs.

Sign in to comment.

More Answers (1)

>> 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
segNum = length(prePt);
segment = [];
for k = 1 : segNum
segment(k,:) = [prePt(k), postPt(k)];
end
This is the complete code I want to know the no of segment of EV will this code work

Categories

Find more on App Building in Help Center and File Exchange

Tags

Asked:

on 12 Jan 2016

Edited:

on 13 Jan 2016

Community Treasure Hunt

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

Start Hunting!