How to avoid looping of anonymous function?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
I am trying this code of bisection method in matlab where I take function through input from user but for every iteration of while loop in asks input. How should I do so that input is given only once.
a=input('guess1: ');
b=input('guess2: ');
acc=input('accuracy: ');
f=@(x)input('enter function: ');
x1=f(a);
x2=f(b);
while (abs(x1-x2)>acc)
c=((a+b)/2);
x3=f(c);
if x1*x3<0
b=c;
x2=x3;
else
a=c;
x1=x3;
end
end
when I run this its like:
bisection
guess1: 0
guess2: 1
accuracy: 0.01
enter function: cos(x)-1.3*x
enter function: cos(x)-1.3*x
enter function: cos(x)-1.3*x
enter function: cos(x)-1.3*x
enter function: cos(x)-1.3*x
enter function: cos(x)-1.3*x
enter function: cos(x)-1.3*x
enter function: cos(x)-1.3*x
enter function: cos(x)-1.3*x
enter function: cos(x)-1.3*x
ans: 0.623047>>
2 comentarios
Geoff Hayes
el 4 de Feb. de 2020
Bhushan - there isn't a looping problem (per se) but rather how you have defined your anonymous function
f=@(x)input('enter function: ');
Whenever you call f like with
x1=f(a);
x2=f(b);
the body of your function f will call input('enter function: ') because that is how you have defined f.
I understand what you are trying to do - you want the user to enter a function that you will then evaluate using the bisection method. You may want to look at str2func and in particular couple of the examples on how to create an anonymous function (the input string would need to be in the format '@(x)cos(x) - 1.3*x').
Respuestas (1)
Matt J
el 4 de Feb. de 2020
Editada: Matt J
el 4 de Feb. de 2020
You could make it the end-user's responsibility to enter the function in anonymous form,
>> f=input('Enter anonymous function: ');
Enter anonymous function: @(x)cos(x)-1.3*x
>> f
f =
function_handle with value:
@(x)cos(x)-1.3*x
As Geoff alluded, you can also use str2func,
>> f=str2func( "@(x)"+input('Enter a function of x: ') )
Enter a function of x: 'cos(x)-1.3*x'
f =
function_handle with value:
@(x)cos(x)-1.3*x
2 comentarios
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!