2014-11-22 79 views
-1

這與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 1×4陣列,但我缺少所有以7

* 1 3 5 7

*結束組合1 3 6 7

等等... *表示什麼,我缺少的輸出,它只是出來爲[]

+0

你是怎麼發現,當你通過代碼在調試器階梯? – 2014-11-22 19:11:05

+0

@OliverCharlesworth [1,3,6,7]的mybuild似乎被[1,3,6,8]覆蓋...但是這並沒有考慮[]數組[1,3,6, 7]應該是。我可以解釋完全錯誤的調試...很難追溯遞歸 – Drew 2014-11-22 19:30:39

回答

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