MATLAB: Adding two matrixes with different row numbers.

MATLABmatrixmatrix arraymatrix manipulationsimulinksum

Hi Mathworks community!
I have a matrix A(mxn) and a matrix B(lxn) such as:
A = [1,2,3,4,5,6,7,8,9,10; 10,11,12,13,14,15,16,17,18,19; 19,20,21,22,23,24,25,26,27,28];
B = [1,2,3,4,5,6,7,8,9,10; 2,4,6,8,10,12,14,18,18,20];
I'd like to get an output such as:
out = [sum(A(1,:),B(1,:)); sum(A(1,:),B(2,:)); sum(A(2,:),B(1,:)); sum(A(2,:),B(2,:)); sum(A(3,:),B(1,:)); sum(A(3,:),B(2,:))];
Any idea about how I could code this efficiently?
Thank's in advance!
Santos García

Best Answer

A = [1,2,3,4,5,6,7,8,9,10; 10,11,12,13,14,15,16,17,18,19; 19,20,21,22,23,24,25,26,27,28];
B = [1,2,3,4,5,6,7,8,9,10; 2,4,6,8,10,12,14,18,18,20];
[Y,X] = ndgrid(1:size(B,1),1:size(A,1));
out = A(X(:),:) + B(Y(:),:)
out = 6×10
2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 26 27 30 11 13 15 17 19 21 23 25 27 29 12 15 18 21 24 27 30 35 36 39 20 22 24 26 28 30 32 34 36 38 21 24 27 30 33 36 39 44 45 48