Reorder a matrix relative to another

조회 수: 12 (최근 30일)
Matthew
Matthew 2015년 3월 2일
편집: Stephen23 2015년 3월 2일
I have investigated all day the different ways to do this, and I have not been able to come up with a plan to achieve exactly what i need. Below are my sample matrices.
a=[5;20;50;30;10]
index=[1;2;3;4;5]
b=[10;50;5;20;50]
c=[44;22;11;88;55]
"a" and "index" are the proper order of the matrix. Matrix "b" is identical is size and shape, but the values are scrambled in order. I need a way to establish an order to move "b" to look like "a", and then apply that reordering pattern to "c". The only matrix i am interested in is the reordered "c"
In the end i want the new reordered matrix to be the following:
cReordered=[11;88;22;55;44]
I am looking for the most efficient way to do this.
I have used:
[bnew, ia, ib] = intersect(a, b, 'stable')
but it only reorders "b", by generating a "bnew". and this will match the pattern in "a", but that is all.
Any advice would be appreciated. thank you.
  댓글 수: 2
Stephen23
Stephen23 2015년 3월 2일
편집: Stephen23 2015년 3월 2일
Are the values in a, b, and index unique? It seems that the vector b should actually be
b = [10;50;5;20;30];
(i.e. replacing the second 50 with 30), is this correct?
Matthew
Matthew 2015년 3월 2일
Sorry i typed that wrong. Yes, the values in a and values in b will be identical, just those in b will be out of order.
b=[10;50;5;20,30]

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

채택된 답변

Stephen23
Stephen23 2015년 3월 2일
편집: Stephen23 2015년 3월 2일
Assuming that the values in both of a and b are unique, and that they each contain exactly the same values, then the vector b original question needs have the second 50 replaced with a 30, like this:
>> a = [5;20;50;30;10];
>> x = [1;2;3;4;5];
>> b = [10;50;5;20;30];
>> c = [44;22;11;88;55];
Then the solution is very easy using MATLAB's indexing ability:
>> [~,xx] = sort(a);
>> [~,yy] = sort(b);
>> d(xx) = c(yy)
d =
11 88 22 55 44
Which matches the desired output [11;88;22;55;44]. Note that this requires that the values in a and b are unique!

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by