I know this question has been asked multiple times but that answer is not working for me. I want to compute summation like this
,
where h(x) = X*theta, theta is nx1 matrix and X is an mxn matrix. I tried to write in this way:
f = @(z)(sum(X(z,:)*theta) - y(z))^2;
v = sum(f([1:m])); % m is length of y
But it gave me this error:
error: for x^A, A must be a square matrix. Use .^ for elementwise power.
error: called from
computeCost>@<anonymous> at line 26 column 35
computeCost at line 27 column 4
ex1 at line 63 column 3
My equivalent for loop version is like this:
v = 0;
for i = 1:m
v = v + (sum(X(i,:)*theta) - y(i))^2;
end
Please let me know how I can vectorize this loop.
This code:
v = 0;
for i = 1:m
v = v + (sum(X(i,:)*theta) - y(i))^2;
end
is identical to this code:
v = 0;
for i = 1:m
v = v + (X(i,:)*theta - y(i))^2;
end
(hint: X(i,:)*theta is a dot product, and returns a scalar).
To vectorize this, simply sum across the result:
v = (X*theta - y).^2;
v = sum(v);
This assumes that y is a column matrix (mx1). Note I used .^ as indicated by your error message. This is the per-element power, rather than the matrix power ^.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With