Sort the array by template
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Rostislav Teryaev
il 23 Mag 2018
Commentato: Ameer Hamza
il 23 Mag 2018
I have two arrays A1 and B1 in which elements correspond:
A1 = [a1 a2 a3 a4 a5];
B1 = [b1 b2 b3 b4 b5];
then I change order of elements of the first array anyhow (they are all unique), for exaple like this:
A2 = [a4 a1 a3 a5 a2];
The question is how to get array B2 sorted in the same way? It should be
B2 = [b4 b1 b3 b5 b2];
I tried to write function which is:
B2 = zeros(length(B1),1);
for i = 1:length(B2)
ind = find( A1 == A2(i) );
B2(i) = B1(ind);
end
but as it uses for loops speed is not fast. Maybe there is a way to do it by using MatLab builtin functions?
0 Commenti
Risposta accettata
Ameer Hamza
il 23 Mag 2018
Modificato: Ameer Hamza
il 23 Mag 2018
For a generalized matrix a1 and a2, you can use the following code
[~,index] = ismember(a2', a1', 'row');
b2 = b1(index)
This will work on R2016b and later.
8 Commenti
Ameer Hamza
il 23 Mag 2018
You will get hold of such solution once you start to develop some intuition about these frequently used MATLAB functions. Of course, that comes with time, experience and reading a lot of documentation :)
Più risposte (1)
sloppydisk
il 23 Mag 2018
a1 = [1 4 2 5 7];
b1 = 1:5;
mySecretOrder = [1 3 2 5 4];
a2 = a1(mySecretOrder);
[~, order] = ismember(a2, a1)
b1 = b1(order)
2 Commenti
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!