필터 지우기
필터 지우기

Combination of rows of two different matrices

조회 수: 3 (최근 30일)
J AI
J AI 2020년 7월 23일
댓글: Fangjun Jiang 2020년 7월 24일
Sorry if this is a repeated question but I failed to find an answer myself. I have two matrices:
A = [-0.6, -0.2;
-60, 2;
6, -20];
B = [-0.4, -0.8;
-40, 8;
4, -80];
I want to find all the possible combinations of sum of each row (sum of individual elements of a row) of A with each row of B, i.e., my desired result is (order does not matter):
ans = [-1, -1;
-40.6, 7.8;
3.4, -80.2;
-60.4, 1.2;
-100, 10;
-56, -78;
5.6, -20.8;
-34, -12;
10, -100];
which is a matrix resulting from possible combinations of A and B.
Thanks in advance.
(Please no for loops. It is pretty trivial then.)
EDIT: I have used 2 columns and 3 rows as an example. Looking for more general solution, i.e., for n number of columns and m number of rows.

채택된 답변

Fangjun Jiang
Fangjun Jiang 2020년 7월 23일
편집: Fangjun Jiang 2020년 7월 23일
Feels non-ideal. Any better solution?
>> C=A(:,1)+B(:,1)';
D=A(:,2)+B(:,2)';
reshape([C(:),D(:)],[],2)
ans =
-1.0000 -1.0000
-60.4000 1.2000
5.6000 -20.8000
-40.6000 7.8000
-100.0000 10.0000
-34.0000 -12.0000
3.4000 -80.2000
-56.0000 -78.0000
10.0000 -100.0000
better one
>> m=size(A,1);
ind1=repmat(1:m,1,m);
ind2=repelem(1:m,m);
A(ind1,:)+B(ind2,:)
ans =
-1.0000 -1.0000
-60.4000 1.2000
5.6000 -20.8000
-40.6000 7.8000
-100.0000 10.0000
-34.0000 -12.0000
3.4000 -80.2000
-56.0000 -78.0000
10.0000 -100.0000
  댓글 수: 2
J AI
J AI 2020년 7월 23일
This works, but I should have been a bit more specific with my question - the number of columns I have used is 2, however, it may vary. So I was looking for a more general solution. Thanks anyway!
J AI
J AI 2020년 7월 23일
Great work! Thanks a lot

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Bruno Luong
Bruno Luong 2020년 7월 23일
편집: Bruno Luong 2020년 7월 23일
A = [-0.6, -0.2;
-60, 2;
6, -20];
B = [-0.4, -0.8;
-40, 8;
4, -80];
Single statement
reshape(permute(A,[3 1 2])+permute(B,[1 3 2]),[],size(A,2))
or a variation
reshape(reshape(A,1,size(A,1),[])+reshape(B,size(B,1),1,[]),[],size(A,2))
Gives
ans =
-1.0000 -1.0000
-40.6000 7.8000
3.4000 -80.2000
-60.4000 1.2000
-100.0000 10.0000
-56.0000 -78.0000
5.6000 -20.8000
-34.0000 -12.0000
10.0000 -100.0000
>>
  댓글 수: 3
Bruno Luong
Bruno Luong 2020년 7월 23일
Yes the variation version does no more no less than the required combination sums and puts at the results at the right place. Not a hair uneccesary arithmetic or memory moving (first version).
Fangjun Jiang
Fangjun Jiang 2020년 7월 24일
Brilliant, Bruno Luong! I learned implicit expansion in a whole new dimension.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by