Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute the sum of vectors

I know this question has been asked multiple times but that answer is not working for me. I want to compute summation like this

equivation,

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.

like image 903
vihang shah Avatar asked Jan 21 '26 23:01

vihang shah


1 Answers

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 ^.

like image 126
Cris Luengo Avatar answered Jan 24 '26 18:01

Cris Luengo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!