How to save output of a recursive function

1 view (last 30 days)
Given a matrix A, I have to make all possible combinations of entries of A such that only one number is selected from each row. I have made the following recursive program which is running successfully. But I am not able to save the output vector X. So, for example in the following matrix A, there will be 27 such combinations, I want to save them in matrix of order 3x27.
A=[3 4 0;2 3 7;45 7 0]
n=1;
X=zeros(3,1);
comb(n, X, A); %function to calculate all combinations.
function X =comb(n,X, A)
if (n>3)
X
return
end
for i=1:3
X(n)= A(n,i);
comb(n+1,X,A);
end
end
  2 Comments
Jan
Jan on 8 Jun 2017
Edited: Jan on 8 Jun 2017
The method shown at stackoverflow uses a global variable to collect the output. This is rather indirect, inefficient and prone to bugs. Use inputs and outputs of function instead.

Sign in to comment.

Accepted Answer

Jan
Jan on 8 Jun 2017
Edited: Jan on 8 Jun 2017
In the line comb(n+1,X,A); the function comb is called, but this does not change the value of X, because the output of this function is not assigned. Do you mean x = comb(n+1,X,A)?
A recursive function might not be the best choice. Either use a method from the FEX, e.g. FEX: Combinator or FEX: VChooseKRO.
Or create a loop:
A = [3 4 0;2 3 7;45 7 0];
[nRow, nCol] = size(A);
nResult = nCol ^ nRow;
index = ones(1, nRow);
Result = zeros(nRow, nResult);
for k = 1:nResult
Result(:, k) = A(sub2ind(size(A), 1:nRow, index));
% Update the index vector:
for k = nRow:-1:1
index(k) = index(k) + 1;
if index(k) <= nCol
break; % index(k) increased successfully, leave "for k" loop
end
index(k) = 1; % index(k) reached the limit, reset it and iterate index(k-1)
end
end
This is equivalent to nRow nested for loops, which count from 1 to nCol and insert the corresponding element into the output. Hard coding this does not work, because the number of loops is flexible. There instead of a bunch of for loops, this has one loop and the list of for loop indices is store in the vector indices. Each index value is incremented and if it exceeds nCol, it is reset to 1 and the next index element is processed.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!