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

Jan
Jan 2017년 6월 8일
편집: Jan 2017년 6월 8일
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.

댓글을 달려면 로그인하십시오.

 채택된 답변

Jan
Jan 2017년 6월 8일
편집: Jan 2017년 6월 8일

0 개 추천

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.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

질문:

2017년 4월 3일

편집:

Jan
2017년 6월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by