我有一個單元陣列包含5個1x2陣列。有什麼方法可以找到最重複的元素嗎?我想我不能使用「模式」功能。我在網上查了一下,找不到解決問題的辦法。每個人都一直在討論帶有字符串的單元陣列。MATLAB - 單元陣列的最重複元素
我使用的單元陣列是這樣的: {[1 2],[2 5],[3 4],[1 2],[0 4]}
我想MATLAB找到[1 2]作爲最重複的元素。
預先感謝您。
我有一個單元陣列包含5個1x2陣列。有什麼方法可以找到最重複的元素嗎?我想我不能使用「模式」功能。我在網上查了一下,找不到解決問題的辦法。每個人都一直在討論帶有字符串的單元陣列。MATLAB - 單元陣列的最重複元素
我使用的單元陣列是這樣的: {[1 2],[2 5],[3 4],[1 2],[0 4]}
我想MATLAB找到[1 2]作爲最重複的元素。
預先感謝您。
對於統一的結構化單元陣列(每單元2個元件)的情況下
%// Convert the uniformly structured data to a 2D numeric array
Anum = vertcat(A{:})
%// ID unique rows and ID all rows based on those
[~,unqID,ID ] = unique(Anum,'rows')
%// Use 'mode' on ID and then index into unqID to get the index of
%// the most frequently occurring cell and finally index into the
%// input cell array with that index to get the desired output
out = A{unqID(mode(ID))}
因此,對於給定輸入數據 -
A = {[1 2], [2 5], [3 4], [1 2], [0 4]}
你將不得不 -
out =
1 2
與行的細胞更通用的情況下,向量
如果正在處理與在每個單元具有任意大小的行向量的單元陣列,則可以使用這種技術 -
%// Get all elements of A
A_ele = [A{:}]
%// Get lengths of each cell
lens = cellfun('length',A)
%// Setup a 2D numeric array corresponding to the input cell array
A_num = zeros(max(lens),numel(lens))+max(A_ele)+1
A_num(bsxfun(@ge,lens,[1:max(lens)]')) = A_ele %//'
%// ID each row, find the mode with those & finally have the desired output
[unqrows,unqID,ID ] = unique(A_num.','rows') %//'
out = A{unqID(mode(ID))}
因此,如果你必須輸入作爲 -
A = {[1 2], [2 5], [3 4], [1 2], [0 4], [1 2 1],[9],[7 2 6 3]}
輸出仍然是 -
out =
1 2
這適用於一般單元陣列A
:
A = {[4 2] [2 5] [4 2] [1 2 1] [9] [7 2 6 3] [1 2 1] [1 2 1] [7 9]}; %// example data
[ii, jj] = ndgrid(1:numel(A)); %// ii, jj describe all pairs of elements from A
comp = cellfun(@isequal, A(ii), A(jj)); %// test each pair for equality
[~, ind] = max(sum(comp,1)); %// get index of (first) most repeated element
result = A{ii(ind)}; %// index into A to get result
你有這樣的*統一的結構*單元陣列(每單元2個單元)爲您的實際輸入的數據? – Divakar 2015-04-02 20:08:44
是的,數據是我的實際輸入數據。 – theakt 2015-04-02 20:19:27