Adding one matrix with another matrix in MATLAB
I am trying to add a matrix with a different matrix in MATLAB.
The first matrix looks like this:
0.0963928845397177 1.30250820960714
-0.830468497619261 1.40991150001902
-0.352252185662263 -1.66254297035808
-0.174775039544099 1.94368447839214
-0.480653419481013 -1.08469845223762
0.836836711417678 0.226818975021420
2.53834934138902 1.09892920248474
-1.32333425148040 0.147188752472257
0.128340263343307 2.29566581301284
-1.44237915336114 2.75255787759549
The second matrix looks like this:
[1 2]
I want to add a second matrix with the first matrix => the value 0.0963928845397177 + 1 and 1.30250820960714 + 2. I want to add 1 to the first column and 2 to the second column.
What I have tried:
secondmatrix .+ firstmatrix
But it doesn't work.
You need to be guided.
You can do it:
A = ones(5,2)
B=[1,2]
C = A+repmat(B,size(A,1),1)
or
C = [A(:,1)+B(1,1) A(:,2)+B(1,2)]
It is probably best avoided repmat
if you can for efficiency if you are going to use this with large matrices. Similar to the approach [A(:,1)+b(1) A(:,2)+b(2)]
. I'm a fan bsxfun
:
bsxfun(@plus, A, b)
Either Jommy suggested , or you can replicate a smaller matrix to make it the same size and then add like this:
C = A + repmat(B,[size(A,1),1]);
try it
sum_ = first_matrix + repmat(second_matrix,size(first_matrix,1),1);
Matlab provides a function for what you want to do, bsxfun , which "Applies a one-by-item binary operation to two arrays with single color expansion enabled"
Sample code:
result_matrix = bsxfun(@plus, firstmatrix, secondmatrix);
If A
is a large matrix and B
is a small one you can write
C = [A(:,1)+B(1) A(:,2)+B(2)];
Another possibility is
C = A + repmat(B, [length(A) 1]);