MATLAB:Fzero

From PrattWiki
Revision as of 20:03, 10 October 2009 by DukeEgr93 (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

The fzero command in MATLAB can be used to find the value of a single parameter of a multivariable function that will set the function equal to zero (if such a value exists). The command can {\it only} find one root at a time, and can only find roots in one variable at a time. There are several different ways to present fzero with the specific function and variable.

Examples

Most General Case

The following examples show a method that will work regardless of how many input variables your function has or how you define your function - whether it is built-in, a variable containing an anonymous function, an anonymous function generated on the fly, or a .m file function. The example is based on wanting to determine roots of:

\(f(x, y, z)=\cos(x)+\sin(y)+z=0\,\!\)

We assume that two of the three variables \(x\), \(y\), and \(z\) are known and that we are looking for the third.

Single-Variable Built-in Functions and .m Functions

The following method works for both built-in single-input functions and .m file single-input functions (i.e. not variables containing anonymous functions). The first argument is the name of the function in single quotes and the second argument is the initial guess or initial bracket for the one variable of the function. For example, to find the solution to \(\cos(x)=0\) with an initial guess of \(x=1\), you can type

fzero('cos', 1)

and get

ans =

   1.5708e+00

To find the solution for \(x\) values between 2 and 5 radians, you could type:

fzero('cos', [2 5])

and get

ans =

   4.7124e+00

If you have a .m file function of one variable, the process is the same. For example, to find a root of \(y=x^2-\cos(x)\) with an initial guess of 1, you could first create a .m file called "MyFun.m" with:

function out = MyFun(in)
out = in.^2 - cos(in);

then use fzero:

fzero('MyFun', 1)

and get

ans =

   8.2413e-01

Anonymous Functions On The Fly

Questions

Post your questions by editing the discussion page of this article. Edit the page, then scroll to the bottom and add a question by putting in the characters *{{Q}}, followed by your question and finally your signature (with four tildes, i.e. ~~~~). Using the {{Q}} will automatically put the page in the category of pages with questions - other editors hoping to help out can then go to that category page to see where the questions are. See the page for Template:Q for details and examples.

External Links

References