-1

I am using this block of code to get all the possible combinations of the rows of the matrix having thee rows. The code is as follows:

sample = [1 1 ; 2 2; 3 3];
v = [];
for i = 1:size(sample,1)-1
    v = [v;(sample(i,:))];
    for j = 1:size(sample,1)
          if isequal(ismember(sample(j,:),v,'rows'),0) 
              display([v;sample(j,:)]);
          else
              j = j+1;
          end 
    end
end

This code gives me the following output:

ans =    
     1     1
     2     2


ans =    
     1     1
     3     3


ans =    
     1     1
     2     2
     3     3

But I need output like this:

ans =    
     1     1


ans =    
     2     2


ans =    
     3     3


ans =    
     1     1
     2     2


ans =    
     1     1
     3     3


ans =    
     2     2
     3     3


ans =    
     1     1
     2     2
     3     3

Only a small change would be enough to get the desired result.

Wolfie
  • 27,562
  • 7
  • 28
  • 55
  • 1
    Possible duplicate of [How can we use nchoosek() to get all the combinations of the rows of a matrix?](https://stackoverflow.com/questions/47204269/how-can-we-use-nchoosek-to-get-all-the-combinations-of-the-rows-of-a-matrix) – etmuse Nov 20 '17 at 10:11
  • No I want to do this without using the nchosek function!! – Ali Hassan Nov 20 '17 at 10:12
  • To keep your existing method, part of the solution is going to have to reset `v` or it can never have any combination without row 1 (possibly another loop outside which also controls where the `i` loop starts) – etmuse Nov 20 '17 at 10:25
  • So how will we do that? – Ali Hassan Nov 20 '17 at 10:42
  • 1
    How do you know a small change would be enough? – m7913d Nov 20 '17 at 17:53
  • Note that you can look into the source code of `nchoosek`. – m7913d Nov 20 '17 at 17:54

1 Answers1

0

What about this:

% getting the number of rows
n_row = size(sample,1);
% calculating all possible permutations of the rows
v = perms([1:n_row]);
disp('---')
% now we iterate over the permutations, as you want to have matrixes of 1,
% 2 and 3 rows
for i = 1: size(v,2)
    idx1 = v(:,1:i);
    % remove repeated answers
    idx1 = unique(idx1,'rows');
    % now we iterate over the answers and display
    for j = 1:size(idx1,1)
        idx2 = idx1(j,:);
        answer = sample(idx2,:);
        disp(answer)
        disp('---')
    end    
end