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

37 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Adam
Adam am 23 Jun. 2017
Bearbeitet: Adam am 23 Jun. 2017
[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).

Weitere Antworten (0)

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by