How to arrange elements in one array to match the position of elements in a second array?
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Tatiana
am 1 Apr. 2025
Kommentiert: Tatiana
am 1 Apr. 2025
If I have two arrays A and B as displayed below, how can I rearrange B such that a new boolean array Ba which corresponds to the values of array B can be resorted according to the values of array A instead?
For example, if I have:
A =
1 5 3 2 4 4 2 2 3 5
2 1 1 2 0 1 1 1 0 0
30 22 23 25 -1 30 18 25 -1 -1
B =
1 2 2 2 3 3 4 4 5 5
2 1 1 2 0 1 0 1 0 1
30 18 25 25 -1 23 -1 30 -1 22
Ba =
0 0 1 0 1 0 0 0 0 0
Note that array B is simply the sorted version of array A according to the first row in an ascended order. It is resorted twice according to the second row in an ascended order for the values in row 1 that equal one another (e.g., if there are multiples elements equal to 3 in row 1, then the array will sort by the second row instead, so if the second row has values 3 3 3 3 3; 2 6 3 9 1, it will then be sorted to 3 3 3 3 3; 1 2 3 6 9)
I only mentioned this in case reverse sorting might work easier than entirely rearranging the position of the array.
I want to rearrange array B and Ba such that it corresponds to the positioning of array A.
So the new arrays would look like this:
A =
1 5 3 2 4 4 2 2 3 5
2 1 1 2 0 1 1 1 0 0
30 22 23 25 -1 30 18 25 -1 -1
Aa =
0 0 0 0 0 0 0 1 1 0
The new array would essentially match A, and the array Aa is the same array Ba but now rearranged so that it follows the arrangement of A rather than B.
I am not entirely sure how to write the MATLAB code to accomplish this. All help is appreciated!
0 Kommentare
Akzeptierte Antwort
Stephen23
am 1 Apr. 2025
Bearbeitet: Stephen23
am 1 Apr. 2025
You could find the mapping with ISMEMBER:
A = [1,5,3,2,4,4,2,2,3,5; 2,1,1,2,0,1,1,1,0,0; 30,22,23,25,-1,30,18,25,-1,-1]
B = [1,2,2,2,3,3,4,4,5,5; 2,1,1,2,0,1,0,1,0,1; 30,18,25,25,-1,23,-1,30,-1,22]
Ba = [0,0,1,0,1,0,0,0,0,0]
Obtain the 2nd output from ISMEMBER:
[~,idx] = ismember(A.',B.','rows');
Reorder using indexing:
Aa = Ba(idx)
Anew = B(:,idx)
Weitere Antworten (1)
Steven Lord
am 1 Apr. 2025
Here's your sample data.
A = [1 5 3 2 4 4 2 2 3 5
2 1 1 2 0 1 1 1 0 0
30 22 23 25 -1 30 18 25 -1 -1];
B = [1 2 2 2 3 3 4 4 5 5
2 1 1 2 0 1 0 1 0 1
30 18 25 25 -1 23 -1 30 -1 22];
Ba =[0 0 1 0 1 0 0 0 0 0];
Aa =[0 0 0 0 0 0 0 1 1 0];
Call sortrows on the transpose of A then transpose the result back.
[B1, indices] = sortrows(A.');
Let's check that the output from sortrows matches the hard-coded expected result from the sample data.
check = isequal(B, B1.')
You can use the second output to reorder Aa to generate Ba.
isequal(Ba, Aa(indices))
0 Kommentare
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!