MATLAB Answers

How to avoid looping of anonymous function?

3 views (last 30 days)
BHUSHAN MAHAJAN
BHUSHAN MAHAJAN on 4 Feb 2020
Commented: Matt J on 5 Feb 2020
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 Comments

Geoff Hayes
Geoff Hayes on 4 Feb 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').
BHUSHAN MAHAJAN
BHUSHAN MAHAJAN on 5 Feb 2020
Thanks Geoff for explaining what actually is happening. I will try str2func.

Sign in to comment.

Answers (1)

Matt J
Matt J on 4 Feb 2020
Edited: Matt J on 4 Feb 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 Comments

Matt J
Matt J on 5 Feb 2020
You're welcome. Please Accept-click the answer if it works.

Sign in to comment.

Sign in to answer this question.

Products


Release

R2018b