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
0 个评论
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!