MATLAB: How to create a function and run it.

functionm-fileMATLABmatlab function

I don't know anything about MATLAB beyond how to create a new script file and type stuff into it.
I copied the following code from a course handout. So I assume it is correct.
%Program 1.1 Bisection Method
%Computes approximate solution of f(x)=0
%Input: function handle f; a,b such that f(a)*f(b)<0,and tolerance tol
%Output: Approximate solution xc
xc=bisect(f,a,b,tol)
if sign(f(a))*sign(f(b)) >= 0
error('f(a)f(b)<0 not satisfied!') %ceases execution
end
fa=f(a)
fb=f(b)
while (b-a)/2>tol
c=(a+b)/2;
fc=f(c);
if fc == 0 %c is a solution, done
break
end
end
if sign(fc)*sign(fa)<0 %a and c make the new interval
b=c;fb=fc;
else %c and b make the new interval
a=c;fa=fc;
end
xc=(a+b)/2;
It is supposed to solve a single-variable equation by bisection. I understand the bisection logic and the function flow logic seems obvious to me.
I want to give it a function, say x^5+x=1, and have it bracket in on x and get something close to 0.754877666. What do I type into the MATLAB command window to do this?
Question 2. Where do I find answers to simple questions like this? Is there a list of simple examples somewhere? I have gone through the "onramp" stuff and read the MATLAB Primer, which took hours, without learning how to just pass some variables to a pre-defined function.

Best Answer

Every function in MATLAB uses the following structure:
function [ouput_vars] = foo(input,vars)
%
% Code goes here....
%
end
In your case, you want the first line to read:
function xc = bisect(funcHandle, a, b, tol)
where funcHandle is a handle for your function. The syntax of a function handle is:
funcHandle = @(variables)(equation)
To use the function, you simply call the variable name as a function, i.e.
f_of_x = funcHandle(pi);
Since your bisection method expects a function of the form f(x) = 0, your function handle would be,
your_fun = @(x)(x^5 + x -1);
Hope this helps!!