All possible combinations for fixed columns?

2 ビュー (過去 30 日間)
Daniel
Daniel 2014 年 12 月 5 日
編集済み: Henrik 2014 年 12 月 6 日
Hey folks,
I'm attempting to build an algorithm that generates a 2^n x n matrix of values where n is the size of an input matrix made of two vectors that represent the minimum (first column) and maximum (second column) of values, respective.
For instance, if: input = [-1 1; -2 2]; output should be something like: [1 2; -1 -2; 1 -2; -1 2];
I looked at using nchoosek for this. However, when finding all possible combination, it includes columns being shifted around as such:
Theta =
-1 1 -2 2
>> C = nchoosek(Theta,2)
C =
-1 1
-1 -2
-1 2
1 -2
1 2
-2 2
For higher order systems (n >= 3), this becomes even more complicated. Is there anyway I can use nchoosek or another algorithm with if statements to solve for the correct output, am I using the incorrect function to solve this, or should I build my own algorithm?
I appreciate any feedback.
- Dan

回答 (1 件)

Henrik
Henrik 2014 年 12 月 6 日
編集済み: Henrik 2014 年 12 月 6 日
I don't know how fast this will be for large n, but this seems to do what you want. You can probably vectorize at least one of the loops.
input=[-1 0 1; 2 4 6];
sz=size(input);
output=zeros(sz(2)^2,2);
for k=0:sz(2)-1
for l=1:sz(2)
output(k*sz(2)+l,:)=[input(1,k+1) input(2,l)];
end
end
output
EDIT: changed the preallocation.
  2 件のコメント
Henrik
Henrik 2014 年 12 月 6 日
編集済み: Henrik 2014 年 12 月 6 日
Here I vectorized one loop:
input=[-1 0 1; 2 4 6];
sz=size(input);
output=zeros(sz(2)^2,2);
l=1:sz(2);
for k=0:sz(2)-1
output(k*sz(2)+l,:)=[ones(sz(2),1)*input(1,k+1) input(2,:).'];
end
Henrik
Henrik 2014 年 12 月 6 日
編集済み: Henrik 2014 年 12 月 6 日
... And here's a full vectorization
input=[-1 0 1; 2 4 6];
sz=size(input);
C1=repmat(input(1,:),sz(2),1);
C1=C1(:);
C2=repmat(input(2,:).',sz(2),1);
output=[C1 C2]

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

カテゴリ

Help Center および File ExchangeElementary Math についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by