linear combination of vector and permutation

2 ビュー (過去 30 日間)
Fidele Adanvo
Fidele Adanvo 2022 年 10 月 3 日
コメント済み: Stephen23 2022 年 10 月 4 日
Hi, i' m developing a program where I find myself with this problem that I couldn't solve nem with combntns(v,k) or with nchoosek .
Anyone here to help me?
Let A=[-1,1] and B=3
I need to find all possible combinations taking from B to B vector element A ( It can be with repetition of the vector element )
I have done it manually, but I need it automatically, or a Matlab function does it.
Let A and B the output of this function has to be:
Out=[-1,-1,-1;
-1,-1, 1
-1, 1,-1
-1, 1, 1
1,-1,-1
1,-1, 1
1, 1,-1
1, 1, 1],

採用された回答

Torsten
Torsten 2022 年 10 月 3 日
values = [-1 1]; %// data
k = 3; %// data
n = numel(values); %// number of values
combs = values(dec2base(0:n^k-1,n)-'0'+1) %// generate all tuples
combs = 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
  2 件のコメント
Fidele Adanvo
Fidele Adanvo 2022 年 10 月 4 日
thank you
Matt J
Matt J 2022 年 10 月 4 日
編集済み: Matt J 2022 年 10 月 4 日
This approach is rather slow, if that matters...
values = -2:2; %// data
k = 9;
timeit(@()version1(values,k))
ans = 0.5780
timeit(@()version2(values,k))
ans = 0.0763
function version1(values,k)
n = numel(values); %// number of values
combs = values(dec2base(0:n^k-1,n)-'0'+1); %// generate all tuples
end
function version2(A,B)
[Out{1:B}]=ndgrid(A);
Out=reshape( cat(B+1,Out{:}),[],B);
end

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

その他の回答 (2 件)

Matt J
Matt J 2022 年 10 月 3 日
編集済み: Matt J 2022 年 10 月 3 日
One way:
A=[-1,1];B=3;
[Out{1:B}]=ndgrid(A);
Out=reshape( cat(B+1,Out{:}),[],B)
Out = 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
  2 件のコメント
Fidele Adanvo
Fidele Adanvo 2022 年 10 月 4 日
thank you
Stephen23
Stephen23 2022 年 10 月 4 日
+1 very neat usage of CAT and RESHAPE.

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


James Tursa
James Tursa 2022 年 10 月 4 日
編集済み: James Tursa 2022 年 10 月 4 日
Another way very similar to Torsten's method, limited to two desired values:
n = 3;
2*(dec2bin(0:2^n-1)-'0')-1
ans = 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

Community Treasure Hunt

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

Start Hunting!

Translated by