为什么这个高斯函数给出不一致的参数错误?

Why does this Gaussian function give nonconformant arguments error?

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

我不确定你想要的结果是什么,但你得到了那个错误,因为你正在通过 [2x2] 矩阵对标量([1x1] 维度)进行 matrix division .请注意,您正在进行矩阵除法(/ 运算符)而不是逐元素除法(./ 运算符)。

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;

或者,也许函数并没有错,而你之所以会遇到这些错误是因为你调用的函数不正确。