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

5 次查看(过去 30 天)
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?

回答(2 个)

KSSV
KSSV 2020-6-18
编辑:KSSV 2020-6-18
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 2020-6-18
编辑:James Tursa 2020-6-18
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,:),:);

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by