代码之家  ›  专栏  ›  技术社区  ›  user366312

为什么高斯函数会给出不一致的参数误差?

  •  -1
  • user366312  · 技术社区  · 6 年前
    function m=gaussian(med, var, n)
      if ( mod(n, 2)==0 )
          n=n+1;
      end;
    
      med=double(med);
      var=double(var);
    
      med = min (max(-(n+1)/2, med),  (n+1)/2);
    
      m=zeros(1,n);
    
      k1=(1/(2*pi*var)^0.5);
      k2=-0.5.*((med-(1:n)).^2)./var;
    
      m(1,1:n)=k1.*exp(k2);
    

    输出1

    >> gaussian([101 2 ; 3 4], [4 301 ; 2 1], [2 2])
    error: gaussian: operator /: nonconformant arguments (op1 is 1x1, op2 is 2x2)
    error: called from
        gaussian at line 13 column 5
    >>
    

    输出2

    >> gaussian([101 2 ; 3 4], [4 301 ; 2 1], 2)
    error: gaussian: operator /: nonconformant arguments (op1 is 1x1, op2 is 2x2)
    error: called from
        gaussian at line 13 column 5
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   carandraug    6 年前

    我不确定你想要的结果是什么,但你得到这个错误,因为你正在做 matrix division 标量的( [1x1] 尺寸)通过 [2x2] 矩阵。注意,你在做矩阵除法( / ./ 操作员)。

    octave:1> function m=gaussian(med, var, n)
    >   if ( mod(n, 2)==0 )
    >       n=n+1;
    >   end;
    > 
    >   med=double(med);
    >   var=double(var);
    > 
    >   med = min (max(-(n+1)/2, med),  (n+1)/2);
    > 
    >   m=zeros(1,n);
    > 
    >   k1=(1/(2*pi*var)^0.5);
    >   k2=-0.5.*((med-(1:n)).^2)./var;
    > 
    >   m(1,1:n)=k1.*exp(k2);
    > endfunction
    octave:2> debug_on_error (1)
    octave:3> gaussian ([101 2 ; 3 4], [4 301 ; 2 1], 2)
    error: gaussian: operator /: nonconformant arguments (op1 is 1x1, op2 is 2x2)
    error: called from
        gaussian at line 13 column 5
    stopped in gaussian at line 13
    13:   k1=(1/(2*pi*var)^0.5);
    debug> (2*pi*var)
    ans =
    
         25.1327   1891.2388
         12.5664      6.2832
    
    debug> 1/(2*pi*var) # matrix division
    error: gaussian: operator /: nonconformant arguments (op1 is 1x1, op2 is 2x2)
    error: called from
        gaussian at line 13 column 5
    debug> 1./(2*pi*var) # your element by element division works
    ans =
    
       0.03978874   0.00052875
       0.07957747   0.15915494
    

    但是,这并不是唯一的问题,因为下一行对于减号运算符也有类似的问题:

    error: gaussian: operator -: nonconformant arguments (op1 is 2x2, op2 is 1x3)
    error: called from
        gaussian at line 14 column 5
    stopped in gaussian at line 14
    14:   k2=-0.5.*((med-(1:n)).^2)./var;
    

    或者,可能函数没有错误,而您得到这些错误是因为您错误地调用了函数。