Sort a vector according to another vector

조회 수: 59 (최근 30일)
Mohsen Rajaei
Mohsen Rajaei 2014년 3월 4일
편집: JONATAN RODRIGUEZ VAZQUEZ 2021년 6월 13일
Hi
I have tow vectors A and B:
A = [4 8 5 9 1]
B = [3 5 4 2 1]
If I sort A with B like this:
C = A(B)
I will get:
C = [5 1 9 8 4]
But I want C like this:
C = [1 9 4 5 8]
How can I do that?
Thank you, M. Rajaei

채택된 답변

lvn
lvn 2014년 3월 4일
[~,Bsort]=sort(B); %Get the order of B
C=A(Bsort)
C =
1 9 4 5 8
  댓글 수: 2
Mohsen Rajaei
Mohsen Rajaei 2014년 3월 4일
OK. Thank you so much. I got it.
JONATAN RODRIGUEZ VAZQUEZ
JONATAN RODRIGUEZ VAZQUEZ 2021년 6월 13일
편집: JONATAN RODRIGUEZ VAZQUEZ 2021년 6월 13일
how can you do the same thing with n x 2 array?
I do it like this
vectors = [3 4;5 12];
modules = [5;13];
[~,modulesSort] = sort(modules); %Get the order of B
%C=A(modulesSort); %not works
% do this
vectorsSortedByModule = vectors(modulesSort,:);

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

추가 답변 (0개)

카테고리

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