2016-07-24 50 views
0

我有一個單元陣列grnPixels,其大小爲(1 x 40),其中每個單元格都有一個M x 1向量數組,其中M是可變的。我也有一個大小爲N x 1的稱爲redCentroid的單個矢量數組。如何檢查數組中的值是否與單元格數組中的值對應

我想檢查redCentroid中的值是否與grnPixels中的任何值相對應。我已經做了一個代碼,但它是極其緩慢在這個Matlab代碼。我該如何改進?所以沒有必要外環或最內層循環

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 

示例數據

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 

回答

1

ismember可以接受兩者的第一或第二輸入的矩陣。

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

嗨,它似乎告訴我,'cat(2,grnPixels {:})'中'串聯的矩陣的維度是不一致的。 – Senyokbalgul

+0

@Senyokbalgul剛做了一個小小的調整。 – Suever

+0

它似乎仍然給我同樣的錯誤.. – Senyokbalgul

1

如果你想找到任何匹配,無論爲了

  1. 複製兩個矩陣的其他兩個矩陣,如果你想在原來的矩陣保持不變。
  2. 排序兩者的新矩陣的單獨
  3. 比較兩個矩陣的最低元件
  4. 如果它們匹配,該元件存儲在一些收集器陣列
  5. 如果它們不這樣做,移動到下一個數數字最小的一組。
  6. 重複第2步到第4步,直到你經歷了一組。
  7. 收集器數組將包含所有匹配。

這應該以2 * M * log(M)+ 2 * M時間運行。

如果您想查找與匹配對應的原始矩陣中的索引,只需將收集器陣列中的每個元素與兩個矩陣的元素進行比較,只要找到匹配就記錄索引,並繼續到達到結束。

如果元素按照特定順序(如座標),則只需將第一個元素中的元素1與第二個元素中的元素1進行比較即可。

相關問題