I had a working bisection method but I need to implement it in a function that will take three arguments: f the function being used, xL the left side of the boundary, and xR the right side of the boundary. Furthermore it has to have the ability to change the function based on the value of x (if the function was f(x) for example). if x is less than or equal zero, f(x) will be x^3 + 3x + 1, if x is greater that zero then f(x) will be 1 + sin(x). The function needs to output the root and the number of iterations performed
How can I pass a function for f is the function arguments, and then how can I find the value of x to determine which function to use?
Here are the errors I am getting along with the console input:
>> f = inline('x^3 + 3x + 1', 'x')
f =
Inline function:
f(x) = x^3 + 3x + 1
>> bisectionF(f,-2,0.1)
Undefined function or variable 'bisectionF'.
>> bisectionF(f,-2,0.1)
Undefined function or variable 'B'.
Error in bisectionF (line 3)
maxIters = 20;B
>> bisectionF(f,-2,0.1)
Error using inlineeval (line 14)
Error in inline expression ==> x^3 + 3x + 1
Error: Unexpected MATLAB expression.
Error in inline/feval (line 33)
INLINE_OUT_ = inlineeval(INLINE_INPUTS_, INLINE_OBJ_.inputExpr, INLINE_OBJ_.expr);
Error in bisectionF (line 7)
fM = feval(f,xM);
>> y = bisectionF('f1',-2,0.1)
Error using feval
Undefined function 'f1' for input arguments of type 'double'.
Error in bisectionF (line 9)
fM = feval(f,xM);
>> f1 = inline('x^3 + 3x + 1', 'x');
>> root = bisectionF(f1,-2,0.1)
Error using inlineeval (line 14)
Error in inline expression ==> x^3 + 3x + 1
Error: Unexpected MATLAB expression.
Error in inline/feval (line 33)
INLINE_OUT_ = inlineeval(INLINE_INPUTS_, INLINE_OBJ_.inputExpr, INLINE_OBJ_.expr);
Error in bisectionF (line 9)
fM = feval(f,xM);
Here is my code:
function[r, iters] = bisectionF(f,xL,xR)
%f1 = inline('x^3 + 3x + 1', 'x');
%f2 = inline('1+sin(x)','x');
maxIters = 20;
precision = 10^(-5);
for j = 1:maxIters
xM=(xL + xR)/ 2;
fM = feval(f,xM);
fL = feval(f,xL);
fR = feval(f,xR);
if fM * fL < 0
xR = xM
elseif fM * fR < 0
xL = xM;
end
if abs(fM) < precision
disp(['Iterations performed: ', num2str(j)])
disp('Convergence was reached')
elseif(j==20)
disp('The maximum number of iterations were performed')
end
r = xM;
iters = j;
end