-1

This is related to Generate a matrix containing all combinations of elements taken from n vectors

My solution uses recursion, but is missing half of the desired outputs. This is how I call it

allinputs = {[1 2] [3 4] [5 6] [7 8]}
inputArray = inputBuilder([],allinputs,1)

I can get this done without recursion but I like this way because it's more extensible for my purposes.

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

I should be getting a vector 16 1x4 arrays but I'm missing all the combinations that end with 7

*1 3 5 7

1 3 5 8

*1 3 6 7

1 3 6 8

etc etc... The * indicates what I'm missing in the output, it just comes out as []

Community
  • 1
  • 1
Drew
  • 91
  • 10
  • What did you discover when you stepped through your code in the debugger? – Oliver Charlesworth Nov 22 '14 at 19:11
  • @OliverCharlesworth mybuild of [1,3,6,7] seems to get overwritten by [1,3,6,8]... but that doesn't account for the [] arrays where [1,3,6,7] should be. I could be interpreting the debugging completely wrong... It's pretty hard to trace through recursion – Drew Nov 22 '14 at 19:30

1 Answers1

2

Solved it

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
Drew
  • 91
  • 10