MATLAB: How to Store all the possible combinations of columns of a matrix

combination of rowsmatrixstore

for example I have : [1 2 3; 4 5 6; 7 8 9] as 3×3 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.

Best Answer

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