[英]How to remove extra duplicated elements in each row of a matrix in matlab?
Let's say I have a matrix 假设我有一个矩阵
A = [2 3 2 5 6 7 2;
1 2 5 4 5 6 7;
7 5 3 9 8 1 2];
How do I remove 2
s and keep one 2
in the first row and keep only one 5
in the second row? 如何删除
2
s并在第一行中保留2
5
,在第二行中仅保留5
个?
The result can't be a matrix anymore, because each row will have a different length. 结果不再是矩阵,因为每一行的长度都不同。 You can obtain the result as a cell array of row vectors as follows:
您可以按以下方式将结果作为行向量的单元格数组获得:
B = mat2cell(A, ones(size(A,1),1)); %// convert matrix to cell array of its rows
B = cellfun(@(x) unique(x,'stable'), B, 'uniformoutput', 0); %// stably remove duplicates
For your example matrix 对于您的示例矩阵
A = [2 3 2 5 6 7 2;
1 2 5 4 5 6 7;
7 5 3 9 8 1 2];
this gives 这给
B{1} =
2 3 5 6 7
B{2} =
1 2 5 4 6 7
B{3} =
7 5 3 9 8 1 2
If you want to find out which values are duplicates within the row, you can do something like this: 如果要找出该行中哪些值重复,可以执行以下操作:
[vals, col_idx] = sort(A,2);
idx = bsxfun(@plus,(col_idx-1)*size(A,1), (1:size(A,1))');
is_duplicate(idx(:,2:end)) = vals(:,1:end-1) == vals(:,2:end);
is_duplicate = reshape(is_duplicate, size(A));
is_duplicate = is_duplicate =
0 0 1 0 0 0 1
0 0 0 0 1 0 0
0 0 0 0 0 0 0
From there, it depends what outcome you are looking for. 从那里开始,这取决于您要寻找什么结果。 You could set the duplicates to
NaN
or some other value, or you could set them to NaN
, but then shift them to the end of the row, using something like the following: 您可以将重复项设置为
NaN
或其他某个值,也可以将它们设置为NaN
,然后使用类似以下内容的方法将其移至行末:
col_idx = cumsum(~is_duplicate, 2);
idx = bsxfun(@plus,(col_idx-1)*size(A,1), (1:size(A,1))');
A_new = nan(size(A));
A_new(idx(~is_duplicate)) = A(~is_duplicate);
A_new = A_new =
2 3 5 6 7 NaN NaN
1 2 5 4 6 7 NaN
7 5 3 9 8 1 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.