Sorting Data in MAtrix1 referencing matrix2

8 visualizaciones (últimos 30 días)
Matt Mallory
Matt Mallory el 29 de Jun. de 2017
Comentada: Jan el 30 de Jun. de 2017
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 comentario
dpb
dpb el 29 de Jun. de 2017
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).

Iniciar sesión para comentar.

Respuestas (3)

Andrei Bobrov
Andrei Bobrov el 30 de Jun. de 2017
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);

Jan
Jan el 30 de Jun. de 2017
Editada: Jan el 30 de Jun. de 2017
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.

John BG
John BG el 29 de Jun. de 2017
Editada: John BG el 30 de Jun. de 2017
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

Categorías

Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by