reorganize two related matrices in ascending order

2 ビュー (過去 30 日間)
Tomás Nunes
Tomás Nunes 2018 年 4 月 16 日
コメント済み: dpb 2018 年 4 月 19 日
I have two matrices, one with -1 and 1's and another with returns that are related to the number in the previous matrix. However, the -1 and 1's aren't organized, in the sense that their position varies in each row. What I pretend is a matrix with the -1's in the first couple of rows and the 1's in the last ones, given that the returns in the second matrix change positions as well. For example:
-1 1 -1 1
-1 -1 1 1
1 1 -1 -1
1 -1 1 -1
0.1 -0.3 2 0.5
-0.9 0 1 1.5
1.5 1.2 0 -0.3
0.9 0.1 1.2 0.3
and I wish to have:
-1 -1 1 1
-1 -1 1 1
-1 -1 1 1
-1 -1 1 1
0.1 2 -0.3 0.5
-0.9 0 1 1.5
0 -0.3 1.5 1.2
0.1 0.3 0.9 1.2
is this possible? I hope I was clear. Thank you

採用された回答

Stephen23
Stephen23 2018 年 4 月 19 日
編集済み: Stephen23 2018 年 4 月 19 日

This is easy with sub2ind:

>> A0 = [-1,1,-1,1;-1,-1,1,1;1,1,-1,-1;1,-1,1,-1]
A0 =
  -1   1  -1   1
  -1  -1   1   1
   1   1  -1  -1
   1  -1   1  -1
>> B0 = [0.1,-0.3,2,0.5;-0.9,0,1,1.5;1.5,1.2,0,-0.3;0.9,0.1,1.2,0.3]
B0 =
   0.10000  -0.30000   2.00000   0.50000
  -0.90000   0.00000   1.00000   1.50000
   1.50000   1.20000   0.00000  -0.30000
   0.90000   0.10000   1.20000   0.30000
>> [A1,idc] = sort(A0,2); % sort, get column indices
>> A1 =
  -1  -1   1   1
  -1  -1   1   1
  -1  -1   1   1
  -1  -1   1   1
>> Sz = size(A0);
>> idr = repmat(1:Sz(1),Sz(2),1).'; % get row indices
>> B1 = B0(sub2ind(Sz,idr,idc)) % convert column&row indices to linear.
B1 =
   0.10000   2.00000  -0.30000   0.50000
  -0.90000   0.00000   1.00000   1.50000
   0.00000  -0.30000   1.50000   1.20000
   0.10000   0.30000   0.90000   1.20000
  1 件のコメント
dpb
dpb 2018 年 4 月 19 日
Good on ya' Stephen, for repmat; I kept trying to be excessively klever in applying sub2ind w/ just the single vector...

サインインしてコメントする。

その他の回答 (1 件)

dpb
dpb 2018 年 4 月 16 日
[A,ix]=sort(A,2);
for i=1:size(A,1), B(i,:)=B(i,ix(i,:)); end

Bound to be a way to write the indexing but it's not coming to me at the moment...

カテゴリ

Help Center および File ExchangeFinancial Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by