2015-04-23 64 views
4

我有一個維度爲nx1的Matlab B中的矢量,它包含從1n的整數。 n=6 B=(2;4;5;1;6;3)在Matlab中重新排序矢量?

我有尺寸mx1的向量Am>1包含以升序相同的整數每一個重複任意次數,例如m=13A=(1;1;1;2;3;3;3;4;5;5;5;5;6)

我想要得到尺寸爲mx1C,其中A中的整數按照B中的順序重新排序。在這個例子中,與ismemberC=(2;4;5;5;5;5;1;1;1;6;3;3;3)

回答

5

一種方法和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)))) 
+0

嵌套'bsxfun'。 (Y) –

0

使用hist另一種解決方案,但帶有循環和擴展內存:(

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

使用的另一種方法repelemaccumarrayunique

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:repelemR2015a引入。如果您使用的是以前的版本,請參閱here

+1

如果OP無法訪問'repelem'的2015a,請將其鏈接到[this one](http://stackoverflow.com/q/1975772/3293881)? – Divakar

+0

@Divakar y不?即使我使用R2014a,我也沒有測試最後一行LOL。 –

+1

想一想,你可以分兩步來做:'count = accumarray(A,1); C =重複(B,計數(B))'。 – Divakar

3

這僅需要一個sort和索引:

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