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?
댓글 수: 0
답변 (2개)
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,:),:);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!