More efficient alternative to the find function?

46 Ansichten (letzte 30 Tage)
Canberk Suat Gurel
Canberk Suat Gurel am 8 Mär. 2018
Kommentiert: Walter Roberson am 9 Mär. 2018
Hi all,
I am working on a path planning algorithm. I have generated a matrix A (consists of 1s and 0s.) which stores the neighbor node information. Using the following code I am finding the available neighbors and storing them in vector F.
F = find(A(current,:)==1);
However, unfortunately I found out that this line of code takes the longest time in my code (from 0.004018 to 0.023119s). (A matrix is a 37901 by 37901 matrix.)
Is there a more computationally efficient method to do this?
Thanks!
This is what the A matrix looks like:

Akzeptierte Antwort

James Tursa
James Tursa am 9 Mär. 2018
It is not clear from your post if A always has the pattern you show, but if it does then why not just this:
F = [current-1,current+1];
F(F<1|F>size(A,2)) = [];
  2 Kommentare
Canberk Suat Gurel
Canberk Suat Gurel am 9 Mär. 2018
Hello James. Thank you for the answer. It certainly follows a pattern.
I need to check [current-1, current+1, current+250, current-250, current+251, current-251, current+252, current-252];
Any suggestions on how to do this more efficiently compared to using F = find(A(current,:)); ? Thanks!
Walter Roberson
Walter Roberson am 9 Mär. 2018
locs = current+[-1, 1, -250, 250, -251, 251, -252, 252];
F = locs( logical(A(current, locs)) );
You can rearrange locs however is suitable.
The result in F is a list of indices, in the same order as you used to create locs.
You could improve performance by originally storing A as logical instead of as double.
Have you considered using diag() to extract the data for all of the rows at the same time? With a small bit of padding and some diag() you could build a 37901 x 8 matrix that focused on just the entries that might have useful information.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Walter Roberson
Walter Roberson am 8 Mär. 2018
You can improve a little by using
F = find(A(current,:));
Your A values are only 0 and 1, so comparing to 1 is going to give you exactly the same as A since == returns 0 and 1.
  1 Kommentar
Canberk Suat Gurel
Canberk Suat Gurel am 9 Mär. 2018
Bearbeitet: Canberk Suat Gurel am 9 Mär. 2018
Hello Walter, your suggestion reduced the time taken to 0.00162 - 0.004878 range. But as James suggested, the order of 1s and 0s are following a pattern. Please check my comment on his post.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by