2

假設我們有一個陣列如何增加一些元素在由特定值的數組在MATLAB

A = zeros([1,10]); 

我們已經和可能重複的幾個指標說:

indSeq = [1,1,2,3,4,4,4]; 

我們怎樣才能提高A(i)索引序列中的i的數量,即A(1) = 2, A(2) = 1, A(3) = 1, A(4) = 3

代碼A(indSeq) = A(indSeq)+1不起作用。

我知道,我可以使用循環來實現這一目標以下,但我不知道是否有無論如何,我們能避免循環?我們可以假設indSeq已排序。

一個for循環解決方案:

for i=1:length(indSeq) 
    A(indSeq(i)) = A(indSeq(i))+1; 
end; 

回答

3

可以使用accumarray這種基於標籤計數的工作,像這樣 -

accumarray(indSeq(:),1) 

標杆

正如other answer建議,你也可以使用hist/histc。讓我們將這兩個數據基準化爲一個大的數據大小。我所使用的基準測試代碼有 -

%// Create huge random array filled with ints that are duplicated & sorted 
maxn = 100000; 
N = 10000000; 
indSeq = sort(randi(maxn,1,N)); 

disp('--------------------- With HISTC') 
tic,histc(indSeq,unique(indSeq));toc 

disp('--------------------- With ACCUMARRAY') 
tic,accumarray(indSeq(:),1);toc 

運行時輸出 -

--------------------- With HISTC 
Elapsed time is 1.028165 seconds. 
--------------------- With ACCUMARRAY 
Elapsed time is 0.220202 seconds. 
1

這是遊程編碼,和下面的代碼應該做的伎倆爲您服務。

A=zeros(1,10); 
indSeq = [1,1,2,3,4,4,4,7,1]; 
indSeq=sort(indSeq); %// if your input is always sorted, you don't need to do this 
pos = [1; find(diff(indSeq(:)))+1; numel(indSeq)+1]; 
A(indSeq(pos(1:end-1)))=diff(pos) 

返回

A = 
    3  1  1  3  0  0  1  0  0  0 

該算法對MATL寫的路易斯Mendo。

1

我認爲你要找的是數組唯一值的出現次數。這可以實現:

[num, val] = hist(indSeq,unique(indSeq)); 

您的示例的輸出是:

num = 2 1 1 3 
val = 1 2 3 4 

所以num是次VAL發生的數量。即1號出現2次,在你的榜樣

相關問題