MATLAB: Get every possible combination of an array

combinationMATLABrandom sequence

I have an array that contains n number of 1s and -1s for example:
[1 -1 1 -1 1 1 1 -1]
I'd like every possible combination of this array (like [1 – 1-1 1 1 1 1 -1] ect…)
I tried using perms, but perms has a limit of size 10 and I need to be able to do upto 32. Another thing about perms is I'll have repeating numbers (which I can remove with ease)

Best Answer

This could be a starting point:
clearvars, close all
clc
arr = [-1 1 -1 1 1 1 1 1 -1];
num_arr_elements = numel(arr);
% find the number of -1
num_minus_one = sum(arr == -1);
% get all possible positions of -1
idx = nchoosek(1:num_arr_elements, num_minus_one);
% Initialize the matrix of combinations with ones
out = ones(size(idx,1), num_arr_elements);
% Place the -1s on the idx position
for ii = 1:size(idx,1)
out(ii,idx(ii,:)) = -1;
end
Two more aspects:
  • We have to get rid of this for loop
  • Number of possible combinations is with n: array length, s1: number of 1s and s2: number of -1s; for n = 32 and (worst case) s1=s2=16, we have an output array of size 9 x 601.080.390. Optimization is heavily needed or buy a lot of RAM.