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!