MATLAB Answers

0

How to order a matrix?

Asked by Sky Scrapper on 23 Apr 2019 at 10:06
Latest activity Commented on by Sky Scrapper on 23 Apr 2019 at 13:08
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 Comments

Show 1 older comment
My original matrix is 1000x20
what i have given in the question is the 1st four columns.I need to keep the corresponding whole columns. so what I did,
[~,idy,idx] = unique(A(:,2:3),'rows','stable');
B =A(idy,:);
then it's showing 1st row but it's also showing the repeted rows for 300 0 0 and so on.
Could you please clarify where is the mistake?
Adam
on 23 Apr 2019 at 12:25
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.
I could solve my problem. thanks for helping me!

Sign in to comment.

Tags

2 Answers

Answer by Alex Mcaulley on 23 Apr 2019 at 10:13
Edited by Alex Mcaulley on 23 Apr 2019 at 10:22

Try this:
[~,ia,~] = unique(A(:, 2:3),'rows','stable');
B = A(ia,:);

  7 Comments

Yes, I got the solution of my problem. i need to take the tolerance of my values because i have some fractional values.
Thank you very much for your help.
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,:);
I have already done this. Again thanks a lot!

Sign in to comment.


Answer by Guillaume
on 23 Apr 2019 at 13:04

how can i do that?
Use uniquetol instead of unique. Note that the 'rows' option of unique is 'ByRows', true with uniquetol
[~, irows] = uniquetol(A(:, [2 3]), 'ByRows', true); %if you are happy with the default tolerance
B = A(irows, :);

  1 Comment

Yes, i have already done that.
I had to take tolerance=0.02
Thank you very much for your kind support.

Sign in to comment.