2015-04-29 1804 views
2

我有一個向量A = [ 1 1 1 2 3 3 3 2 2 1 1 1 1 3 3 3 ]在Matlab中查找矩陣中重複元素的位置

我想找到每個元素的位置並將其存儲在它自己的矩陣中。更具體地說,我想要找出每個元素集合中每個元素的位置,在一個m矩陣中(其中m是元素的類型,n是在向量中找到的元素的數量)一個)。因此,例如,假設向量A中只有值1,2和3,我的矩陣的第一列將是值爲1的值,並且將讀取(1,2,3,10,..., ,11,12,13),第二列的數值爲2時將讀取(4,8,9),第三列的值爲3時讀取(5,6,7,14,15 ,16)。

+0

矩陣中的每一行和每列應該有相同的長度。你的專欄沒有。你想用零/ NaN填充矩陣的其餘部分,還是爲每一列使用單元陣列? – David

+0

哦,我沒有想到,單元陣列,我的壞。 – genap

回答

3

這一個班輪按預期工作:

B = accumarray(A', 1:length(A), [], @(x) {sort(x)}) 

B是一個單元陣列,其中B{i}包含其中i位於指數的排序列表。

+0

它爲什麼有效? – genap

+0

'accumarray'是一個奇妙的功能,我建議[你閱讀它的文檔](http://www.mathworks.com/help/matlab/ref/accumarray.html)。基本上,它將所有元素的索引作爲一個向量'x'輸入到函數'@(x){sort(x)}'中,並將結果賦給'B'的位置'i'。 – Simon

1

Divakar's answersort

[out,i] = sort(A); 
out1 = diff(find([1,diff(out)])); 
out2 = [out1,numel(A)-sum(out1(:))]; 
out3 = mat2cell(i,1,out2); 

結果類似:

A = [ 1 1 1 2 3 3 3 2 2 1 1 1 1 3 3 3 ]; %// input 

>> celldisp(out3) 

out3{1} = 

1  2  3 10 11 12 13 


out3{2} = 

4  8  9 


out3{3} = 

5  6  7 14 15 16 
3

這可能是一個辦法 -

%// For each element create a pair: [R,C], where the first element R would 
%// represent its index position in input array and C would be their uniqueness 
[R,C] = find(bsxfun(@eq,A(:),unique(A(:).'))) %//' 

%// Find lengths of each unique group 
lens = diff([0 ; find(diff(C)) ; numel(C)]) 

%// Store each element into groups based on the uniqueness and whose 
%// values would be the index positions i.e. taken from R 
out = mat2cell(R(:).',1,lens) 

對於給定的輸入採樣運行 -

>> A 
A = 
    1  1  1  2  3  3  3  2  2 ... 
          1  1  1  1  3  3  3 
>> celldisp(out) 
out{1} = 
    1  2  3 10 11 12 13 
out{2} = 
    4  8  9 
out{3} = 
    5  6  7 14 15 16 
+0

不錯+1 :)順便說一句,可能可以使用'[C,R] = sort(A);'? –

+1

@SanthanSalai不錯!你知道你應該將其作爲解決方案發布,因爲它可能非常有效! – Divakar

+0

我做到了。但大部分的答案是從你的想法..謝謝:) –