How to order a matrix?
이전 댓글 표시
Hello,
I have a matrix,
A=[ 100 5 0 ; 200 0 -5 ; 300 0 0 ; 300 5 0 ; -100 0 5 ; 300 0 0; 300 0 5];
I want to get,
A= [100 5 0; 200 0 -5 ; 300 0 0; 300 5 0 ; 300 0 5 ; -100 0 5];
I am writing code:
B= unique(A(:, 2:3),'rows');
then it's removing the first row as 5 0 is also repeted for the 4th row 300 5 0 but I need to keep the 1st row.
Is it possible to do?
댓글 수: 4
Adam
2019년 4월 23일
What is wrong with just using
B = unique( A, 'rows' )
or
B = unique( A, 'rows', 'stable' )
though your chosen output ordering does not match either unique's sorted output nor its stable output which retains the original ordering.
Your version using 2:3 won't do this though either.
You can sort the output to your desired ordering afterwards though.
Sky Scrapper
2019년 4월 23일
Adam
2019년 4월 23일
It's not really obvious from your example what you are trying to achieve in a more general case. Your example just removes one row (which can be removed by using just a simple unique as mentioned) and then orders the remaining ones in a fairly unintuitive manner with respect to how they started.
What are you actually trying to keep? If you are trying to keep all unique rows then what I wrote works fine, if you are really trying to only run a unique on the 2nd and 3rd columns then your version does that, but from what you say, that isn't what you want to do.
Sky Scrapper
2019년 4월 23일
답변 (2개)
Alex Mcaulley
2019년 4월 23일
편집: Alex Mcaulley
2019년 4월 23일
Try this:
[~,ia,~] = unique(A(:, 2:3),'rows','stable');
B = A(ia,:);
댓글 수: 7
Sky Scrapper
2019년 4월 23일
Sky Scrapper
2019년 4월 23일
Sky Scrapper
2019년 4월 23일
Alex Mcaulley
2019년 4월 23일
A = [ 100 5 0 ; 200 0 -5 ; 300 0 0 ; 300 5 0 ; -100 0 5 ; 300 0 0; 300 0 5];
[~,ia,~] = unique(A(:, 2:3),'rows','stable');
B = A(ia,:)
B =
100 5 0
200 0 -5
300 0 0
-100 0 5
It keeps the first column! And remove the repeated rows
Sky Scrapper
2019년 4월 23일
Alex Mcaulley
2019년 4월 23일
Using round
If you want to round the first column:
A = [ 100 5 0 ; 200 0 -5 ; 300 0 0 ; 300 5 0 ; -100 0 5 ; 300 0 0; 300 0 5];
A(:,1) = round(A(:,1),-2);
[~,ia,~] = unique(A(:, 2:3),'rows','stable');
B = A(ia,:);
Sky Scrapper
2019년 4월 23일
카테고리
도움말 센터 및 File Exchange에서 Set Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!