How can we use nchoosek() to get all the combinati

2020-08-02 11:19发布

问题:

If we have a vector v of 1- 5 numbers we can use nchoosek(v,2) to get all the combinations having two elements. But this function does now allow us to get all the combinations of a matrix. I want to use it to get all the combinations of rows of a matrix.

回答1:

Here's one way to do it:

function p = q47204269(inMat)
% Input handling:
if nargin == 0 || isempty(inMat)
  inMat = magic(5);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
rowsCell = num2cell(inMat,2);
nRows = size(inMat,1);
p = cell(nRows,1);
for indR = 1:nRows
  r = nchoosek(1:nRows,indR);
  p{indR} = cell2mat(reshape(rowsCell(r.',:).',indR,1,[]));
end  

See also:

  • The perms function, as it might come in handy in what you're doing.
  • This question.


回答2:

with square matrix A

v = 1:size(A,1);
a = nchoosek(v,2);
B = zeros(2,size(A,1),length(a));
for i = 1:length(a)
    B(:,:,i) = A(a(i,:)',:);
end

Each layer of array B is a 2 row matrix with the row combos from A



回答3:

Not the most readable answer, but just for the sake of a one-liner :-)

A = randn(5,3); % example matrix
N = 2; % number of rows to pick each time
result = permute(reshape(A(nchoosek(1:size(A,1), N).', :), N, [], size(A,2)), [1 3 2]);

The result is a 3D array, such that each third-dim slice gives one of the a submatrices of A.