4

Why does the expression for h(theta) below sometimes return 0 and sometimes return NaN? h(theta) contains a division by zero for theta = 0 and should always return NaN. If I just ask for h(0), it all works fine.

However, when it evaluates a zero contained in a multi-element array, it returns h = 0 when it should return NaN. But if specifically evaluating only the element that is zero, then it returns NaN as it should.

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

The first element should be NaN:

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

When evaluating the zero element specifically it works correctly:

>> 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
1
  • You can put >> to the input lines for formatting and better readability. Commented Jul 27, 2015 at 11:38

1 Answer 1

5

You need to do an element-wise division with ./ instead of / to get the desired result. This is called the right array division.

>> h = tan(theta)./(1+(tan(theta)./tan(2.*theta)))
h =
       NaN    5.4220
Sign up to request clarification or add additional context in comments.

1 Comment

File this under "one more thing MATLAB does contrary to how every other language does it, and contrary to normal expectations"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.