Reordering a vector in matlab?

I have a vector in matlab of Bdimension nx1that contains integers from 1to nin a specific order, for example. n=6 B=(2;4;5;1;6;3).

I have a vector of Adimension mx1c m>1, which contains the same integers in ascending order, each of which is repeated an arbitrary number of times, for example. m=13 A=(1;1;1;2;3;3;3;4;5;5;5;5;6).

I want to get a Cdimension mx1in which the integers in Areorder after order in B. In this exampleC=(2;4;5;5;5;5;1;1;1;6;3;3;3)

+4
source share
4 answers

One approach with ismemberand sort-

[~,idx] = ismember(A,B)
[~,sorted_idx] = sort(idx)
C = B(idx(sorted_idx))

, bsxfun -

C = B(nonzeros(bsxfun(@times,bsxfun(@eq,A,B.'),1:numel(B))))
+5

sort :

ind = 1:numel(B);
ind(B) = ind;
C = B(sort(ind(A)));
+3

Another approach using repelem, accumarray,unique

B=[2;4;5;1;6;3];
A=[1;1;1;2;3;3;3;4;5;5;5;5;6];

counts = accumarray(A,A)./unique(A);
repelem(B,counts(B));

%// or as suggested by Divakar 
%// counts = accumarray(A,1);
%// repelem(B,counts(B));

PS:repelem was introduced to . If you are using a previous version, see here R2015a

+2
source

Another solution using hist, but with a loop and expanding memory :(

y = hist(A, max(A))
reps = y(B);
C = [];
for nn = 1:numel(reps)
    C = [C; repmat(B(nn), reps(nn), 1)];
end
0
source

Source: https://habr.com/ru/post/1584187/


All Articles