How can I Store all the possible combinations of columns of a matrix?

for example I have : [1 2 3; 4 5 6; 7 8 9] as 3x3 matrix. Now I want : [2 1 3; 5 4 6; 8 7 9] and every other combination of it. in other word I want all nchoosek(n,2) of columns of a nxn matrix.

 Réponse acceptée

I would recommend that you only save the indices, if you really need to. Sure, you only have a small matrix, but the amount of required memory can become a problem really fast in combinatorial problems.
a = [1 2 3; 4 5 6; 7 8 9];
idx = perms(1:size(a,2));
for ii = idx'
your_mat = a(:,ii)
end

3 commentaires

Thank you very much. This was the answer I expected. Now, what permutations are there if we want n-2 columnc be the same and just 2 columns swap. Here is an example of what I mean: a=[1 2 3 4;5 6 7 8;9 10 11 12;13 14 15 16] then indices would be (1,2,3,4) now I want to know how can I implement (2,1,3,4) (3,2,1,4) (4,2,3,1) (1,3,2,4) (1,4,3,2) (1,2,4,3) as you see at any permutation just 2 indices are swaping and the rest are the same as in (1,2,3,4) Thank you in advance
how to store all the your_mat value from every loop into one matrix? Thanks in advance
In this case how do you get a 18x3 matrix as a result? Thank you

Connectez-vous pour commenter.

Plus de réponses (1)

As a starting point you could store the output of the function 'perms' is a cell array, in which the kth cell cell contains all the possible permutations of the kth column. Eg:
clear all
clc
A= [1 2 3;4 5 6;7 8 9];
P = cell(1,size(A,1));
for k = 1:size(A,1)
P{k} = perms(A(:,k))'; % Notice the transpose of the output.
end
disp('P{1}')
disp(P{1})
disp('P{2}')
disp(P{2})
disp('P{3}')
disp(P{3})
which gives this:
P{1}
7 7 4 4 1 1
4 1 7 1 4 7
1 4 1 7 7 4
P{2}
8 8 5 5 2 2
5 2 8 2 5 8
2 5 2 8 8 5
P{3}
9 9 6 6 3 3
6 3 9 3 6 9
3 6 3 9 9 6
Then you could implement a loop in which you take every column of say P{1} and get the possible combinations with the columns from P{2}, P{3} and so on. There is probably a built-in function for this but I don't know it sorry. I hope that helps!

2 commentaires

samad khansari
samad khansari le 25 Juil 2014
Modifié(e) : samad khansari le 25 Juil 2014
Thank you very much but not helping :)
Oh shoot sorry then I guess I misunderstood the question! :)

Connectez-vous pour commenter.

Catégories

En savoir plus sur Circuit Envelope Simulation dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by