performance of diff on a logical array

조회 수: 3 (최근 30일)
Tom DeLonge
Tom DeLonge 2018년 2월 27일
댓글: Tom DeLonge 2018년 3월 9일
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.

채택된 답변

Walter Roberson
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()
  댓글 수: 4
Tom DeLonge
Tom DeLonge 2018년 3월 9일
oh this is a nice contribution. Indeed, something I've been looking for a while. Let's see whether it is 64-bit compatible...
Tom DeLonge
Tom DeLonge 2018년 3월 9일
Walter, I checked the contribution. The results are indeed interesting. It turns out, that using sharedchild I get a speedup by a factor of 2. I was quite surprised, I would have expected a 5-fold speedup (as indicated by my stats above). Turns out, that now the actual binary operation takes longer than before (nearly 4 times). The sharedchild-operation however is incredibly fast.
I have no idea what is going on behind the scenes here...

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

lokender Rawat
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
Walter Roberson
Walter Roberson 2018년 3월 9일
This will overwrite the entire variable index each time through the loop.
Tom DeLonge
Tom DeLonge 2018년 3월 9일
yes, Robert, thanks for that comment. I was able to increase the speed by a factor of 2 when not using diff, but rather having
A(1:end-1) > A(2:end)
still not really fast, since two logical arrays seem to be allocated here...

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by