how to generate random matrix with known matrix

Hello Everyone, For example I have; a=[1 2 3]; b=[4 5]; s=8;
I can create matrix(es?) like this; matrix1=[a b s]; (ans=[1 2 3 4 5 8]) matrix2=[a s b]; (ans=[1 2 3 8 4 5]) matrix3=[s b a]; (ans=[8 4 5 1 2 3]) etc...
But how can I make Matlab generate all the possible (3!) combinations without writing them manually myself? Is it even possible? I am aware that it is not that hard to do with 6 different outcomes but I have (15!) combinations that I have to generate. I appriciate all answers. Thank you.

2 Comments

Hello Melike,
The perms function will give all possible permutations of the elements of a vector, and you could use that as a building block to get concatenated permutations of small row vectors. However, maybe you should think about the final result. 15! is approximately 1.31e12. Suppose the the average length of the small vectors is 2 and you generated all the results at once as implied above. Then even with everything stored as uint8, it takes39000 Gbytes of memory. That's a lot of memory.
If you only wanted to generate a few million of them or whatever at random, that's doable with the help of the randperm function.
Thank you David :) I didn't consider the memory aspect, I will think about alternative approaches.

Sign in to comment.

 Accepted Answer

Indeed, as David warned, seriously reconsider your approach before trying the following with 15 matrices:
a=[1 2 3]; b=[4 5]; s=8; % your data, row vectors
C = {a b s} % store them in a cell array for easy access
p = perms(1:numel(C)) % get all permutations
matrix = arrayfun(@(k) [C{p(k,:)}], 1:size(p,1), 'un', 0) % concatenate the permutations
% matrix{k} now holds the k-th permutation of the three arrays (a, b, and s)

1 Comment

Thank you Jos. I didn't realize it would be this easy :) I will consider my approach with memory problem in mind...

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!