Function isn't returning anything
2 views (last 30 days)
Show older comments
At the moment I have this function which I would like to determine if there is a critical point of the function f on the interval on the interval [a,b]. If there is I'd like it to return 1 for a relative max and -1 for a relative min, and 0 if it is not on the interval. At the moment I do not have the anything for returning the 0 because currently it only spits out v and ac given they are not suppressed for debugging. I can't really see any reason it isn't giving me something for n. Any and all help is much appreciated.
function n = myanalyzecp(f,a,b)
syms x i
v = diff(f(x))
ac = diff(diff(f(x)))
for i=[a:b]
if subs(v,a)==0
if subs(ac,a)>0
n==1
return
else if subs(ac,a)<0
n==-1
return
end
end
end
end
0 Comments
Answers (1)
Geoff Hayes
on 7 Mar 2015
QingQangQong - note that in your code, you are using n as either
n==1
or
n==-1
The == is used when you want to check to see if two objects are identical. If you wish to assign 1 or -1 to n then use the equals sign
n = 1;
or
n = -1;
But even that might not fix the problem as you may not always satisfy either the if or the elseif conditions. In that case, you should assign a default value for n prior to entering the for loop.
3 Comments
Geoff Hayes
on 7 Mar 2015
Try stepping through the code (using the debugger). On each iteration of the for loop, check to see what
subs(v,a)
is returning. Is this a double which you can compare with zero, or is it of some other data type?
Note that trying to check whether a floating point value (if that is what subs(v,a) is returning) is identical to zero is not appropriate/possible due to the nature of the data type (with integers you can do this comparison, but not with doubles). When comparing in this fashion, you should check to see if the value is close to zero (within some tolerance), and if so, then consider it to be zero. Something like
tol = 0.000001;
if abs(subs(v,a)) < tol
if subs(ac,a)>0
n==1
return
else if subs(ac,a)<0
n==-1
return
end
end
end
tol is just the tolerance you use to determine whether the number can be considered zero or not.
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!