Reputation: 5690
I have a MATLAB matrix with 2 columns in which I would like to apply separate functions to each column. Specifically, I want to add 5 to one column, and 3 to the other.
For example,
a = 0 4
2 5
3 7
. .
. .
. .
would become
a = 5 9
7 10
8 12
. .
. .
. .
I know I can add the same value to both column with a simple a = a + x
, but in this case I am trying to assign different numbers to add to each side.
Upvotes: 0
Views: 101
Reputation:
You can do it as below
a(:,1)=a(:,1)+5;
a(:,2)=a(:,2)+3;
Edit: More General Code :D
function [Result]=AddColumn(A, B)
[aRows aCols]=size(A);
[bRows bCols]=size(B);
if(aCols~=bCols || bRows>1)
ErrorMessage='not Matched'
return;
end;
B=B'
X=B*ones(1,aRows);
X=X';
Result=A+X;
end
Upvotes: 0
Reputation: 11917
A different way of doing this, this time using repmat:
>> a = [0 4; 2 5; 3 7; 1 2]
a =
0 4
2 5
3 7
1 2
>> a = a + repmat([5, 3], size(a, 1), 1)
a =
5 7
7 8
8 10
6 5
Upvotes: 1
Reputation: 10176
You could easily add the numbers like the following:
a = ones(5, 2)
b = [2 5]
c = bsxfun(@plus, a, b)
which will give you:
a =
1 1
1 1
1 1
1 1
1 1
b =
2 5
c =
3 6
3 6
3 6
3 6
3 6
bsxfun
also offers a lot more operations, look here: http://www.mathworks.de/help/techdoc/ref/bsxfun.html
Upvotes: 4