How can I find and remove the nonzero duplicates in each column of a matrix
2 次查看(过去 30 天)
显示 更早的评论
X is a n-by-n matrix of integers ranging from 0 to n. I want to find nonzero duplicate entries in each column and remove them.
2 个评论
Image Analyst
2016-7-4
编辑:Image Analyst
2016-7-4
Unless there is exactly the same number of elements to remove in each column, you can't. For example, you can't "remove" 3 elements from column 1 and 8 elements from column 2. Can you give an example of input and output and how you used unique() to try to solve it?
采纳的回答
per isakson
2016-7-6
编辑:per isakson
2016-7-6
Given
- "matrix of integers"
- "the first row is always the column number"
- "the duplicate, if exists, is always the same integer as the column number"
Try this
X = [ 1 2 3 4 5
2 9 5 3 8
7 5 4 0 1
6 7 3 2 0
3 1 6 7 9 ];
Y = nan( size(X) );
for jj = 1 : size( X, 2)
isdub = X( :, jj ) == jj;
if any( isdub(2:end) )
col = X(:,jj);
col( isdub ) = [];
Y(:,jj) = cat( 1, col, zeros(sum(isdub),1) );
else
Y(:,jj) = X(:,jj);
end
end
result
>> Y
Y =
1 2 5 4 5
2 9 4 3 8
7 5 6 0 1
6 7 0 2 0
3 1 0 7 9
>>
This code trades performance for readability.
 
Requirement of comment: "modify the codes ... keep the one in the first row and only remove the other one"
Y = nan( size(X) );
for jj = 1 : size( X, 2)
col = X(2:end,jj);
isdub = col == jj;
if any( isdub )
col( isdub ) = [];
Y(:,jj) = cat( 1, jj, col, zeros(sum(isdub),1) );
else
Y(:,jj) = X(:,jj);
end
end
result
>> Y
Y =
1 2 3 4 5
2 9 5 3 8
7 5 4 0 1
6 7 6 2 0
3 1 0 7 9
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!