0

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.

  • Do you mean you want to end up with new 2 row matrices made up from rows 1&2, rows 1&3, 3&5 etc, with row combinations as you'd get from nchoosek? – etmuse Nov 09 '17 at 14:29
  • Exactly that's all I need..Actually I need to call knnClassify() function on each possible combination of rows of that matrix so I will be needing all the matrices with desired rows.. – Ali Hassan Nov 09 '17 at 14:31

3 Answers3

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:

Dev-iL
  • 23,742
  • 7
  • 57
  • 99
  • What is n here? I want to select n number of rows each time. I mean first all the combinations of only 1 row then 2 rows than 3 rows than n rows... – Ali Hassan Nov 09 '17 at 18:57
  • @AliHassan I have updated the answer to make it clearer. – Dev-iL Nov 09 '17 at 20:52
0

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

etmuse
  • 505
  • 2
  • 9
  • Please don't advocate bad practices like growing matrices in a loop. – Dev-iL Nov 09 '17 at 16:31
  • Oops, I was testing if it worked on a separate machine from the one I have SO open on and totally forgot to re-type the pre-allocation when I transferred over. Will fix now. – etmuse Nov 09 '17 at 16:34
  • Growing matrices in a loop is only a bad practice if speed is critical or if the matrix size is significant compared to available memory. Usually it isn't. – nekomatic Nov 20 '17 at 10:34
-1

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.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147