Reputation: 3347
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
Reputation: 16035
You need a matrix multiplication to vectorize that.
Probably:
theta = theta - alpha/m*(X'*((X*theta)-y))
Upvotes: 1