I created a cell array of shape m x 2, each element of which is a matrix of shape d x d.
For example like this:
A = cell(8, 2);
for row = 1:8
for col = 1:2
A{row, col} = rand(3, 3);
end
end
More generally, I can represent A as follows:
where each A_{ij} is a matrix.
Now, I need to randomly pick a matrix from each row of A, because A has m rows in total, so eventually I will pick out m matrices, which we call a combination.
Obviously, since there are only two picks for each row, there are a total of 2^m possible combinations.
My question is, how to get these 2^m combinations quickly?
It can be seen that the above problem is actually finding the Cartesian product of the following sets:


2^mis actually a binary number, so we can use those to create linear indices. You'll get an array containing 1s and 0s, something like[1 1 0 0 1 0 1 0 1], which we can treat as column "indices", using a0to indicate the first column and a1to indicate the second.On my R2007b version this runs virtually instant for
m = 20.NB: this will take
m * 2^mbytes of memory to storebin_idx. Where that's just 20 MB form = 20, that's already 30 GB form = 30, i.e. you'll be running out of memory fairly quickly, and that's for just storing permutations as booleans! Ifmis large in your case, you can't store all of your possibilities anyway, so I'd just select a random one:Old, slow answer for large
mperms()1 gives you all possible permutations of a given set. However, it does not take duplicate entries into account, so you'll need to callunique()to get the unique rows.The only thing left now is to somehow do this over all possible amounts of
1s and2s. I suggest using a simple loop:NB: I've not initialised
out, which will be slow especially for largem. Of courseout = zeros(2^m, m)will be its final size, but you'll need to juggle the indices within theforloop to account for the changing sizes of the unique permutations.You can create linear indices from
outusingfind()Linear indices are row-major in MATLAB, thus whenever you need the matrix in column 1, simply use its row number and whenever you need the second column, use the row number +
size(A,1), i.e. the total number of rows.Combining everything together:
1 There's a note in the documentation: