How to generate all possible vectors where each element can take one of two values

조회 수: 1 (최근 30일)
Given vectors a and b both of length N, I want to generate the 2^N vectors for which element i is either a[i] or b[i]. For example, if a=[1,2,3] and b=[4,5,6], then I want to generate
C =
1 2 3
1 2 6
1 5 3
1 5 6
4 2 3
4 2 6
4 5 3
4 5 6
I can do this with the following code
N = length(a);
M = ff2n(N);
Mc = abs(M-1);
C = a.*Mc + b.*M;
but I'm wondering if there is a better way to accomplish this, possibly not requiring ff2n which is not part of standard MATLAB installation? Is there a way to use nchoosek or permute or something like that?

채택된 답변

Paul
Paul 2022년 6월 23일
a = [1 2 3];
b = [4 5 6];
n = numel(a);
C = mat2cell([a; b],2,ones(1,n));
[D{1:n}] = ndgrid(C{:});
E = sortrows(cell2mat(cellfun(@(x) x(:),D,'UniformOutput',false)))
E = 8×3
1 2 3 1 2 6 1 5 3 1 5 6 4 2 3 4 2 6 4 5 3 4 5 6

추가 답변 (1개)

Torsten
Torsten 2022년 6월 21일
Generate all possible combinations of 0 and 1:
m = 3;
justRows = dec2bin(0:2^m-1)-'0'
Now replace the 0's by a(i) and the 1 by b(i).
  댓글 수: 3
Torsten
Torsten 2022년 6월 23일
You can use "allcomb" available here:
a=[1,2,3];
b=[4,5,6];
A = [a;b];
result = allcomb(A(:,1),A(:,2),A(:,3))
Kevin Galloway
Kevin Galloway 2022년 6월 23일
Thanks, Torsten. This is a nice function, and an efficient way of accomplishing my task. Much appreciated!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by