CaptainProg
CaptainProg

Reputation: 5690

Applying different functions to different columns of a matrix

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

Answers (3)

user1164811
user1164811

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

Bill Cheatham
Bill Cheatham

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

tim
tim

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

Related Questions