# fzero function with cases

2 views (last 30 days)
Simo on 15 May 2020
Answered: Star Strider on 16 May 2020
I have to search for the zero of a function that has 2 cases , but it doesn't work
Are there other way to define a function that has cases?
e = 0.1;
zeri=zeros(length(step),1);
i=1;
f=@(e,par) (par==1).*((sqrt(2*mass*e/h2))*sin(sqrt(2*mass*e/h2)*a)-(sqrt(2*mass*(vo-e)/h2))*cos(sqrt(2*mass*e/h2)*a))+(par==2).*((sqrt(2*mass*e/h2))*cos(sqrt(2*mass*e/h2)*a)+(sqrt(2*mass*(vo-e)/h2))*sin(sqrt(2*mass*e/h2)*a));
par = 1; % ^case 1 ^case 2
while e<vo
try y = fzero(f, [e,e+0.1]);
line([-a a],[y y],'Color','red');
zeri(i)=y;
i = i +1
if par==1
par=2
else
par=1
end
end
end
e = e +0.1

Star Strider on 16 May 2020
The correct way to use ‘f’ with fzero in the posted code is:
y = fzero(@(e)f(e,par), [e,e+0.1]);
There are too many missing variables to be able to run your code (and I have no idea what you are doing with half of a try-catch block).
Also, there may be problems using the limits for fzero, since there may not be a zero-crossing between those values.