performance of diff on a logical array
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2018-3-9
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()
更多回答(1 个)
lokender Rawat
2018-3-9
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!