drdot
drdot

Reputation: 3347

Vectorize column wise operation in octave or matlab

How can I vectorize the following code? It is basically computing the mean of each column.

mu(1) = sum(X(:,1))/C
mu(2) = sum(X(:,2))/C

and this (normalized each element, each column has different mean and std): (X is 47x2. mu, sigma are both 1x2)

X_norm(:,1) = (X(:,1)-mu(1))/sigma(1)
X_norm(:,2) = (X(:,2)-mu(2))/sigma(2)

Upvotes: 0

Views: 913

Answers (2)

user3042711
user3042711

Reputation: 11

You can even use mu = mean(X).

Upvotes: 1

Amro
Amro

Reputation: 124543

It's as simple as:

mu = sum(X) ./ C

sum by default operates along the first dimension (on columns).


EDIT:

For the second part of the question:

X_norm = bsxfun(@rdivide, bsxfun(@minus, X, mu), sigma)

It is similar to doing repmat's, but without the memory overhead.

Upvotes: 2

Related Questions