Wednesday, August 5, 2009

fprintf (serial)

Write text to the device

Syntax

  • fprintf(obj,'cmd')
    fprintf(obj,'format','cmd')
    fprintf(obj,'cmd','mode')
    fprintf(obj,'format','cmd','mode')

Arguments


obj
A serial port object.
'cmd'
The string written to the device.
'format'
C language conversion specification.
'mode'
Specifies whether data is written synchronously or asynchronously.

Description

fprintf(obj,'cmd') writes the string cmd to the device connected to obj. The default format is %s\n. The write operation is synchronous and blocks the command line until execution is complete.

fprintf(obj,'format','cmd') writes the string using the format specified by format. format is a C language conversion specification. Conversion specifications involve the % character and the conversion characters d, i, o, u, x, X, f, e, E, g, G, c, and s. Refer to the sprintf file I/O format specifications or a C manual for more information.

fprintf(obj,'cmd','mode') writes the string with command line access specified by mode. If mode is sync, cmd is written synchronously and the command line is blocked. If mode is async, cmd is written asynchronously and the command line is not blocked. If mode is not specified, the write operation is synchronous.

fprintf(obj,'format','cmd','mode') writes the string using the specified format. If mode is sync, cmd is written synchronously. If mode is async, cmd is written asynchronously.

Remarks

Before you can write text to the device, it must be connected to obj with the fopen function. A connected serial port object has a Status property value of open. An error is returned if you attempt to perform a write operation while obj is not connected to the device.

The ValuesSent property value is increased by the number of values written each time fprintf is issued.

An error occurs if the output buffer cannot hold all the data to be written. You can specify the size of the output buffer with the OutputBufferSize property.

If you use the help command to display help for fprintf, then you need to supply the pathname shown below.

  • help serial/fprintf

Synchronous Versus Asynchronous Write Operations

By default, text is written to the device synchronously and the command line is blocked until the operation completes. You can perform an asynchronous write by configuring the mode input argument to be async. For asynchronous writes:

  • The BytesToOutput property value is continuously updated to reflect the number of bytes in the output buffer.
  • The M-file callback function specified for the OutputEmptyFcn property is executed when the output buffer is empty.

You can determine whether an asynchronous write operation is in progress with the TransferStatus property.

Synchronous and asynchronous write operations are discussed in more detail in Controlling Access to the MATLAB Command Line.

Rules for Completing a Write Operation with fprintf

A synchronous or asynchronous write operation using fprintf completes when:

  • The specified data is written.
  • The time specified by the Timeout property passes.

Additionally, you can stop an asynchronous write operation with the stopasync function.

Rules for Writing the Terminator

All occurrences of \n in cmd are replaced with the Terminator property value. Therefore, when using the default format %s\n, all commands written to the device will end with this property value. The terminator required by your device will be described in its documentation.

Example

Create the serial port object s, connect s to a Tektronix TDS 210 oscilloscope, and write the RS232? command with the fprintf function. RS232? instructs the scope to return serial port communications settings.

  • s = serial('COM1');
    fopen(s)
    fprintf(s,'RS232?')

Because the default format for fprintf is %s\n, the terminator specified by the Terminator property was automatically written. However, in some cases you might want to suppress writing the terminator. To do so, you must explicitly specify a format for the data that does not include the terminator, or configure the terminator to empty.

  • fprintf(s,'%s','RS232?')

fprintf

Write formatted data to file

Syntax

  • count = fprintf(fid,format,A,...)

Description

count = fprintf(fid,format,A,...) formats the data in the real part of matrix A (and in any additional matrix arguments) under control of the specified format string, and writes it to the file associated with file identifier fid. fprintf returns a count of the number of bytes written.

Argument fid is an integer file identifier obtained from fopen. (It may also be 1 for standard output (the screen) or 2 for standard error. See fopen for more information.) Omitting fid causes output to appear on the screen.

Format String

The format argument is a string containing C language conversion specifications. A conversion specification controls the notation, alignment, significant digits, field width, and other aspects of output format. The format string can contain escape characters to represent non-printing characters such as newline characters and tabs.

Conversion specifications begin with the % character and contain these optional and required elements:

  • Flags (optional)
  • Width and precision fields (optional)
  • A subtype specifier (optional)
  • Conversion character (required)

You specify these elements in the following order:

Flags

You can control the alignment of the output using any of these optional flags.


Character
Description
Example
A minus sign (-)
Left-justifies the converted argument in its field.
%-5.2d
A plus sign (+)
Always prints a sign character (+ or -).
%+5.2d
Zero (0)
Pad with zeros rather than spaces.
%05.2d

