0

My code is given below i get this error :

The expression to the left of the equals sign is not a valid target for an assignment.

It points to Temp1(i) = ( ( X(i,1)*theta(i,1) + X(i,2)*theta(i,2) ) - y(i));

I dont understand what is wrong here. Please help

Temp1 = zeros(m);
sum1 = 0;
for i = 1:1:m
{
    Temp1(i) = ( ( X(i,1)*theta(i,1) + X(i,2)*theta(i,2) ) - y(i));

    sum1 = sum1 + (Temp1(i)^2);
}

J = sum1 / (2*m);
fprintf(' The value of J = ');
fprintf('%f', J);
return J; 
4

3 回答 3

2

您可以将整个代码矢量化为:

J = sum( (sum(X.*theta,2) - y).^2 ) ./ (2*m);
于 2012-07-25T19:18:37.550 回答
1

您的代码应阅读

Temp1 = zeros(m);
sum1 = 0;
for i = 1:1:m

    Temp1(i) = ( ( X(i,1)*theta(i,1) + X(i,2)*theta(i,2) ) - y(i));

    sum1 = sum1 + (Temp1(i)^2);
end


J = sum1 / (2*m);

fprintf(' The value of J = ');
fprintf('%f', J);

即您不使用大括号,而是 for 循环具有以下语法:

for i=1:10
    .
    .
    .
end
于 2012-07-25T17:39:37.420 回答
0

尽管这可能无法直接回答您的问题,但我相信您可能对调用zeros(m). 这实际上会产生一个m x m零矩阵。根据上面的代码,您似乎只是将 temp 变量视为向量。尝试zeros(m,1)制作一个矢量。

于 2012-07-25T17:41:02.100 回答