How to delete duplicate values in a column
조회 수: 2 (최근 30일)
이전 댓글 표시
Matrix A is as follows:
A = [10023 10024 10025 10026 10027
1 1 1 1 1
1 1 1 1 1
1 1 2 1 1
2 3 2 5 1
2 3 2 5 2
4 3 4 5 1
4 3 4 6 1
1 3 4 6 1
1 1 1 1 1];
I want to remove the duplicate number in each column and produce the new matrix B like following:
B = [10023 10024 10025 10026 10027
1 1 1 1 1
2 3 2 5 2
4 1 4 6 1
1 0 1 1 0];
% The zero are added to ID numbers 10024 & 10027 in order to keep the consistenty of matrix B dimension.
댓글 수: 0
답변 (1개)
Image Analyst
2016년 12월 10일
This works:
A = [10023 10024 10025 10026 10027
1 1 1 1 1
1 1 1 1 1
1 1 2 1 1
2 3 2 5 1
2 3 2 5 2
4 3 4 5 1
4 3 4 6 1
1 3 4 6 1
1 1 1 1 1]
B = zeros(size(A));
for col = 1 : size(A, 2)
thisCol = A(:, col);
thisCol(diff(thisCol) == 0) = []; % Remove repeats.
B(1:length(thisCol), col) = thisCol;
end
% Trim off all zero rows
lastRow = find(all(B==0, 2), 1, 'first')-1;
B = B(1:lastRow, :)
댓글 수: 8
Image Analyst
2016년 12월 11일
Well what did you try? Did you get anything like this:
A = [10023 10024 10025 10026 10027
1 1 1 1 1
1 1 1 1 1
1 1 2 1 1
2 3 2 5 1
2 3 2 5 2
4 3 4 5 1
4 3 4 6 1
1 3 4 6 1
1 1 1 1 1]
B = zeros(size(A));
for col = 1 : size(A, 2)
thisCol = A(:, col);
thisCol(diff(thisCol) == 0) = []; % Remove repeats.
B(1:length(thisCol), col) = thisCol;
end
% Trim off all zero rows
lastRow = find(all(B==0, 2), 1, 'first')-1;
B = B(1:lastRow, :)'
bRight = B(:, 2 : end)
B2 = unique(bRight, 'rows')
% Go down these rows finding out all the rows that have the row
for row = 1 : size(B2, 1)
thisRow = B2(row, :)
[ia, ib] = ismember(bRight, thisRow, 'rows')
extractedRows = B(ia, :)';
T{row} = extractedRows;
end
celldisp(T)
And you'll see:
T =
1×4 cell array
[5×1 double] [5×2 double] [5×1 double] [5×1 double]
T{1} =
10027
1
2
1
0
T{2} =
10023 10025
1 1
2 2
4 4
1 1
T{3} =
10024
1
3
1
0
T{4} =
10026
1
5
6
1
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!