Field Width and Precision Specifications

You can control the width and precision of the output by including these options in the format string.


Character
Description
Example
Field width
A digit string specifying the minimum number of digits to be printed.
%6f
Precision
A digit string including a period (.) specifying the number of digits to be printed to the right of the decimal point.
%6.2f

Conversion Characters

Conversion characters specify the notation of the output.


Specifier
Description
%c
Single character
%d
Decimal notation (signed)
%e
Exponential notation (using a lowercase e as in 3.1415e+00)
%E
Exponential notation (using an uppercase E as in 3.1415E+00)
%f
Fixed-point notation
%g
The more compact of %e or %f, as defined in [2]. Insignificant zeros do not print.
%G
Same as %g, but using an uppercase E
%i
Decimal notation (signed)
%o
Octal notation (unsigned)
%s
String of characters
%u
Decimal notation (unsigned)
%x
Hexadecimal notation (using lowercase letters a-f)
%X
Hexadecimal notation (using uppercase letters A-F)

Conversion characters %o, %u, %x, and %X support subtype specifiers. See Remarks for more information.

Escape Characters

This table lists the escape character sequences you use to specify non-printing characters in a format specification.


Character
Description
\b
Backspace
\f
Form feed
\n
New line
\r
Carriage return
\t
Horizontal tab
\\
Backslash

\'' or ''

(two single quotes)

Single quotation mark
%%
Percent character

Remarks

The fprintf function behaves like its ANSI C language namesake with these exceptions and extensions.

  • If you use fprintf to convert a MATLAB double into an integer, and the double contains a value that cannot be represented as an integer (for example, it contains a fraction), MATLAB ignores the specified conversion and outputs the value in exponential format. To successfully perform this conversion, use the fix, floor, ceil, or round functions to change the value in the double into a value that can be represented as an integer before passing it to sprintf.
  • The following, non-standard subtype specifiers are supported for the conversion characters %o, %u, %x, and %X.


    b
    The underlying C data type is a double rather than an unsigned integer. For example, to print a double-precision value in hexadecimal, use a format like '%bx'.
    t
    The underlying C data type is a float rather than an unsigned integer.

  • For example, to print a double value in hexadecimal use the format '%bx'
  • The fprintf function is vectorized for nonscalar arguments. The function recycles the format string through the elements of A (columnwise) until all the elements are used up. The function then continues in a similar manner through any additional matrix arguments.
    Note fprintf displays negative zero (-0) differently on some platforms, as shown in the following table.



Conversion Character
Platform
%e or %E
%f
%g or %G
PC
0.000000e+000
0.000000
0
SGI
0.000000e+00
0.000000
0
HP700
-0.000000e+00
-0.000000
0
Others
-0.000000e+00
-0.000000
-0

Examples

The statements

  • x = 0:.1:1;
    y = [x; exp(x)];
    fid = fopen('exp.txt','w');
    fprintf(fid,'%6.2f %12.8f\n',y);
    fclose(fid)

create a text file called exp.txt containing a short table of the exponential function:

  • 0.00    1.00000000
    0.10 1.10517092
    ...
    1.00 2.71828183

The command

  • fprintf('A unit circle has circumference %g.\n',2*pi)

displays a line on the screen:

  • A unit circle has circumference 6.283186.

To insert a single quotation mark in a string, use two single quotation marks together. For example,

  • fprintf(1,'It''s Friday.\n')

displays on the screen:

  • It's Friday.

The commands

  • B = [8.8  7.7; 8800  7700]
    fprintf(1,'X is %6.2f meters or %8.3f mm\n',9.9,9900,B)

display the lines:

  • X is 9.90 meters or 9900.000 mm
    X is 8.80 meters or 8800.000 mm
    X is 7.70 meters or 7700.000 mm

Explicitly convert MATLAB double-precision variables to integral values for use with an integral conversion specifier. For instance, to convert signed 32-bit data to hexadecimal format:

  • a = [6 10 14 44];
    fprintf('%9X\n',a + (a<0)*2^32)
    6
    A
    E
    2C

fplot

Plot a function between specified limits

Syntax

  • fplot('function',limits)
    fplot('function',limits,LineSpec)
    fplot('function',limits,tol)
    fplot('function',limits,tol,LineSpec)
    fplot('function',limits,n)
    [X,Y] = fplot('function',limits,...)
    [...] = plot('function',limits,tol,n,LineSpec,P1,P2,...)

