All possible combination based on 2^n but with 1 and -1

2 ビュー (過去 30 日間)
BeeTiaw
BeeTiaw 2021 年 5 月 14 日
コメント済み: Dyuman Joshi 2021 年 5 月 14 日
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?
  2 件のコメント
Jan
Jan 2021 年 5 月 14 日
Your example contain [1,1,1] twice.
BeeTiaw
BeeTiaw 2021 年 5 月 14 日
編集済み: BeeTiaw 2021 年 5 月 14 日
Yes. It is correct. That is the desired output.

サインインしてコメントする。

回答 (3 件)

Dyuman Joshi
Dyuman Joshi 2021 年 5 月 14 日
y=dec2bin([7 4 2 1])-'0';
y(y==0)=-1;
z =[y; flipud(y)]
This only works for this particular example. If you want a generalised answer, give more examples.
  2 件のコメント
BeeTiaw
BeeTiaw 2021 年 5 月 14 日
I am still trying to understand why we put [7 4 2 1].
Dyuman Joshi
Dyuman Joshi 2021 年 5 月 14 日
Because only this combination corresponds to the desired result.
That's why I mentioned - "This only works for this particular example. If you want a generalised answer, give more examples"

サインインしてコメントする。


Daniel Pollard
Daniel Pollard 2021 年 5 月 14 日
You could take the answer from your previous question, subtract 0.5 and multiply by 2. Your accepted answer was
n = 3;
m = dec2bin(0:pow2(n)-1)-'0' % limited precision
m = 8×3
0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1
which then becomes
n = 3;
m = dec2bin(0:pow2(n)-1)-'0'; % limited precision
m = 2*(m-0.5)
m = 8×3
-1 -1 -1 -1 -1 1 -1 1 -1 -1 1 1 1 -1 -1 1 -1 1 1 1 -1 1 1 1

Jan
Jan 2021 年 5 月 14 日
編集済み: Jan 2021 年 5 月 14 日
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)
m = 8×3
0 0 0 1 0 0 0 1 0 1 1 0 0 0 1 1 0 1 0 1 1 1 1 1
pool = [1, -1]; % Arbitrary values
result = pool(m + 1) % Add 1 to use m as index
result = 8×3
1 1 1 -1 1 1 1 -1 1 -1 -1 1 1 1 -1 -1 1 -1 1 -1 -1 -1 -1 -1
  1 件のコメント
BeeTiaw
BeeTiaw 2021 年 5 月 14 日
This is not creating the desired output as per the figure. The combination is different.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by