Bisection method in matlab
Friends i write a code of bisection method in matlab.
Here a function named 'ammaraziz' is present. i want to modify this code such that the programme requests user to enter the function and also the lower and higher limits. so help me that what modifications are necessary. Actually i am new to matlab. So help me out to solve this problem the code is as follows:
clear all
clc
ammaraziz = @(x) sin(x);
x_lwr = 0;
x_hgr = 5;
x_mid = (x_lwr + x_hgr)/2;
while abs(ammaraziz(x_mid))>0.01
if (ammaraziz(x_mid) * ammaraziz(x_hgr)) < 0
x_lwr = x_mid;
else
x_hgr = x_mid;
end
x_mid = (x_lwr + x_hgr)/2;
end
fprintf ('The root is %g
' , x_mid)
ezplot(ammaraziz)
Update: Answer
Sure, to request the user to input the function and the upper and lower bounds, you can use the input
function in MATLAB. However, for the function input, it's a bit trickier because MATLAB requires the function to be defined beforehand or to be inputted as a function handle.
I've modified your code below:
clear all
clc
% User inputs for function, lower and upper bounds
fun_str = input('Please enter the function in terms of x: ', 's');
x_lwr = input('Enter the lower limit: ');
x_hgr = input('Enter the upper limit: ');
% Converting string to function handle
ammaraziz = str2func(['@(x)', fun_str]);
x_mid = (x_lwr + x_hgr)/2;
while abs(ammaraziz(x_mid))>0.01
if (ammaraziz(x_mid) * ammaraziz(x_hgr)) < 0
x_lwr = x_mid;
else
x_hgr = x_mid;
end
x_mid = (x_lwr + x_hgr)/2;
end
fprintf ('The root is %g\n' , x_mid)
% Create a figure and plot the function
figure
fplot(ammaraziz, [x_lwr, x_hgr])
In the modified code, input
is used to take the string of function from the user, and lower and upper bounds. str2func
is then used to convert the function string into a function handle. The rest of the code remains the same.
Keep in mind that when you enter the function, it should be in a format that MATLAB understands. For example, you should write x.^2
for x squared, not x^2
. The dot is needed for element-wise operations when x is a vector (which it can be when used in plotting or other MATLAB functions).
In the last line, fplot
is used instead of ezplot
to plot the function. fplot
is more flexible and it takes the function handle directly (while ezplot
does not). You need to specify the plotting range, here the entered bounds [x_lwr, x_hgr]
are used.