Senyokbalgul
Senyokbalgul

Reputation: 1102

How to check if the values in an array correspond to values in a cell array

I have a cell array called grnPixels of size (1 x 40), where each individual cell has an M x 1 vector array of numbers where M is variable. I also have a single vector array called redCentroid of size N x 1.

I want to check if the values in redCentroid correspond to any values in grnPixels. I have made a code but it is extremely slow in this Matlab code. How can I improve this?

nRedCells = length(propsRed);
nGrnCells = length(propsGrn);
grnPixels = cell(1,nGrnCells);
redCentroid = zeros(nRedCells,1);
matchMemory = zeros(nRedCells,1);

for j = 1:nRedCells
    for i = 1:nGrnCells
        for n = 1:length(grnPixels{i})
            matchment = ismember(redCentroid(j),grnPixels{i}(n));
            if matchment == 1
                matchMemory(j,1:2) = [j i];
            end
            continue
        end
     end
 end

Sample Data

redCentroid

51756
65031
100996
118055
122055
169853
197175
233860
244415
253822

grnPixels{1}

142
143
100996
167
168

grnPixels{2}

537
538
539
540
541
542
233860
244415
545
546
547
548

Upvotes: 0

Views: 62

Answers (2)

AlgorithmsX
AlgorithmsX

Reputation: 307

If you want to find any matches regardless of order

  1. Copy the two matrices to two other matrices if you want the original matrices to remain unchanged.
  2. Sort both of the new matrices individually
  3. Compare the lowest elements of the two matrices
  4. If they match, store the element in some collector array
  5. If they don't, move to the next number in the set with the lowest number.
  6. Repeat steps 2 through 4 until you have gone through one set.
  7. The collector array will contain all the matches.

This should run in 2*M*log(M)+2*M time.

If you want to find the indices in the original matrices that correspond to the matches, just compare each element in the collector array with the elements of both matrices, record the index whenever a match is found, and continue until you reach the end.

If the elements are in a specific order, like coordinates, just compare element 1 in the first set to element 1 in the second set.

Upvotes: 1

Suever
Suever

Reputation: 65430

ismember can accept a matrix for both the first or second input so there is no need for the outer loop or the most inner loop.

matchMemory = zeros(numel(redCentroid), 2);

for k = 1:numel(grnPixels)
    % Check which of the centroids are in grnpixels
    isPresent = ismember(redCentroid, grnPixels{k});

    % If they were present fill in the first column with the index in red
    matchMemory(isPresent, 1) = find(isPresent);

    % Fill in the second column with the index in green
    matchMemory(isPresent, 2) = k;
end

Upvotes: 1

Related Questions