Search code examples
matlabcomparisoncoordinatesmemory-efficient

How to compare the pairs of coordinates most efficiently without using nested loops in Matlab?


If I have 20 pairs of coordinates, whose x and y values are say :

x   y
27  182
180 81
154 52
183 24
124 168
146 11
16  90
184 153
138 133
122 79
192 183
39  25
194 63
129 107
115 161
33  14
47  65
65  2
1   124
93  79

Now if I randomly generate 15 pairs of coordinates (x,y) and want to compare with these 20 pairs of coordinates given above, how can I do that most efficiently without nested loops?


Solution

  • If you're trying to see if any of your 15 randomly generated coordinate pairs are equal to any of your 20 original coordinate pairs, an easy solution is to use the function ISMEMBER like so:

    oldPts = [...];  %# A 20-by-2 matrix with x values in column 1
                     %#   and y values in column 2
    newPts = randi(200,[15 2]);  %# Create a 15-by-2 matrix of random
                                 %#   values from 1 to 200
    isRepeated = ismember(newPts,oldPts,'rows');
    

    And isRepeated will be a 15-by-1 logical array with ones where a row of newPts exists in oldPts and zeroes otherwise.