set unique values in matrix for each column new to 0

2 次查看(过去 30 天)
Hi,
I want to set the dublicate values to zero:
The problem with this code is that it sets all duplicate values ​​to 0, even across columns. I want the duplicate values ​​to be removed only per column E.g. the error in my code:
0 0 0
0 0 1
1 0 2
2 1 3
2 2 4
2 2 4
is going to
0 0 0
0 0 0
1 0 0
2 0 3
0 0 4
0 0 0
I want
0 0 0
0 0 1
1 0 2
2 1 3
0 2 4
0 0 0
DOK_HQ10000_FD_zeitlich_neu= zeros(size(DOK_HQ10000_FD_zeitlich))
[~,pos] = unique(DOK_HQ10000_FD_zeitlich,'first')
DOK_HQ10000_FD_zeitlich_neu(pos)=DOK_HQ10000_FD_zeitlich(pos)

采纳的回答

Ruchika P Barman
Ruchika P Barman 2022-7-13
It is my understanding that you are trying to set the duplicate values to zero considering the elements columnwise in the matrix.
M = [0 0 0 ; 0 0 1; 1 0 2 ; 2 1 3 ; 2 2 4 ; 2 2 4]
M = 6×3
0 0 0 0 0 1 1 0 2 2 1 3 2 2 4 2 2 4
ans1=[];
[~,col]=size(M);
for c=1:col
x=(M(:,c))';
y = [x(1) diff(x)];
y = find(y==0);
z = x;
z(y)=0;
ans1 = [ans1;z];
end
ans1=ans1'
ans1 = 6×3
0 0 0 0 0 1 1 0 2 2 1 3 0 2 4 0 0 0
This should solve your problem, thank you.

更多回答(3 个)

Bruno Luong
Bruno Luong 2022-7-13
It looks like your repeated elemenst are adjacent
M = [0 0 0 ; 0 0 1; 1 0 2 ; 2 1 3 ; 2 2 4 ; 2 2 4]
M = 6×3
0 0 0 0 0 1 1 0 2 2 1 3 2 2 4 2 2 4
M.*(diff([nan(size(M(1,:))); M],1,1)~=0)
ans = 6×3
0 0 0 0 0 1 1 0 2 2 1 3 0 2 4 0 0 0

Bruno Luong
Bruno Luong 2022-7-13
This works for repeated elements that are in any order in the columns
M = randi(4,10,3)
M = 10×3
3 1 3 1 2 4 2 3 3 3 2 4 3 3 4 4 3 1 4 1 2 2 2 4 4 4 2 2 3 1
[m,n]=size(M);
IJ = cell(n,1);
v = cell(n,1);
for j=1:n
[v{j},IJ{j}] = unique(M(:,j),'stable');
IJ{j}(:,2)=j;
end
accumarray(cat(1,IJ{:}), cat(1,v{:}), [m,n])
ans = 10×3
3 1 3 1 2 4 2 3 0 0 0 0 0 0 0 4 0 1 0 0 2 0 0 0 0 4 0 0 0 0

Bruno Luong
Bruno Luong 2022-7-13
编辑:Bruno Luong 2022-7-13
Another solution without assum^tion of M is sorted by column
M = randi(4,10,3)
M = 10×3
1 4 2 2 2 2 4 2 3 2 4 3 1 2 2 3 3 1 2 4 3 1 2 4 2 2 1 1 2 1
[m,n]=size(M);
[S,i] = sort(M);
M(i+(0:n-1)*m) = S.*~~[true(1,n);diff(S)]
M = 10×3
1 4 2 2 2 0 4 0 3 0 0 0 0 0 0 3 3 1 0 0 0 0 0 4 0 0 0 0 0 0

类别

Help CenterFile Exchange 中查找有关 Biological and Health Sciences 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by