I have a series of numbers:
test = [1 1 1 2 2 2 3 3 3 4 4 4 5 5 5]
which I want to randomely fill into a 3x5 matrix without having the same number in the same row.
How can I do this in matlab? Potentially I could randomize the test vector and fill it into the 5x3 matrix but I don't know how to do this without getting the same number in the same row.
You can take the unique matrix of test and pick any three elements out of it and fill in the required 5X3 matrix.
randsample needs a statistics toolbox, if you doesn't have it, you may use randperm as shown below.
If you want 3X5 matrix:
If you want to fill a 3-by-5 matrix with all of the values in
test
, making sure each row has no repeated values, you can do this very succinctly by usingtoeplitz
to first generate an index matrix, then randomly permute the dimensions withrandperm
:And a sample
index
:If your values in
test
are the numbers 1 through 5, this should be all you need to do. Iftest
could be any vector with with 5 different numbers, three of each, then you can get the unique values of yourtest
vector and index them withindex
. This solution will generalize to anytest
vector:And the result will be guaranteed to be a reordered version of what's in
test
:Here is a brute-force way of doing it
EDIT : If you want 3x5 like you mentioned in your comment, it is a lot easier. Just one line below.