为什么下面的 h(theta)
表达式有时返回 0
有时返回 NaN
? h(theta)
包含对 theta = 0
的零除,并且应始终返回 NaN
。如果我只要求 h(0)
,一切正常。
但是,当它计算包含在多元素数组中的零时,它返回 h = 0
而它应该返回 NaN
。但是,如果仅专门评估为零的元素,则它会按原样返回 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
关于matlab - 为什么 Matlab 在评估数组时错误地返回 0,但在评估标量时正确返回 NaN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31651941/