0
    function [ y ] = EquationDerivs( x, w )
%EQUATIONDERIVS Summary of this function goes here
%   Detailed explanation goes here

if (w==0.2)
    y = ((0.2*cos(x))+1)/((0.2+cos(x))^2);
elseif (w==0.3)
    y = ((0.3*cos(x))+1)/((0.3+cos(x))^2);
elseif (w==0.4)
    y = ((0.4*cos(x))+1)/((0.4+cos(x))^2);
elseif (w==0.5)
    y = ((0.5*cos(x))+1)/((0.5+cos(x))^2);
elseif (w==0.6)
    y = ((0.6*cos(x))+1)/((0.6+cos(x))^2);
elseif (w==0.7)
    y = ((0.7*cos(x))+1)/((0.7+cos(x))^2);
elseif (w==0.8)
    y = ((0.8*cos(x))+1)/((0.8+cos(x))^2);
elseif (w==0.9)
    y = ((0.9*cos(x))+1)/((0.9+cos(x))^2);
elseif (w==1)
    y = 1/(1+cos(x));
else
    y = -115;
end

end

So I have this simple code to tell matlab when to use a dertiviate of a function based on the value of W and for whatever reason on w==0.3, and a few others the code jumps to the else statement anyone know why? I'll post my command window below but notice how when W is equal to 0.3, 0.6, or 0.9 is just jumps to my else statement?

for W = 0.2:0.1:1
theta = degtorad(30);
yP = feval(@EquationDerivs,theta,W)
end

yP =

    1.0324


yP =

  -115


yP =

    0.8400


yP =

    0.7679


yP =

  -115


yP =

    0.6549


yP =

    0.6099


yP =

  -115


yP =

    0.5359

>> 
MaxSpd
  • 23
  • 4

1 Answers1

0

There are so many things that are not right in that code. I'm going to assume for no that you also could compute w=0.23 and you do not want it to be y = -115;. I can change it later if needed.

Your code can be shortened to:

function [ y ] = EquationDerivs( x, w )
if w<=1
    y = ((w*cos(x))+1)/((w+cos(x))^2);
else 
  y = -115;
end

But independently of writing good code, you have found out the nice world of numerical computing. Try 0.1+0.2==0.3. You will notice its false. This is because computers have finite accuracy and can not represent all numbers. When comparing floating point numbers, you need to compare their difference, as (w-0.3)<1e-6.

If you want to understand that better, read this fantastic answer.

Ander Biguri
  • 35,140
  • 11
  • 74
  • 120
  • Thanks so much! You are so right idk why I didn't think to just replace all the statements by placing w into the equation. – MaxSpd Feb 16 '17 at 09:12
  • @MaxSpd I suggest you learn a bit of programming, this is one of the very very basic ideas behind writing code. If this helped you, consider accepting the answer as valid – Ander Biguri Feb 16 '17 at 09:15
  • 1
    Believe it or not but 2 years of highschool programming didn't even mention this sort of thing we went over writing numbers in binary and hexadecimal but we never went over this. The response you linked was really helpful too thank you again! – MaxSpd Feb 16 '17 at 14:13
  • @MaxSpd Floating point representation can get quite complicated, often basic programming courses try to avoid it because of that. However, as soon as you start doing real maths in a computer, its essential. – Ander Biguri Feb 16 '17 at 14:15