【问题标题】:Why does Matlab incorrectly return 0 when evaluating an array, but correctly return NaN when evaluating a scalar?为什么 Matlab 在评估数组时错误地返回 0,但在评估标量时正确地返回 NaN?
【发布时间】:2015-10-17 13:41:47
【问题描述】:

为什么下面h(theta) 的表达式有时会返回0,有时会返回NaNh(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

【问题讨论】:

  • 您可以将>> 放在输入行中,以便格式化和提高可读性。

标签: matlab nan


【解决方案1】:

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

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

【讨论】:

  • 将此归档在“MATLAB 所做的另一件事与其他所有语言的做法相反,并且与正常预期相反”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
  • 2016-01-16
  • 2012-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多