How to generate all possible vectors where each element can take one of two values
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Kevin Galloway
il 21 Giu 2022
Commentato: Kevin Galloway
il 23 Giu 2022
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?
0 Commenti
Risposta accettata
Paul
il 23 Giu 2022
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)))
0 Commenti
Più risposte (1)
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!