drdot
drdot

Reputation: 3347

Vectorize code with sum operation in octave or matlab

How to vectorize the following code? Edit: theta, y are column vectors; X is matrix; alpha, m are scalars.

   temp1 = theta(1) - alpha/m * sum((X*theta-y).*X(:,1));
   temp2 = theta(2) - alpha/m * sum((X*theta-y).*X(:,2));
   theta(1) = temp1;
   theta(2) = temp2;

I tried the following, but the sum operation does not do what I want...

   temp = alpha/m*sum(bsxfun(@times, (X*theta-y), X))
   theta = bsxfun(@minus, theta, temp)

Upvotes: 0

Views: 391

Answers (1)

Oli
Oli

Reputation: 16035

You need a matrix multiplication to vectorize that.

Probably:

theta = theta - alpha/m*(X'*((X*theta)-y))

Upvotes: 1

Related Questions