How to find elements in an array faster / without using for loop?
Show older comments
Hi,
I have the following working code with a for loop but I want to make the process faster. For the sizes of arrays I use this process now takes up to 30 seconds.
The code:
neighbour is a X by 2 array with integers only (for example 65000 x 2)
squares is a Y by 4 array with integers only (for example 35000 x 4)
B = zeros(squares,1); %the preallocation I tried - not much helpful, minimal time saving
for i = 1:length(neighbour) % for loop going though values from 1 to length of 'neighbour' array ~ for example 1:65000
B = any(squares == (neighbour(i,1)),2) & any(squares == (neighbour(i,2)),2);
% this finds indicies of lines in 'squares' where there are both values from 'i'th row of 'neighbour' array
end
If not clear from the code what I want to do is:
I want to go though the 'neighbour' array row by row and obtain the indicies of lines in 'square' array which contain the values as in that row in neighbour array.
Example:
if the neighbour array had only 1 row with
[1 2]
in it, and the square array looked like this:
[ 4 58 6 7;
1 2 47 48;
84 12 8 9],
then the output should be the index of the line in square array which contains both numbers i.e.
2
I have tried preallocation but the time it saves is marginal. Do you have any ideas on how to make this faster, ideally without a for loop?
Many thanks,
Jan
Accepted Answer
More Answers (1)
Christopher McCausland
on 3 Feb 2022
1 vote
5 Comments
Jan Brychta
on 3 Feb 2022
Christopher McCausland
on 3 Feb 2022
Edited: Christopher McCausland
on 4 Feb 2022
Hi Jan,
I’m on mobile here so please excuse the formatting. I suspect that ismember should be significantly quicker as it will us matrix based operations rather than element by element.
Try; [Lia,Locb] = ismember(Neighbour,Square,’rows’)
This should return which elements are present and their location. Adding in ‘rows’ will ensure that the entirety of Neighbour is used and not just one element.
Also for speed comparison you can use
tic
%code you want to time here
toc
And matlab will return a runtime in the command window. Hope this helps, Christopher
Jan Brychta
on 4 Feb 2022
Christopher McCausland
on 4 Feb 2022
Hi Jan,
The fact that your data isn't the same size is a little problematic! I would suggest zero padding but I think this will cause more problems as neighbour would probably never be found in the larger matrix (square).
One option might be to use reshape() to reshape square to the same size as neighbour. I think re-arrainging neigbhour and using [Lia,Locb] = ismember(Neighbour,Square,’rows’) will probably be your best bet.
Let me know how you get on,
Christopher
Jan Brychta
on 5 Feb 2022
Edited: Jan Brychta
on 5 Feb 2022
Categories
Find more on Resizing and Reshaping Matrices 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!