这与Generate a matrix containing all combinations of elements taken from n vectors
有关我的解决方案使用递归,但缺少一半所需的输出。这就是我称之为
的方式allinputs = {[1 2] [3 4] [5 6] [7 8]}
inputArray = inputBuilder([],allinputs,1)
我可以在没有递归的情况下完成这项工作,但我喜欢这种方式,因为它对我的目的更具扩展性。
function inputArray = inputBuilder(currBuild, allInputs, currIdx)
inputArray = [];
if currIdx <= length(allInputs)
for i = 1:length(allInputs{currIdx})
mybuild = [currBuild allInputs{currIdx}(i)];
inputArray = [inputArray inputBuilder(mybuild,allInputs,currIdx + 1)];
end
if currIdx == length(allInputs)
inputArray = {inputArray mybuild};
end
end
end
我应该得到一个矢量16个1x4阵列,但我缺少所有以7结尾的组合
* 1 3 5 7
1 3 5 8
* 1 3 6 7
1 3 6 8
等等... *表示我在输出中缺少的东西,它只是以[]
形式出现答案 0 :(得分:2)
解决了它
function inputArray = inputBuilder(currBuild, allInputs, currIdx)
inputArray = [];
if currIdx <= length(allInputs)
for i = 1:length(allInputs{currIdx})
mybuild = [currBuild allInputs{currIdx}(i)];
inputArray = [inputArray inputBuilder(mybuild,allInputs,currIdx + 1)];
end
else
if isempty(inputArray)
inputArray = {currBuild};
else
inputArray = {inputArray currBuild};
end
end
end