Reputation: 1102
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
Reputation: 307
If you want to find any matches regardless of order
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
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