performance of diff on a logical array
3 views (last 30 days)
Show older comments
Tom DeLonge
on 27 Feb 2018
Commented: Tom DeLonge
on 9 Mar 2018
I have a 5000x5000 logical array. I want to find the indices where the logical array has a rising edge, e.g. whenever the array goes from 0 to 1 within a row. Until now I did this as follows:
rising_edges = diff(A) == 1;
However, I notice that this is slow. I am pretty certain that this is slow because diff(A) has to allocate new memory for a 5000x5000 double array.
I am wondering: is there a more elegant and faster way of doing this? I'd also be happy with just the subscripts instead of a full logical index array.
0 Comments
Accepted Answer
Walter Roberson
on 9 Mar 2018
rising_edges = A(:,2:end)) & ~A(:,1:end-1);
this operates on the entire array at the same time. You can use the two-output version of find() on the result, prioritized by row instead of by column. You can put the two outputs together and sortrows() or there are various other ways like findgroups()
4 Comments
More Answers (1)
lokender Rawat
on 9 Mar 2018
You can simply declare an array "mat" and do the following, you do not need to create another new double array here. It will find the index from the logical array for each row and put it in "index" variable.
[matRow,matCol]=size(mat)
for i=1:matRow
index=find(mat(i,2:end)-mat(i,1:end-1)==1)
end
2 Comments
Walter Roberson
on 9 Mar 2018
This will overwrite the entire variable index each time through the loop.
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!