MATLAB: Replacing elements of a logical index vector

logical indexing

“Idx” is a logical index vector when a certain “power on” condition is true (e.g. idx=Pwr_on>threshold) Say the result is 5 "zeros" and 5 "ones" per cycle i.e. idx=[0;0;0;0;0;1;1;1;1;1;0;0;0;0;0;1;1;1;1;1;0;0;0;0;0………] Every time idx is true; I need to replace the first element and last element with “0” within the index. So effectively idx=[0;0;0;0;0;0;1;1;1;0;0;0;0;0;0;0;1;1;1;0;0;0;0;0;0………] Any suggestions

Best Answer

This will do it. It's explicit so you can see what's going on. Of course, you could collapse it all down into a single line of code (though that may be hard to follow).
idx=[0;0;0;0;0;1;1;1;1;1;0;0;0;0;0;1;1;1;1;1;0;0;0;0;0]
di = [0; diff(idx)]
leadingEdges = find(di>0)
trailingEdges = find(di<0)-1
idx(leadingEdges) = 0;
idx(trailingEdges) = 0