递归函数只生成所需输出的一半



这与 生成一个矩阵,其中包含从 n 个向量获取的所有元素组合

我的解决方案使用递归,但缺少所需的输出的一半。这就是我所说的

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

等等

等等...* 表示我在输出中缺少的内容,它只是显示为 []

解决了

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

最新更新