Removing repeated numbers in a matrix

조회 수: 3 (최근 30일)
AA
AA 2020년 8월 23일
댓글: Bruno Luong 2020년 8월 23일
Ex: In a matrix
A = [9 9 1 1 2 2 2 2 2 0 3 3; 7 7 4 4 4 5 5 6 6 6 6 6 ; 8 8 7 7 7 8 8 8 9 9 9 5]
, i want to eliminate all repeating elements and retain non-repeating elements
i.e. from the above example
A = [9 1 2 0 3 ; 7 4 5 6 ; 8 7 8 9 5]
To prevent a dimensions error because of different output results, the remaining entries on the left can be filled by zero like here
A = [9 1 2 0 3 ; 7 4 5 6 0 ; 8 7 8 9 5]

채택된 답변

Stephen23
Stephen23 2020년 8월 23일
편집: Stephen23 2020년 8월 23일
>> A = [9,9,1,1,2,2,2,2,2,0,3,3;7,7,4,4,4,5,5,6,6,6,6,6;8,8,7,7,7,8,8,8,9,9,9,5]
A =
9 9 1 1 2 2 2 2 2 0 3 3
7 7 4 4 4 5 5 6 6 6 6 6
8 8 7 7 7 8 8 8 9 9 9 5
>> X = diff(A(:,[1,1:end]),1,2)~=0;
>> X(:,1) = true;
>> S = size(A);
>> [R,~] = ndgrid(1:S(1),1:S(2));
>> C = cumsum(+X,2);
Method one: accumarray:
>> B = accumarray([R(:),C(:)],A(:),[],@mode,0)
B =
9 1 2 0 3
7 4 5 6 0
8 7 8 9 5
Method two: indexing:
>> B = zeros(S(1),max(C(:)));
>> B(sub2ind(S,R,C)) = A
B =
9 1 2 0 3
7 4 5 6 0
8 7 8 9 5

추가 답변 (1개)

KSSV
KSSV 2020년 8월 23일
편집: KSSV 2020년 8월 23일
A = [9 9 1 1 2 2 2 2 2 0 3 3; 7 7 4 4 4 5 5 6 6 6 6 6 ; 8 8 7 7 7 8 8 8 9 9 9 5] ;
[m,n] = size(A) ;
C = cell(m,1) ;
for i = 1:m
C{i} = unique(A(i,:)) ;
end
L = cellfun(@length,C) ;
B = zeros(m,max(L)) ;
for i = 1:m
B(i,1:L(i)) = C{i} ;
end
  댓글 수: 4
Stephen23
Stephen23 2020년 8월 23일
편집: Stephen23 2020년 8월 23일
"Easy to fix with 'stable' option"
Nope, not fixed. Lets try it:
>> c = arrayfun(@(r) unique(A(r,:),'stable'), 1:size(A,1), 'unif', 0);
>> n = max(cellfun(@length,c));
>> B = cell2mat(cellfun(@(x) [x,zeros(1,n-length(x))], c, 'unif', 0)')
B =
9 1 2 0 3
7 4 5 6 0
8 7 9 5 0
Note that the last row differs from the expected output given in the original question:
9 1 2 0 3
7 4 5 6 0
8 7 8 9 5
Bruno Luong
Bruno Luong 2020년 8월 23일
You are absolutely right.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Types에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by