Find repeating rows in a matrix and replace with zeros

2 ビュー (過去 30 日間)
Savannah D
Savannah D 2020 年 11 月 3 日
コメント済み: Monika Jaskolka 2020 年 11 月 3 日
I have a large matrix (5683384x2 double) containing xy-coordinates of an ROI mask. If an xy-coordinate does not repeat enough times, I want to set the row to zeros.
For example if my matrix is [9 10; 9 10; 9 10; 9 10; 9 10; 7 12; 3 4; 3 4; 3 4; 3 4]. I want to replace rows that do not repeat 3 times, so [7 12] would become [0 0]. Is there any way to do this?

採用された回答

Monika Jaskolka
Monika Jaskolka 2020 年 11 月 3 日
編集済み: Monika Jaskolka 2020 年 11 月 3 日
This can probably be optimized, but it works to replace rows that don't occur more times than the set threshold, in this case 3 times.
M = [9 10; 9 10; 9 10; 9 10; 9 10; 7 12; 3 4; 3 4; 3 4; 3 4; 7 12];
threshold = 3;
[~, ~, ic] = unique(M, 'rows', 'stable');
numOccurances = accumarray(ic, 1);
idxToDelete = false(size(M,1), 1);
for i = 1:length(numOccurances)
if numOccurances(i) < threshold
duplicateRows = find(ic==i);
idxToDelete(duplicateRows) = true;
end
end
M(idxToDelete,:) = 0;
If you want to delete the rows entirely, you can replace the last line with this:
M(idxToDelete,:) = []; % Alternatively, delete rows
  2 件のコメント
Savannah D
Savannah D 2020 年 11 月 3 日
編集済み: Savannah D 2020 年 11 月 3 日
Thank you! the numOccurances tripped me up at first with my threshold, but this worked great!
Monika Jaskolka
Monika Jaskolka 2020 年 11 月 3 日
No problem! If the answer worked for you, please press the "Accept this answer" button.

サインインしてコメントする。

その他の回答 (1 件)

Bruno Luong
Bruno Luong 2020 年 11 月 3 日
編集済み: Bruno Luong 2020 年 11 月 3 日
M = [9 10; 9 10; 9 10; 9 10; 9 10; 7 12; 3 4; 3 4; 3 4; 3 4; 7 12];
minlgt = 3; % keep all rows consecutively repeated at least minlgt times
i = find([true; any(diff(M,1,1),2); true]);
lgt = diff(i);
removed = lgt<minlgt;
M(repelem(i(removed),lgt(removed)),:) = 0

カテゴリ

Help Center および File ExchangeIntroduction to Installation and Licensing についてさらに検索

タグ

製品


リリース

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by