简体   繁体   中英

MATLAB: Sort a 3d array by another 3d array

I have a 3d array A of random numbers which I'd like to order each k'th dimension individually:

A=rand(3,1,16);
[m, n, k]=size(A);

The array that dictates the order of each matrix in the 3rd dimension is B:

B=randi(3,3,1,16); %this should be without replacement but think it will work anyway

If A(:,1,1)=[0.5, 0.2, 0.6]' and B(:,1,1)=[3,1,2] then the ordered A should be [0.2, 0.6, 0.5]' and so on for each A(:,1,1:k). Please note it's not ordering A numerically.

A(B) is what I might have expected to work and keeps the dimensions but not the right orders.

I've tried to work through this: https://uk.mathworks.com/matlabcentral/answers/307838-sort-3d-matrix-according-to-another-3d-matrix without any success.

Any thoughts would be much appreciated.

To sort A along the k -th dimension based on B : if your data is not complex, a simple way is:

  1. Pack A and B into a complex array where A is the imaginary part and B is the real part;
  2. Sort along the k -th dimension based on the real part;
  3. Keep the imaginary part.

This is done in one line as follows:

result = imag(sort(B+1j*A, k, 'ComparisonMethod', 'real'));

Example :

>> A = rand(2,4,3)
A(:,:,1) =
   0.162182308193243   0.311215042044805   0.165648729499781   0.262971284540144
   0.794284540683907   0.528533135506213   0.601981941401637   0.654079098476782
A(:,:,2) =
   0.689214503140008   0.450541598502498   0.228976968716819   0.152378018969223
   0.748151592823709   0.083821377996933   0.913337361501670   0.825816977489547
A(:,:,3) =
   0.538342435260057   0.078175528753184   0.106652770180584   0.004634224134067
   0.996134716626885   0.442678269775446   0.961898080855054   0.774910464711502

>> B = randi(9, size(A))
B(:,:,1) =
     8     1     3     4
     8     4     8     9
B(:,:,2) =
     2     2     8     5
     3     2     6     2
B(:,:,3) =
     8     4     4     3
     6     5     1     2

>> k = 2;

>> result = imag(sort(B+1j*A, k, 'ComparisonMethod', 'real'))
result(:,:,1) =
   0.311215042044805   0.165648729499781   0.262971284540144   0.162182308193243
   0.528533135506213   0.601981941401637   0.794284540683907   0.654079098476782
result(:,:,2) =
   0.450541598502498   0.689214503140008   0.152378018969223   0.228976968716819
   0.083821377996933   0.825816977489547   0.748151592823709   0.913337361501670
result(:,:,3) =
   0.004634224134067   0.078175528753184   0.106652770180584   0.538342435260057
   0.961898080855054   0.774910464711502   0.442678269775446   0.996134716626885

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM