All possible combination based on 2^n but with 1 and -1
4 views (last 30 days)
Hi all, thank you for those of you who have answered my question below.
I have a slightly different question but still does not know how to achieve this.
Again, I want to create a matrix containing all possible combination. Example of this is shown below. The size of the matrix depends on the number of variable n and the total of combination should follow the . The example below is valid for and, hence, the total number of rows is 8. The value of each element is 1 and -1.
How to create this matrix automatically depending on the number of variable n?
Dyuman Joshi on 14 May 2021
y=dec2bin([7 4 2 1])-'0';
z =[y; flipud(y)]
This only works for this particular example. If you want a generalised answer, give more examples.
Jan on 14 May 2021
Edited: Jan on 14 May 2021
dec2bin creates a CHAR vector, while -'0' converts it to a double again. This indirection costs some time. The direct approach:
n = 3;
m = rem(floor((0:2^n-1).' ./ 2 .^ (0:n-1)), 2)
pool = [1, -1]; % Arbitrary values
result = pool(m + 1) % Add 1 to use m as index