为什么 Matlab 在评估数组时错误地 return 0,但在评估标量时正确地 return NaN?

Why does Matlab incorrectly return 0 when evaluating an array, but correctly return NaN when evaluating a scalar?

为什么下面 h(theta) 的表达式有时 return 0 而有时 return NaNh(theta) 包含 theta = 0 的零除,并且应该始终 return NaN。如果我只要求 h(0),一切正常。

但是,当它计算包含在多元素数组中的零时,它 return 在它应该 return NaNh = 0。但是,如果只专门评估为零的元素,那么它应该 returns NaN

>> theta = [0 1]
theta =
     0     1

第一个元素应该是NaN:

>> h = tan(theta)/(1+(tan(theta)/tan(2.*theta)))
h =
     0    5.4220 

在具体评估零元素时它可以正常工作:

>> h = tan(theta(1))/(1+(tan(theta(1))/tan(2.*theta(1))))
h =
     NaN 

>> h = tan(theta(2))/(1+(tan(theta(2))/tan(2.*theta(2))))
h =
     5.4220

您需要使用 ./ 而不是 / 进行逐元素除法以获得所需的结果。这叫做右数组划分.

>> h = tan(theta)./(1+(tan(theta)./tan(2.*theta)))
h =
       NaN    5.4220