Recursive function only generating half of desired outputs

1 view (last 30 days)
I'm trying to generate all combinations of elements taken from n vectors
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 of 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 []

Accepted Answer

Drew
Drew on 22 Nov 2014
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

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!