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

3 ビュー (過去 30 日間)
Ian Garza
Ian Garza 2020 年 6 月 18 日
編集済み: James Tursa 2020 年 6 月 18 日
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 Center および File ExchangeCreating 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