Function isn't returning anything
이전 댓글 표시
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
답변 (1개)
Geoff Hayes
2015년 3월 7일
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
QingQangQong
2015년 3월 7일
Geoff Hayes
2015년 3월 7일
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.
QingQangQong
2015년 3월 7일
편집: QingQangQong
2015년 3월 7일
카테고리
도움말 센터 및 File Exchange에서 Assumptions에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!