Sort rows of a matrix based on a specific array

조회 수: 1 (최근 30일)
Amirhossein Moosavi
Amirhossein Moosavi 2020년 7월 13일
댓글: madhan ravi 2020년 7월 13일
Hi everyone,
Let us assum Matrix A and array B as follows:
A = [1 0 1
2 0 0
4 0 0
3 1 1
6 0 0
5 0 0]
B = [3 4 1]
Array B always include values stored in the first column of Matrix A. So, I want to sort rows of Matrix A based on Array B. Whatever comes first in Array B must come first in Matrix A. Moreover, I do not want to change the position of any other rows in Matrix A that their values (first column) do not exist in Array B.
Having said this, sorted version of Matrix A based on Array B will be as follows:
An = [3 1 1
2 0 0
4 0 0
1 0 1
6 0 0
5 0 0]
Would you please guide me what is the fastest way to do this?
Regards,
Amir

채택된 답변

Stephen23
Stephen23 2020년 7월 13일
편집: Stephen23 2020년 7월 13일
>> [X,Y] = ismember(A(:,1),B);
>> [~,Z] = sort(Y(X));
>> T = A(X,:);
>> A(X,:) = T(Z,:)
A =
3 1 1
2 0 0
4 0 0
1 0 1
6 0 0
5 0 0

추가 답변 (1개)

madhan ravi
madhan ravi 2020년 7월 13일
v = sort(B);
A([1, v(end)], :) = A([v(end), 1], :)
  댓글 수: 2
Amirhossein Moosavi
Amirhossein Moosavi 2020년 7월 13일
Thank you, but it does not work for some cases. Let us say Array B is as follows:
B = [3 4]
Then, Matrix A becomes like this (using your code):
A = [3 1 1
2 0 0
4 0 0
1 0 1
6 0 0
5 0 0]
While, Matrix A must have become as follows:
A = [1 0 1
2 0 0
3 1 1
4 0 0
6 0 0
5 0 0]
madhan ravi
madhan ravi 2020년 7월 13일
I misunderstood the question.

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

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by