0

Can anyone please help in writing the code to generate a matrix of which each row should contain a new arrangement (permutation without repetition)?

I have tried the following:

        %Generate an array of 8 elements randomly
        array=floor(randi([0,100],1,K));
        %Generate all permutations of 'array'. Each row signifies a new arrangement
        %all_matrix=perms(array);                  
        %// Create all possible permutations (with repetition) of letters stored in x
        C = cell(K, 1);             %// Preallocate a cell array
        [C{:}] = ndgrid(array);         %// Create K grids of values
        y = cellfun(@(array){array(:)}, C); %// Convert grids to column vectors
        all_matrix_repetition = [y{:}];  
        all_matrix=zeros(factorial(K),K);
        for i=1:size(all_matrix_repetition,1)
            if length(all_matrix_repetition(i,:))==length(unique(all_matrix_repetition(i,:)))
           all_matrix(count,:)=all_matrix_repetition(i,:);
           count=count+1;
    end
end

But getting the memory error. I am using Matlab 2011a. Please help me.

Avijit Dasgupta
  • 2,055
  • 3
  • 22
  • 36

1 Answers1

0

If I understood right I think this will do:

arraySize = 3;
array = randi(100,[1 arraySize]);
indexes = perms(1:arraySize);
permutated = array(indexes);

Where you would get, for instance:

array =

    19    24    42


indexes =

     3     2     1
     3     1     2
     2     3     1
     2     1     3
     1     2     3
     1     3     2


permutated =

    42    24    19
    42    19    24
    24    42    19
    24    19    42
    19    24    42
    19    42    24
Gui Brunow
  • 192
  • 3
  • 11
  • What if the length of the array is greater than 10? – Avijit Dasgupta Apr 02 '16 at 05:17
  • It shouldn't matter, I put only 3 just to be easy to visualize. – Gui Brunow Apr 02 '16 at 05:25
  • I'm sorry, just tested it, I wasn't aware that there was a limitation for perms size. – Gui Brunow Apr 02 '16 at 05:26
  • You can make something like this: `a = randi(PA,1,NP); repeated = a == 1:NP; while(~isempty(repeated(repeated == true))) newCrossing = randi(PA,1,NP); a(repeated) = newCrossing(repeated); repeated = a == 1:NP; end b = randi(PA,1,NP); repeated = b == 1:NP; repeated = repeated | b == a; while(~isempty(repeated(repeated == true))) newCrossing = randi(PA,1,NP); b(repeated) = newCrossing(repeated); repeated = b == 1:NP; repeated = repeated | b == a; end` **It's not it but you can use the ideia.** – Gui Brunow Apr 02 '16 at 05:29