I have two matrices A and B, and I would like to compute a matrix C whose rows are all possible combinations of the sum of a row of A and a row of B. What would be the fastest way to perform the computation?
Additional question - what if A and B are both gpuArrays?
Update - Example
Say A is a matrix of 3 rows and B is a matrix of 2 rows, then I would like C to be the matrix
C = [A(1, :) + B(1, :);
A(1, :) + B(2, :);
A(2, :) + B(1, :);
A(2, :) + B(2, :);
A(3, :) + B(1, :);
A(3, :) + B(2, :)];

댓글 수: 2

madhan ravi
madhan ravi 2019년 2월 26일
편집: madhan ravi 2019년 2월 26일
illustrate with a short example
Alexander Shtof
Alexander Shtof 2019년 2월 26일
Done.

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

 채택된 답변

Adam
Adam 2019년 2월 26일
편집: Adam 2019년 2월 26일

0 개 추천

C = repelem( A, size( B, 1 ), 1 ) + repmat( B, size( A, 1 ), 1 );
Should be the same for gpuArrays too. Whether it is fastest for runtime or not is another matter entirely. There are any number of possible ways of doing it - this is just one. I certainly don't have time to think up, implement and time all of them!

댓글 수: 2

Alexander Shtof
Alexander Shtof 2019년 2월 26일
This actually works great! Did not know that a function like repelem exists. I used meshgrid to construct pairwise indices, and it resulted in a slower computation.
Thank you!
Adam
Adam 2019년 2월 26일
Yeah, it's one of those useful components to know. It is a relatively recent addition, added in R2015a, although the years seem to be flying past so I guess that is already 4 years ago now!

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

추가 답변 (1개)

Jos (10584)
Jos (10584) 2019년 2월 26일

0 개 추천

% An old-school 20th century indexing trick:
A = randi(9,3,2)
B = 100*randi(9,4,2)
[ia, ib] = ndgrid(1:size(A,1),1:size(B,1))
C = A(ia,:) + B(ib,:)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

태그

질문:

2019년 2월 26일

답변:

2019년 2월 26일

Community Treasure Hunt

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

Start Hunting!

Translated by