Sorting Data in MAtrix1 referencing matrix2
8 ビュー (過去 30 日間)
古いコメントを表示
Hello, I have dataset A which is a 326x1 matrix that needs to be sorted. I have a reference matrix B, that is 300x2. Each data point in A is paired with another data point within A. The pairing is determined by the pairing across columns in B. How do I generate Apaired which is a 163x2 matrix correctly paired according to B?
Thanks for helping an inexperienced matlaber!
1 件のコメント
dpb
2017 年 6 月 29 日
Don't follow the arrangement described, sorry. Show us 10 or so elements of the two files as example and then the expected output.
How does the difference in lengths work (although perhaps it will become clear if we see the above example).
回答 (3 件)
Andrei Bobrov
2017 年 6 月 30 日
n = numel(B);
b0 = interp1((1:n)',B(:),linspace(1,n,numel(A))');
[~,i0] = sort(b0);
a0 = sort(A);
[~,i1] = sort(i0);
Apaired = reshape(a0(i1),[],2);
0 件のコメント
Jan
2017 年 6 月 30 日
編集済み: Jan
2017 年 6 月 30 日
I'm not sure if I understand the question correctly. This code searches for occurrences of the elements of A in B(:, 1) and creates the matrix Apaired consisting of the found elements in the 1st column and the corresponding elements of B(:, 2) in the 2nd column:
[LiA, LocB] = ismember(A, B(:, 1));
Apaired = [A(LiA), B(LocB(LiA), 2)]
If John BG's answer produces the wanted result, use this much more efficient version:
A2 = A(B)
It is a good programing practice to avoid the iterative growing of an array, because this is extremely expensive. You see a corresponding MLint warning in the editor and should consider this hint carefully.
0 件のコメント
John BG
2017 年 6 月 29 日
編集済み: John BG
2017 年 6 月 30 日
Hi Matt
1.
Let be a shorter sample of data to illustrate how to generate the sought vector:
A=randi([-10 10],1,10) % data matrix
=
-7 3 8 0 4 -7 10 1 4 -10
2.
generating the indexing matrix
B=randi([1 size(A,2)],2,9) % pairing matrix
=
9 2 4 4 2 1 7 2 8
8 6 6 5 3 10 10 10 6
3.
pairing A according to B
[s1 s2]=size(B)
A2=[0;0]
for k=1:1:s2
B0=[A(B(1,k)); A(B(2,k))];
A2=[A2 B0];
end
A2(:,1)=[];
A2
A2 =
4 3 0 0 3 -7 10 3 1
1 -7 -7 4 8 -10 -10 -10 -7
if you find this answer useful would you please be so kind to consider marking my answer as Accepted Answer?
To any other reader, if you find this answer useful please consider clicking on the thumbs-up vote link
thanks in advance
John BG
参考
カテゴリ
Help Center および File Exchange で Resizing and Reshaping Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!