2012-11-26 69 views
3

我們有p.e. i = 1:25迭代。 每個迭代結果是一個1xlength(N)單元陣列,其中0<=N<=25Matlab:按每個唯一值出現的次數排序一個向量

iteration 1: 4  5  9 10  20  
iteration 2: 3  8  9 13  14  6 
... 
iteration 25: 1  2 3 

我們評估所有迭代的一個矩陣的結果排序根據頻率的每個值重複在像本實施例中降序排列:

Matrix= 
    Columns 1 through 13 
    16 22 19 25  2  5  8 14 17 21  3 12 13 
    6  5  4  4  3  3  3  3  3  3  2  2  2 
    Columns 14 through 23 
    18 20  1  6  7  9 10 11 15 23 
    2  2  1  1  1  1  1  1  1  1 

結果的解釋:第1列:N == 16存在於6迭代,列2:N == 22存在於5次迭代中。 如果在任何迭代中未顯示數字N(在該範例N == 4,N == 24),則不列出頻率索引爲零。

我想將每次迭代(i)關聯到第一個N它顯示p.e. N == 9是目前僅在第一次迭代i = 1而不是在i = 2N == 3只有在i = 25太等,以i = 2,而不是直到所有i的是唯一的關聯N的。

預先感謝您。

回答

2

下面是一個使用(即它返回的索引爲第一值)的unique一個功能,是在R2012a

%# make some sample data 
iteration{1} = [1 2 4 6]; 
iteration{2} = [1 3 6]; 
iteration{3} = [1 2 3 4 5 6]; 
nIter= length(iteration); 

%# create an index vector so we can associate N's with iterations 
nn = cellfun(@numel,iteration); 
idx = zeros(1,sum(nn)); 
idx([1,cumsum(nn(1:end-1))+1]) = 1; 
idx = cumsum(idx); %# has 4 ones, 3 twos, 6 threes 

%# create a vector of the same length as idx with all the N's 
nVec = cat(2,iteration{:}); 

%# run `unique` on the vector to identify the first occurrence of each N 
[~,firstIdx] = unique(nVec,'first'); 

%# create a "cleanIteration" array, where each N only appears once 
cleanIter = accumarray(idx(firstIdx)',firstIdx',[nIter,1],@(x){sort(nVec(x))},{}); 

cleanIter = 
    [1x4 double] 
    [   3] 
    [   5] 

>> cleanIter{1} 
ans = 
    1  2  4  6 
+0

謝謝你的這種做法很有教育意義@Jonas。 – professor

1

引入下面是使用accumarray另一種解決方案的一種方式。評論中的解釋

% example data (from your question) 
iteration{1} = [4  5  9 10  20 ]; 
iteration{2} = [3  8  9 13  14  6]; 
iteration{3} = [1  2 3]; 
niterations = length(iteration); 

% create iteration numbers 
% same as Jonas did in the first part of his code, but using a short loop 
for i=1:niterations 
    idx{i} = i*ones(size(iteration{i})); 
end 

% count occurences of values from all iterations 
% sort them in descending order 
occurences = accumarray([iteration{:}]', 1); 
[occ val] = sort(occurences, 1, 'descend'); 

% remove zero occurences and create the Matrix 
nonzero = find(occ); 
Matrix = [val(nonzero) occ(nonzero)]' 

Matrix = 

3  9  1  2  4  5  6  8 10 13 14 20 
2  2  1  1  1  1  1  1  1  1  1  1 


% find minimum iteration number for all occurences 
% again, using accumarray with @min function 
assoc = accumarray([iteration{:}]', [idx{:}]', [], @min); 
nonzero = find(assoc); 
result = [nonzero assoc(nonzero)]' 

result = 

1  2  3  4  5  6  8  9 10 13 14 20 
3  3  2  1  1  2  2  1  1  2  2  1 
+0

謝謝你的方法@angainor。 – professor

相關問題