我正在嘗試從向量陣列中獲取所有可能的元素組合。例如,假設我有一個元胞陣列
C = {[1 2 3 4 5], [6:13], [14 15]}
那么輸出應該是這樣的
out = {[1 6 14], [1 6 15], [1 7 14], [1 7 15],....,[5 13 15]}
我嘗試使用遞回函式來實作這一點,但下面的代碼似乎不起作用。如何獲得所有這些組合的串列?
function [out,i] = permuteTest2(a,i,N,l,out)
if nargin == 0
a={[1 2],[4 5],[7 8]};
N = length(a);
i = 1;
out = [];
end
if i == N
out = [out, a{i}(l)];
return;
else
for k=i:N
L = length(a{k});
for l=1:L
out =[out a{k}(l)];
[out,i] =permuteTest2(a, i 1, N,l,out);
end
end
end
uj5u.com熱心網友回復:
假設您有一個C
包含 N 個向量的元胞陣列。要從每個向量中獲取一個元素的所有組合,您需要將第一個向量中的每個元素與其余向量的所有組合組合:
function combs = all_combinations(C)
a = C{1};
b = all_combinations(C(2:end));
% ... get all the combinations of a and b here
如果C
只有一個元素,那么所有組合就是那個元素(讓我們將其轉換為一個單元格陣列,每個單元格中有一個數字,以匹配預期的輸出格式):
function combs = all_combinations(C)
a = C{1};
if numel(C) == 1
combs = num2cell(a);
return;
end
b = all_combinations(C(2:end));
% ... get all the combinations of a and b here
這會處理遞回部分。現在我們需要做的就是找到兩組a
和的所有組合b
:
function combs = all_combinations(C)
a = C{1};
if numel(C) == 1
combs = num2cell(a);
return;
end
b = all_combinations(C(2:end));
combs = cell(numel(a), numel(b));
for ii = 1:numel(a)
for jj = 1:numel(b)
combs{ii, jj} = [a(ii), b{jj}];
end
end
combs = combs(:);
要理解上面的答案,重要的是要跟蹤哪些元素是元胞陣列,哪些不是,以及我們如何索引元胞陣列({}
從陣列中提取元素,()
索引元胞陣列的各個部分,創建一個新的元胞陣列) .
我也numel
到處使用,而不是length
. numel
效率更高,并且如果您輸入的陣列不是一維以上的向量,則上面的代碼也可以同樣有效地作業。
更健壯的函式將測驗輸入C
是否為具有至少一個元素的元胞陣列,并將測驗該元胞陣列的每個元素是否為數值陣列(或向量)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/505846.html