Changing order of elements of one vector depending on the order of another vector

조회 수: 35 (최근 30일)
Hi
I have two vectors, say:
a = [0.1 0.4 0.2 0.9 2]
b = [5 10 11 2 4]
I want to order a, such that the vector would start with the smallest element, and finish with the largest, like this:
a = [0.1 0.2 0.4 0.9 2]
Not that now element 2 and 3 of the vector a have been swapped for this purpose. Now I want to somehow swap the elements of b exactly as the elements of a where swapped (so the new b would be b = [5 11 10 2 4]). How can I do that systematically? Many thanks

채택된 답변

Adam
Adam 2017년 6월 23일
편집: Adam 2017년 6월 23일
[sortedA, idx] = sort( a );
sortedB = b(idx);
When you look at something like
doc sort
which, by the way, is the obvious first place to search when you want to do something like this, always take note of all the different calling syntaxes for a function. So many questions are asked that turn out to just be a case of someone not looking far enough down the help page.
In particular, in cases like this, take note of all the output arguments, not just the first. Functions like sort (and unique and various others that change an array in some way or other) usually also return a set of indices that can be applied to another vector to achieve the same sorting (or whatever shuffling of the elements of the array took place).

추가 답변 (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