【问题标题】:Vectorize 2d chi-square grid search向量化 2d 卡方网格搜索
【发布时间】:2017-05-24 14:27:35
【问题描述】:

最佳拟合线性参数 A 和 B (y=Ax+b) 对应于这些参数上的卡方函数的最小值。我想对全局最小值进行蛮力网格搜索(保证,因为 2 参数线性卡方是抛物面)并通过 3 个嵌套循环(如下)实现了它,但希望避免循环(即,使用数组属性进行矢量化)。

卡方(加权最小二乘)定义为(伪代码):

卡方(k,j) = sum (y[i]-(A[k]*x[i]+B[j]))/yerr[i])^2.

以下是 Matlab 代码,它使用 AB 参数值的 10,000 个组合(每个 100 个值)的卡方值填充 100 x 100 网格。共有三个数据数组:xyyerr

感谢您对 2 参数线性卡方网格的无环版本的任何帮助!

基思

 % create parameter grid
  a = linspace(85,110,100);
  b = linspace(10,35,100);
  [A,B] = meshgrid(a,b);

  % calculate chi-square over parameter grid
  chi2(100,100) = zeros;

  for k = 1:100;
      for j = 1:100;
          for i = 1:length(y)
          chi2a = ((y(i)-a(k)*x(i)-b(j))/yerr(i)).^2;
          chi2(k,j) = chi2(k,j)+chi2a;
          end
      end
  end  

【问题讨论】:

    标签: matlab vectorization


    【解决方案1】:

    我们可以bsxfun它-

    x3d = reshape(x,1,1,numel(x));
    y3d = reshape(y,1,1,numel(y));
    yerr3d = reshape(yerr,1,1,numel(yerr));
    p0 = bsxfun(@minus, bsxfun(@minus,y3d,bsxfun(@times,a(:),x3d)), b);
    p1 = bsxfun(@rdivide, p0, yerr3d);
    out = sum(p1.^2,3);
    

    使用 MATLAB 的隐式扩展,计算 p0p1 将简化为 -

    p0 = ((y3d - a(:).*x3d) - b);
    p1 = p0 ./yerr3d;
    

    时间安排 -

    % Setup
    N = 2000;
    x = rand(N,1);
    y = rand(N,1);
    yerr = rand(N,1);
    
    a = linspace(85,110,100);
    b = linspace(10,35,100);
    

    我们得到 -

    ----------- With loopy method -------------------------
    Elapsed time is 1.056787 seconds.
    ----------- With BSXFUN method -------------------------
    Elapsed time is 0.109601 seconds.
    

    【讨论】:

    • 谢谢你——这很有帮助!!
    猜你喜欢
    • 2014-07-19
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 2016-10-09
    • 2019-12-06
    • 2017-03-28
    相关资源
    最近更新 更多