为什么我不能计算CostFunction J.

时间:2015-06-15 15:50:33

标签: matlab machine-learning

这是我CostFunctionJ的实现:

    function J = CostFunctionJ(X,y,theta)

    m = size(X,1);
    predictions = X*theta;
    sqrErrors =(predictions - y).^2;

    J = 1/(2*m)* sum(sqrErrors);

但是当我尝试在MATLAB中输入命令时:

>> X = [1 1; 1 2; 1 3];
>> y = [1; 2; 3];
>> theta = [0,1];
>> J = CostFunctionJ(X,y,theta)

它给了我以下错误:

Error using  * 
Inner matrix dimensions must agree.
Error in CostFunctionJ (line 4)
predictions = X*theta;

1 个答案:

答案 0 :(得分:1)

正如评论中所建议的那样,错误是因为x维度为3x2theta维度为1x2,因此您无法X*theta }。

我怀疑你想要:

theta = [0;1]; % note the ; instead of ,
% theta is now of dimension 2x1
% X*theta is now a legit operation

会导致:

>> predictions = X*theta
predictions =

   1
   2
   3