Description

fplot plots a function between specified limits. The function must be of the form y = f(x), where x is a vector whose range specifies the limits, and y is a vector the same size as x and contains the function's value at the points in x (see the first example). If the function returns more than one value for a given x, then y is a matrix whose columns contain each component of f(x) (see the second example).

fplot('function',limits) plots 'function' between the limits specified by limits. limits is a vector specifying the x-axis limits ([xmin xmax]), or the x- and y-axis limits, ([xmin xmax ymin ymax]).

'function' must be the name of an M-file function or a string with variable x that may be passed to eval, such as 'sin(x)', 'diric(x,10)' or '[sin(x),cos(x)]'.

The function f(x) must return a row vector for each element of vector x. For example, if f(x) returns [f1(x),f2(x),f3(x)] then for input [x1;x2] the function should return the matrix

  • f1(x1) f2(x1) f3(x1)
    f1(x2) f2(x2) f3(x2)

fplot('function',limits,LineSpec) plots 'function' using the line specification LineSpec.

fplot('function',limits,tol) plots 'function' using the relative error tolerance tol (The default is 2e-3, i.e., 0.2 percent accuracy).

fplot('function',limits,tol,LineSpec) plots 'function' using the relative error tolerance tol and a line specification that determines line type, marker symbol, and color.

fplot('function',limits,n) with n >= 1 plots the function with a minimum of n+1 points. The default n is 1. The maximum step size is restricted to be (1/n)*(xmax-xmin).

fplot(fun,lims,...) accepts combinations of the optional arguments tol, n, and LineSpec, in any order.

[X,Y] = fplot('function',limits,...) returns the abscissas and ordinates for 'function' in X and Y. No plot is drawn on the screen, however you can plot the function using plot(X,Y).

[...] = plot('function',limits,tol,n,LineSpec,P1,P2,...) enables you to pass parameters P1, P2, etc. directly to the function 'function':

  • Y = function(X,P1,P2,...)

To use default values for tol, n, or LineSpec, you can pass in the empty matrix ([]).

Remarks

fplot uses adaptive step control to produce a representative graph, concentrating its evaluation in regions where the function's rate of change is the greatest.

Examples

Plot the hyperbolic tangent function from -2 to 2:

  • fplot('tanh',[-2 2])



Create an M-file, myfun, that returns a two column matrix:

  • function Y = myfun(x)
    Y(:,1) = 200*sin(x(:))./x(:);
    Y(:,2) = x(:).^2;

