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

42 次查看(过去 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