【问题标题】:Vectorize code with sum operation in octave or matlab在 octave 或 matlab 中使用求和运算对代码进行矢量化
【发布时间】:2014-07-07 10:01:33
【问题描述】:

如何向量化以下代码? 编辑: theta, y 是列向量; X是矩阵; alpha, m 是标量。

   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;

我尝试了以下,但求和运算并没有做我想要的......

   temp = alpha/m*sum(bsxfun(@times, (X*theta-y), X))
   theta = bsxfun(@minus, theta, temp)

【问题讨论】:

  • theta 是行向量还是列向量?
  • sum 运算符做了什么,你想让它做什么而不是做什么?
  • 两个版本在做不同的事情...正确答案如下..

标签: matlab octave vectorization


【解决方案1】:

你需要一个矩阵乘法来向量化它。

大概:

theta = theta - alpha/m*(X'*((X*theta)-y))

【讨论】:

    猜你喜欢
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 2012-05-19
    相关资源
    最近更新 更多