Plot the function with the statement:

  • fplot('myfun',[-20 20]

Addition Examples

  • subplot(2,2,1);fplot('humps',[0 1])
    subplot(2,2,2);fplot('abs(exp(-j*x*(0:9))*ones(10,1))',[0 2*pi])
    subplot(2,2,3);fplot('[tan(x),sin(x),cos(x)]',2*pi*[-1 1 -1 1])
    subplot(2,2,4);fplot('sin(1./x)',[0.01 0.1],1e-3)

format

Control display format for output

Graphical Interface

As an alternative to format, use preferences. Select Preferences from the File menu in the MATLAB desktop and use Command Window preferences.

Syntax

  • format
    format type
    format('type')

Description

MATLAB performs all computations in double precision. Use the format function to control the output format of the numeric values displayed in the Command Window. The format function affects only how numbers are displayed, not how MATLAB computes or saves them. The specified format applies only to the current session. To maintain a format across sessions, instead use MATLAB preferences.

format by itself, changes the output format to the default type, short, which is 5-digit scaled, fixed-point values.

format type changes the format to the specified type. The table below describes the allowable values for type and provides an example for pi, unless otherwise noted. To see the current type file, use get(0,'Format'), or for compact versus loose, use get(0,'FormatSpacing').


Value for type
Result
Example
+
+, -, blank
+
bank
Fixed dollars and cents
3.14
compact
Suppresses excess line feeds to show more output in a single screen. Contrast with loose.
theta = pi/2
theta=
1.5708
hex
Hexadecimal (hexadecimal representation of a binary double-precision number)
400921fb54442d18
long
15-digit scaled fixed point
3.14159265358979
long e
15-digit floating point
3.141592653589793e+00
long g
Best of 15-digit fixed or floating point
3.14159265358979
loose
Adds linefeeds to make output more readable. Contrast with compact.
theta = pi/2

theta=

1.5708
rat
Ratio of small integers
355/113
short
5-digit scaled fixed point
3.1416
short e
5-digit floating point
3.1416e+00
short g
Best of 5-digit fixed or floating point
3.1416

format('type') is the function form of the syntax.

Examples

Change the format to long by typing

  • format long

View the result for the value of pi by typing

  • pi

and MATLAB returns

  • ans =
    3.14159265358979

View the current format by typing

  • get(0,'Format')

MATLAB returns

  • ans =
    long

Set the format to short e by typing

  • format short e

or use the function form of the syntax

  • format('short','e')

Algorithms

If the largest element of a matrix is larger than 103 or smaller than 10-3, MATLAB applies a common scale factor for the short and long formats. The function format + displays +, -, and blank characters for positive, negative, and zero elements. format hex displays the hexadecimal representation of a binary double-precision number. format rat uses a continued fraction algorithm to approximate floating-point values by ratios of small integers. See rat.m for the complete code.

for

Repeat statements a specific number of times

Syntax

  • for variable = expression
    statements
    end

Description

The general format is

  • for variable = expression
    statement
    ...
    statement
    end

The columns of the expression are stored one at a time in the variable while the following statements, up to the end, are executed.

In practice, the expression is almost always of the form scalar : scalar, in which case its columns are simply scalars.

The scope of the for statement is always terminated with a matching end.

Examples

Assume k has already been assigned a value. Create the Hilbert matrix, using zeros to preallocate the matrix to conserve memory:

  • a = zeros(k,k)  % Preallocate matrix
    for m = 1:k
    for n = 1:k
    a(m,n) = 1/(m+n -1);
    end
    end

Step s with increments of -0.1

  • for s = 1.0: -0.1: 0.0,..., end

Successively set e to the unit n-vectors:

  • for e = eye(n),..., end

The line

  • for V = A,..., end

has the same effect as

  • for k = 1:n, V = A(:,k);..., end

except k is also set here.


fopen

Open a file or obtain information about open files

Syntax

  • fid = fopen(filename)
    fid = fopen(filename,permission)
    [fid,message] = fopen(filename,permission,machineformat)
    fids = fopen('all')
    [filename,permission, machineormat] = fopen(fid)

Description

fid = fopen(filename) opens the file filename for read access. (On PCs, fopen opens files for binary read access.)

fid is a scalar MATLAB integer, called a file identifier. You use the fid as the first argument to other file input/output routines. If fopen cannot open the file, it returns -1. Two file identifiers are automatically available and need not be opened. They are fid=1 (standard output) and fid=2 (standard error).

fid = fopen(filename,permission) opens the file filename in the mode specified by permission. permission can be:


'r'
Open file for reading (default).
'w'
Open file, or create new file, for writing; discard existing contents, if any.
'a'
Open file, or create new file, for writing; append data to the end of the file.
'r+'
Open file for reading and writing.
'w+'
Open file, or create a new file, for reading and writing; discard existing contents, if any.
'a+'
Open file, or create new file, for reading and writing; append data to the end of the file.
'A'
Append without automatic flushing; used with tape drives
'W'
Write without automatic flushing; used with tape drives

filename can be a MATLABPATH relative partial pathname if the file is opened for reading only. A relative path is always searched for first with respect to the current directory. If it is not found and reading only is specified or implied then fopen does an additional search of the MATLABPATH

Files can be opened in binary mode (the default) or in text mode. In binary mode, no characters are singled out for special treatment. In text mode on the PC, , the carriage return character preceding a newline character is deleted on input and added before the newline character on output. To open in text mode, add "t" to the permission string, for example 'rt' and 'wt+'. (On Unix, text and binary mode are the same so this has no effect. But on PC systems this is critical.)

    Note If the file is opened in update mode ('+'), an input command like fread, fscanf, fgets, or fgetl cannot be immediately followed by an output command like fwrite or fprintf without an intervening fseek or frewind. The reverse is also true. Namely, an output command like fwrite or fprintf cannot be immediately followed by an input command like fread, fscanf, fgets, or fgetl without an intervening fseek or frewind.

[fid,message] = fopen(filename,permission) opens a file as above. If it cannot open the file, fid equals -1 and message contains a system-dependent error message. If fopen successfully opens a file, the value of message is empty.

[fid,message] = fopen(filename,permission,machineformat) opens the specified file with the specified permission and treats data read using fread or data written using fwrite as having a format given by machineformat. machineformat is one of the following strings:


'cray' or 'c'

Cray floating point with big-endian byte ordering

'ieee-be' or 'b'

IEEE floating point with big-endian byte ordering

'ieee-le' or 'l'

IEEE floating point with little-endian byte ordering

'ieee-be.l64' or 's'

IEEE floating point with big-endian byte ordering and 64-bit long data type

'ieee-le.l64' or 'a'

IEEE floating point with little-endian byte ordering and 64-bit long data type

'native' or 'n'

Numeric format of the machine on which MATLAB is running (the default).

'vaxd' or 'd'

VAX D floating point and VAX ordering

'vaxg' or 'g'

VAX G floating point and VAX ordering

fids = fopen('all') returns a row vector containing the file identifiers of all open files, not including 1 and 2 (standard output and standard error). The number of elements in the vector is equal to the number of open files.

[filename,permission,machineformat] = fopen(fid) returns the filename, permission string, and machineformat string associated with the specified file. An invalid fid returns empty strings for all output arguments.

The 'W' and 'A' permissions are designed for use with tape drives and do not automatically perform a flush of the current output buffer after output operations. For example, open a 1/4" cartridge tape on a SPARCstation for writing with no auto-flush:

  •            fid = fopen('/dev/rst0','W')

Examples

The example uses fopen to open a file and then passes the fid, returned by fopen, to other file I/O functions to read data from the file and then close the file.

  • fid=fopen('fgetl.m');
    while 1
    tline = fgetl(fid);
    if ~ischar(tline), break, end
    disp(tline)
    end
    fclose(fid);



fopen (serial)



Connect a serial port object to the device

Syntax

  • fopen(obj)

Arguments


obj
A serial port object or an array of serial port objects.

Description

fopen(obj) connects obj to the device.

Remarks

Before you can perform a read or write operation, obj must be connected to the device with the fopen function. When obj is connected to the device:

An error is returned if you attempt to perform a read or write operation while obj is not connected to the device. You can connect only one serial port object to a given device.

Some properties are read-only while the serial port object is open (connected), and must be configured before using fopen. Examples include InputBufferSize and OutputBufferSize. Refer to the property reference pages to determine which properties have this constraint.

The values for some properties are verified only after obj is connected to the device. If any of these properties are incorrectly configured, then an error is returned when fopen is issued and obj is not connected to the device. Properties of this type include BaudRate, and are associated with device settings.

If you use the help command to display help for fopen, then you need to supply the pathname shown below.

  • help serial/fopen

Example

This example creates the serial port object s, connects s to the device using fopen, writes and reads text data, and then disconnects s from the device.

  • s = serial('COM1');
    fopen(s)
    fprintf(s,'*IDN?')
    idn = fscanf(s);
    fclose(s)

fminsearch

Minimize a function of several variables

Syntax

  • x = fminsearch(fun,x0)
    x = fminsearch(fun,x0,options)
    x = fminsearch(fun,x0,options,P1,P2,...)
    [x,fval] = fminsearch(...)
    [x,fval,exitflag] = fminsearch(...)
    [x,fval,exitflag,output] = fminsearch(...)

Description

fminsearch finds the minimum of a scalar function of several variables, starting at an initial estimate. This is generally referred to as unconstrained nonlinear optimization.

x = fminsearch(fun,x0) starts at the point x0 and finds a local minimum x of the function described in fun. x0 can be a scalar, vector, or matrix.

x = fminsearch(fun,x0,options) minimizes with the optimization parameters specified in the structure options. You can define these parameters using the optimset function. fminsearch uses these options structure fields:


Display
Level of display. 'off' displays no output; 'iter' displays output at each iteration; 'final' displays just the final output; 'notify' (default) dislays output only if the function does not converge.
MaxFunEvals
Maximum number of function evaluations allowed.
MaxIter
Maximum number of iterations allowed.
TolX
Termination tolerance on x.

x = fminsearch(fun,x0,options,P1,P2,...) passes the problem-dependent parameters P1, P2, etc., directly to the function fun. Use options = [] as a placeholder if no options are set.

[x,fval] = fminsearch(...) returns in fval the value of the objective function fun at the solution x.

[x,fval,exitflag] = fminsearch(...) returns a value exitflag that describes the exit condition of fminsearch:


>0
Indicates that the function converged to a solution x.
0
Indicates that the maximum number of function evaluations was exceeded.
<0
Indicates that the function did not converge to a solution.

[x,fval,exitflag,output] = fminsearch(...) returns a structure output that contains information about the optimization:


output.algorithm
The algorithm used
output.funcCount
The number of function evaluations
output.iterations
The number of iterations taken

Arguments

fun is the function to be minimized. It accepts an input x and returns a scalar f, the objective function evaluated at x. The function fun can be specified as a function handle.

  • x = fminsearch(@myfun,x0,A,b)

where myfun is a MATLAB function such as

  • function f = myfun(x)
    f = ... % Compute function value at x

fun can also be an inline object.

  • x = fminsearch(inline('sin(x*x)'),x0,A,b);

Other arguments are described in the syntax descriptions above.

Examples

A classic test example for multidimensional minimization is the Rosenbrock banana function

The minimum is at (1,1) and has the value 0. The traditional starting point is (-1.2,1). The M-file banana.m defines the function.

  • function f = banana(x)
    f = 100*(x(2)-x(1)^2)^2+(1-x(1))^2;

The statement

  • [x,fval] = fminsearch(@banana,[-1.2, 1])

produces

  • x =

    1.0000 1.0000

    fval =

    8.1777e-010

This indicates that the minimizer was found to at least four decimal places with a value near zero.

Move the location of the minimum to the point [a,a^2] by adding a second parameter to banana.m.

  • function f = banana(x,a)
    if nargin <>, a = 1; end
    f = 100*(x(2)-x(1)^2)^2+(a-x(1))^2;

Then the statement

  • [x,fval] = fminsearch(@banana, [-1.2, 1], ...
    optimset('TolX',1e-8), sqrt(2));

sets the new parameter to sqrt(2) and seeks the minimum to an accuracy higher than the default on x.

Limitations

fminsearch can often handle discontinuity, particularly if it does not occur near the solution. fminsearch may only give local solutions.

fminsearch only minimizes over the real numbers, that is, must only consist of real numbers and must only return real numbers. When has complex variables, they must be split into real and imaginary parts.

fmins

Minimize a function of several variables
    Note The fmins function was replaced by fminsearch in Release 11 (MATLAB 5.3). In Release 12 (MATLAB 6.0), fmins displays a warning message and calls fminsearch.

Syntax

  • x = fmins('fun',x0)
    x = fmins('fun',x0,options)
    x = fmins('fun',x0,options,[],P1,P2, ...)
    [x,options] = fmins(...)

Description

x = fmins('fun',x0) returns a vector x which is a local minimizer of fun(x) near .

x = fmins('fun',x0,options) does the same as the above, but uses options control parameters.

x = fmins('fun',x0,options,[],P1,P2,...) does the same as above, but passes arguments to the objective function, fun(x,P1,P2, ...). Pass an empty matrix for options to use the default value.

[x,options] = fmins(...) returns, in options(10), a count of the number of steps taken.

Arguments


x0
Starting vector.
P1,P2...
Arguments to be passed to fun.
[]
Argument needed to provide compatibility with fminu in the Optimization Toolbox.
fun
A string containing the name of the objective function to be minimized. fun(x) is a scalar valued function of a vector variable.
options
A vector of control parameters. Only four of the 18 components of options are referenced by fmins; Optimization Toolbox functions use the others. The four control options used by fmins are:
  • options(1) -- If this is nonzero, intermediate steps in the solution are displayed. The default value of options(1) is 0.
  • options(2) and options(3) -- These are the termination tolerances for x and function(x), respectively. The default values are 1.e-4.
  • options(14) -- This is the maximum number of steps. The default value is 500.

Examples

A classic test example for multidimensional minimization is the Rosenbrock banana function

The minimum is at (1,1) and has the value 0. The traditional starting point is (-1.2,1). The M-file banana.m defines the function.

  • function f = banana(x)
    f = 100*(x(2)-x(1)^2)^2+(1-x(1))^2;

The statements

  • [x,out] = fmins('banana',[-1.2, 1]);
    x
    out(10)

produce

  • x =

    1.0000 1.0000

    ans =

    165

This indicates that the minimizer was found to at least four decimal places in 165 steps.

Move the location of the minimum to the point [a,a^2] by adding a second parameter to banana.m.

  • function f = banana(x,a)
    if nargin <>, a = 1; end
    f = 100*(x(2)-x(1)^2)^2+(a-x(1))^2;

Then the statement

  • [x,out] = fmins('banana', [-1.2, 1], [0, 1.e-8], [], sqrt(2));

sets the new parameter to sqrt(2) and seeks the minimum to an accuracy higher than the default.

Algorithm

The algorithm is the Nelder-Mead simplex search described in the two references. It is a direct search method that does not require gradients or other derivative information. If n is the length of x, a simplex in n-dimensional space is characterized by the n+1 distinct vectors which are its vertices. In two-space, a simplex is a triangle; in three-space, it is a pyramid.

At each step of the search, a new point in or near the current simplex is generated. The function value at the new point is compared with the function's values at the vertices of the simplex and, usually, one of the vertices is replaced by the new point, giving a new simplex. This step is repeated until the diameter of the simplex is less than the specified tolerance.

fminbnd

Minimize a function of one variable on a fixed interval

Syntax

  • x = fminbnd(fun,x1,x2)
    x = fminbnd(fun,x1,x2,options)
    x = fminbnd(fun,x1,x2,options,P1,P2,...)
    [x,fval] = fminbnd(...)
    [x,fval,exitflag] = fminbnd(...)
    [x,fval,exitflag,output] = fminbnd(...)

Description

fminbnd finds the minimum of a function of one variable within a fixed interval.

x = fminbnd(fun,x1,x2) returns a value x that is a local minimizer of the function that is described in fun in the interval x1 <= x <= x2.

x = fminbnd(fun,x1,x2,options) minimizes with the optimization parameters specified in the structure options. You can define these parameters using the optimset function. fminbnd uses these options structure fields:


Display
Level of display. 'off' displays no output; 'iter' displays output at each iteration; 'final' displays just the final output; 'notify' (default) dislays output only if the function does not converge.
MaxFunEvals
Maximum number of function evaluations allowed.
MaxIter
Maximum number of iterations allowed.
TolX
Termination tolerance on x.

x = fminbnd(fun,x1,x2,options,P1,P2,...) provides for additional arguments, P1, P2, etc., which are passed to the objective function, fun(x,P1,P2,...). Use options=[] as a placeholder if no options are set.

[x,fval] = fminbnd(...) returns the value of the objective function computed in fun at x.

[x,fval,exitflag] = fminbnd(...) returns a value exitflag that describes the exit condition of fminbnd:


>0
Indicates that the function converged to a solution x.
0
Indicates that the maximum number of function evaluations was exceeded.
<0
Indicates that the function did not converge to a solution.

[x,fval,exitflag,output] = fminbnd(...) returns a structure output that contains information about the optimization:


output.algorithm
The algorithm used
output.funcCount
The number of function evaluations
output.iterations
The number of iterations taken

Arguments

fun is the function to be minimized. fun accepts a scalar x and returns a scalar f, the objective function evaluated at x. The function fun can be specified as a function handle.

  • x = fminbnd(@myfun,x0)

where myfun is a MATLAB function such as

  • function f = myfun(x)
    f = ... % Compute function value at x.

fun can also be an inline object.

  • x = fminbnd(inline('sin(x*x)'),x0);

Other arguments are described in the syntax descriptions above.

Examples

x = fminbnd(@cos,3,4) computes to a few decimal places and gives a message on termination.

  • [x,fval,exitflag] =
    fminbnd(@cos,3,4,optimset('TolX',1e-12,'Display','off'))

computes to about 12 decimal places, suppresses output, returns the function value at x, and returns an exitflag of 1.

The argument fun can also be an inline function. To find the minimum of the function on the interval (0,2), create an inline object f

  • f = inline('x.^3-2*x-5');

Then invoke fminbnd with

  • x = fminbnd(f, 0, 2)

The result is

  • x =
    0.8165

The value of the function at the minimum is

  • y = f(x)

    y =
    -6.0887

Limitations

The function to be minimized must be continuous. fminbnd may only give local solutions.

fminbnd often exhibits slow convergence when the solution is on a boundary of the interval.

fminbnd only handles real variables.

fmin

Minimize a function of one variable
    Note The fmin function was replaced by fminbnd in Release 11 (MATLAB 5.3). In Release 12 (MATLAB 6.0), fmin displays a warning message and calls fminbnd.

Syntax

  • x = fmin('fun',x1,x2)
    x = fmin('fun',x1,x2,options)
    x = fmin('fun',x1,x2,options,P1,P2, ...)
    [x,options] = fmin(...)

Description

x = fmin('fun',x1,x2) returns a value of x which is a local minimizer of fun(x) in the interval .

x = fmin('fun',x1,x2,options) does the same as the above, but uses options control parameters.

x = fmin('fun',x1,x2,options,P1,P2,...) does the same as the above, but passes arguments to the objective function, fun(x,P1,P2,...). Pass an empty matrix for options to use the default value.

[x,options] = fmin(...) returns, in options(10), a count of the number of steps taken.

Arguments


x1,x2
Interval over which fun is minimized.
P1,P2...
Arguments to be passed to fun.
fun
A string containing the name of the function to be minimized.
options
A vector of control parameters. Only three of the 18 components of options are referenced by fmin; Optimization Toolbox functions use the others. The three control options used by fmin are:
  • options(1) -- If this is nonzero, intermediate steps in the solution are displayed. The default value of options(1) is 0.
  • options(2) -- This is the termination tolerance. The default value is 1.e-4.
  • options(14) -- This is the maximum number of steps. The default value is 500.

Examples

fmin('cos',3,4) computes to a few decimal places.

fmin('cos',3,4,[1,1.e-12]) displays the steps taken to compute to 12 decimal places.

To find the minimum of the function on the interval (0,2), write an M-file called f.m.

  • function y = f(x)
    y = x.^3-2*x-5;

Then invoke fmin with

  • x = fmin('f', 0, 2)

The result is

  • x =
    0.8165

The value of the function at the minimum is

  • y = f(x)

    y =
    -6.0887

flops

Count floating-point operations

Description

This is an obsolete function. With the incorporation of LAPACK in MATLAB version 6, counting floating-point operations is no longer practical.



flow

A simple function of three variables

Syntax

  • v = flow
    v = flow(n)
    v = flow(x,y,z)
    [x,y,z,v] = flow(...)

Description

flow, a function of three variables, is the speed profile of a submerged jet within a infinite tank. flow is useful for demonstrating slice, interp3, and for generating scalar volume data.

v = flow produces a 50-by-25-by-25 array.

v = flow(n) produces a 2n-by-n-by-n array.

v = flow(x,y,z) evaluates the speed profile at the points x, y, and z.

[x,y,z,v] = flow(...) returns the coordinates as well as the volume data.

floor

Round towards minus infinity

Syntax

  • B = floor(A)

Description

B = floor(A) rounds the elements of A to the nearest integers less than or equal to A. For complex A, the imaginary and real parts are rounded independently.

Examples

  • a = [-1.9, -0.2, 3.4, 5.6, 7.0, 2.4+3.6i]

    a =
    Columns 1 through 4
    -1.9000 -0.2000 3.4000 5.6000

    Columns 5 through 6
    7.0000 2.4000 + 3.6000i

    floor(a)

    ans =
    Columns 1 through 4
    -2.0000 -1.0000 3.0000 5.0000

    Columns 5 through 6
    7.0000 2.0000 + 3.0000i

flipud

Flip matrices up-down

Syntax

  • B = flipud(A)

Description

B = flipud(A) returns A with rows flipped in the up-down direction, that is, about a horizontal axis.

If A is a column vector, then flipud(A) returns a vector of the same length with the order of its elements reversed. If A is a row vector, then flipud(A) simply returns A.

Examples

If A is the 3-by-2 matrix,

  • A =
    1 4
    2 5
    3 6

then flipud(A) produces

  •     3    6
    2 5
    1 4

If A is a column vector,

  • A =
    3
    5
    7

then flipud(A) produces

  • A =
    7
    5
    3

Limitations

The array being operated on cannot have more than two dimensions. This limitation exists because the axis upon which to flip a multidimensional array would be undefined.

fliplr

Flip matrices left-right

Syntax

  • B = fliplr(A)

Description

B = fliplr(A) returns A with columns flipped in the left-right direction, that is, about a vertical axis.

If A is a row vector, then fliplr(A) returns a vector of the same length with the order of its elements reversed. If A is a column vector, then fliplr(A) simply returns A.

Examples

If A is the 3-by-2 matrix,

  • A =
    1 4
    2 5
    3 6

then fliplr(A) produces

  •     4    1
    5 2
    6 3

If A is a row vector,

  • A =
    1 3 5 7 9

then fliplr(A) produces

  •     9    7    5    3    1

Limitations

The array being operated on cannot have more than two dimensions. This limitation exists because the axis upon which to flip a multidimensional array would be undefined.

flipdim

Flip array along a specified dimension

Syntax

  • B = flipdim(A,dim)

Description

B = flipdim(A,dim) returns A with dimension dim flipped.

When the value of dim is 1, the array is flipped row-wise down. When dim is 2, the array is flipped columnwise left to right. flipdim(A,1) is the same as flipud(A), and flipdim(A,2) is the same as fliplr(A).

Examples

flipdim(A,1) where

  • A =

    1 4
    2 5
    3 6

produces

  •      3     6
    2 5
    1 4