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
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