How can I find all possible combinations of rows from two separate arrays?

5 visualizaciones (últimos 30 días)
I currently have two arrays, a positive array, and a negative array. I am trying to find all combinations of positive rows and negative rows. For example I have two arrays, A and B:
A=[1 2 3;4 5 6;7 8 9]
B=[-1 -2 -3; -4 -5 -6; -7 -8 -9]
I want to find all possible combinations of positive and negative rows such that:
AB1=[1 2 3; -4 -5 -6; 7 8 9]
AB2=[1 2 3, -4 -5 -6; -7 -8 -9]
...
and so on. Since I have three rows, I know that there are 2^3=8 possible combinations of positive and negative rows. A and B will always be the same size for my application, but the size could increase or decrease. For example, I could have two rows in A and B which would have 2^2=4 possible combinations (++ ,--, +-, -+), or I could have up to 10 rows in each array which would have 2^10=1024 possible combinations.
How can I write matlab code that would cycle through the rows of A and B and output ABn where n is the number of possible combinations?

Respuestas (2)

KSSV
KSSV el 18 de Jun. de 2020
Editada: KSSV el 18 de Jun. de 2020
s = [1 1 1 -1 -1 -1] ;
s = nchoosek(s,3) ;
A = [1 2 3 ; 4 5 6; 7 8 9] ;
n = size(s,1) ;
B = zeros(3,3,n) ;
for i = 1:n
B(:,:,i) = s(i,:)'.*A
end

James Tursa
James Tursa el 18 de Jun. de 2020
Editada: James Tursa el 18 de Jun. de 2020
E.g., For arbitrary values in A and B, doesn't have to be B = -A
n = size(A,1);
C = repmat({A},2^n,1);
mask = dec2bin((0:(2^n-1))') == '1';;
for k=1:2^n
C{k}(mask(k,:),:) = B(mask(k,:),:);
end
Or if you want to force B = -A, then B isn't strictly necessary and you could do this
C{k}(mask(k,:),:) = -C{k}(mask(k,:),:);

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Productos


Versión

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by