矢量化二维卡方检索

时间:2017-05-24 14:27:35

标签: matlab vectorization

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

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

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

下面是Matlab代码,在AB个参数值(每个100个值)的10,000种组合中,使用卡方值填充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  

1 个答案:

答案 0 :(得分: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.