Saturday, July 25, 2009

compan

Companion matrix

Syntax

*

A = compan(u)

Description


A = compan(u) returns the corresponding companion matrix whose first row is -u(2:n)/u(1), where u is a vector of polynomial coefficients. The eigenvalues of compan(u) are the roots of the polynomial.

Examples

The polynomial

has a companion matrix given by

*

u = [1 0 -7 6]
A = compan(u)
A =
0 7 -6
1 0 0
0 1 0

The eigenvalues are the polynomial roots:

*

eig(compan(u))

ans =
-3.0000
2.0000
1.0000

This is also roots(u).


compass

Plot arrows emanating from the origin

Syntax

*

compass(X,Y)
compass(Z)
compass(...,LineSpec)
h = compass(...)

Description

A compass plot displays direction or velocity vectors as arrows emanating from the origin. X, Y, and Z are in Cartesian coordinates and plotted on a circular grid.

compass(X,Y) displays a compass plot having n arrows, where n is the number of elements in X or Y. The location of the base of each arrow is the origin. The location of the tip of each arrow is a point relative to the base and determined by [X(i),Y(i)].

compass(Z) displays a compass plot having n arrows, where n is the number of elements in Z. The location of the base of each arrow is the origin. The location of the tip of each arrow is relative to the base as determined by the real and imaginary components of Z. This syntax is equivalent to compass(real(Z),imag(Z)).

compass(...,LineSpec) draws a compass plot using the line type, marker symbol, and color specified by LineSpec.

h = compass(...) returns handles to line objects.

Examples

Draw a compass plot of the eigenvalues of a matrix.

*

Z = eig(randn(20,20));
compass(Z)



complex

Construct complex data from real and imaginary components

Syntax

*

c = complex(a,b)
c = complex(a)

Description


c = complex(a,b) creates a complex output, c, from the two real inputs.

*

c = a + bi

The output is the same size as the inputs, which must be scalars or equally sized vectors, matrices, or multi-dimensional arrays of the same data type.

Note If b is all zeros, c is complex and the value of all its imaginary components is 0. In contrast, the result of the addition a+0i returns a strictly real result.

c = complex(a) for real a returns the complex result c with real part a and 0 as the value of all imaginary components. Even though the value of all imaginary components is 0, c is complex and isreal(c) returns false.

The complex function provides a useful substitute for expressions such as

*

a + i*b or a + j*b

in cases when the names "i" and "j" may be used for other variables (and do not equal ), when a and b are not double-precision, or when b is all zero.

Example

Create complex uint8 vector from two real uint8 vectors.

*

a = uint8([1;2;3;4])
b = uint8([2;2;7;7])
c = complex(a,b)
c =
1.0000 + 2.0000i
2.0000 + 2.0000i
3.0000 + 7.0000i
4.0000 + 7.0000i


computer

Identify information about computer on which MATLAB is running

Syntax

*

str = computer
[str,maxsize] = computer
[str,maxsize,endian] = computer

Description

str = computer returns the string str with the computer type on which MATLAB is running.

[str,maxsize] = computer returns the integer maxsize, which contains the maximum number of elements allowed in an array with this version of MATLAB.

[str,maxsize,endian] = computer also returns either 'L' for little endian byte ordering or 'B' for big endian byte ordering.

The list of supported computers changes as new computers are added and others become obsolete. A typical list follows.

str Computer

ALPHA Compaq Alpha (OSF1)

HP700 HP 9000/700 (HP-UX 10.20)

HPUX HP PA-RISC (HP-UX 11.00)

IBM_RS IBM RS6000 workstation (AIX)

GLNX86 Linux on PC

PCWIN Microsoft Windows

SGI Silicon Graphics (IRIX/IRIX64)

SOL2 Sun Solaris 2 SPARC workstation

Remarks

SGI64 users prior to R12 must migrate to SGI with R12. LNX86 users prior to R12 must migrate to GLNX86 with R12.
ColorSpec

Color specification

Description

ColorSpec is not a command; it refers to the three ways in which you specify color in MATLAB:

* RGB triple
* Short name
* Long name

The short names and long names are MATLAB strings that specify one of eight predefined colors. The RGB triple is a three-element row vector whose elements specify the intensities of the red, green, and blue components of the color; the intensities must be in the range [0 1]. The following table lists the predefined colors and their RGB equivalents.

RGB Value Short Name Long Name
[1 1 0] y yellow

[1 0 1] m magenta

[0 1 1] c cyan

[1 0 0] r red

[0 1 0] g green

[0 0 1] b blue

[1 1 1] w white

[0 0 0] k black

Remarks


The eight predefined colors and any colors you specify as RGB values are not part of a figure's colormap, nor are they affected by changes to the figure's colormap. They are referred to as fixed colors, as opposed to colormap colors.

Examples

To change the background color of a figure to green, specify the color with a short name, a long name, or an RGB triple. These statements generate equivalent results:

*

whitebg('g')
whitebg('green')
whitebg([0 1 0]);

You can use ColorSpec anywhere you need to define a color. For example, this statement changes the figure background color to pink:

*

set(gcf,'Color',[1,0.4,0.6])



colperm

Sparse column permutation based on nonzero count

Syntax


*

j = colperm(S)

Description


j = colperm(S) generates a permutation vector j such that the columns of S(:,j) are ordered according to increasing count of nonzero entries. This is sometimes useful as a preordering for LU factorization; in this case use lu(S(:,j)).

If S is symmetric, then j = colperm(S) generates a permutation j so that both the rows and columns of S(j,j) are ordered according to increasing count of nonzero entries. If S is positive definite, this is sometimes useful as a preordering for Cholesky factorization; in this case use chol(S(j,j)).

Algorithm

The algorithm involves a sort on the counts of nonzeros in each column.

Examples

The n-by-n arrowhead matrix

*

A = [ones(1,n); ones(n-1,1) speye(n-1,n-1)]

has a full first row and column. Its LU factorization, lu(A), is almost completely full. The statement

*

j = colperm(A)

returns j = [2:n 1]. So A(j,j) sends the full row and column to the bottom and the rear, and lu(A(j,j)) has the same nonzero structure as A itself.

On the other hand, the Bucky ball example,

*

B = bucky

has exactly three nonzero elements in each row and column, so j = colperm(B) is the identity permutation and is no help at all for reducing fill-in with subsequent factorizations.



comet


Two-dimensional comet plot

Syntax

*

comet(y)
comet(x,y)
comet(x,y,p)

Description


A comet plot is an animated graph in which a circle (the comet head) traces the data points on the screen. The comet body is a trailing segment that follows the head. The tail is a solid line that traces the entire function.

comet(y) displays a comet plot of the vector y.

comet(x,y) displays a comet plot of vector y versus vector x.

comet(x,y,p) specifies a comet body of length p*length(y). p defaults to 0.1.

Remarks


Note that the trace left by comet is created by using an EraseMode of none, which means you cannot print the plot (you get only the comet head) and it disappears if you cause a redraw (e.g., by resizing the window).

Examples

Create a simple comet plot:

*

t = 0:.01:2*pi;
x = cos(2*t).*(cos(t).^2);
y = sin(2*t).*(sin(t).^2);
comet(x,y);


comet3


Three-dimensional comet plot

Syntax


*

comet3(z)
comet3(x,y,z)
comet3(x,y,z,p)

Description


A comet plot is an animated graph in which a circle (the comet head) traces the data points on the screen. The comet body is a trailing segment that follows the head. The tail is a solid line that traces the entire function.

comet3(z) displays a three-dimensional comet plot of the vector z.

comet3(x,y,z) displays a comet plot of the curve through the points [x(i),y(i),z(i)].

comet3(x,y,z,p) specifies a comet body of length p*length(y).

Remarks


Note that the trace left by comet3 is created by using an EraseMode of none, which means you cannot print the plot (you get only the comet head) and it disappears if you cause a redraw (e.g., by resizing the window).

Examples

Create a three-dimensional comet plot.

*

t = -10*pi:pi/250:10*pi;
comet3((cos(2*t).^2).*sin(t),(sin(2*t).^2).*cos(t),t);
colorbar

Display colorbar showing the color scale

Syntax

*

colorbar
colorbar('vert')
colorbar('horiz')
colorbar(h)
h = colorbar(...)
colorbar(...,'peer',axes_handle)

Description


The colorbar function displays the current colormap in the current figure and resizes the current axes to accommodate the colorbar.

colorbar updates the most recently created colorbar or, when the current axes does not have a colorbar, colorbar adds a new vertical colorbar.

colorbar('vert') adds a vertical colorbar to the current axes.

colorbar('horiz') adds a horizontal colorbar to the current axes.

colorbar(h) uses the axes h to create the colorbar. The colorbar is horizontal if the width of the axes is greater than its height, as determined by the axes Position property.

h = colorbar(...) returns a handle to the colorbar, which is an axes graphics object.

colorbar(...,'peer',axes_handle) creates a colorbar associated with the axes axes_handle instead of the current axes.

Remarks


colorbar works with two-dimensional and three-dimensional plots.



colordef

Sets default property values to display different color schemes

Syntax


*

colordef white
colordef black
colordef none
colordef(fig,color_option)
h = colordef('new',color_option)

Description

colordef enables you to select either a white or black background for graphics display. It sets axis lines and labels to show up against the background color.

colordef white sets the axis background color to white, the axis lines and labels to black, and the figure background color to light gray.

colordef black sets the axis background color to black, the axis lines and labels to white, and the figure background color to dark gray.

colordef none sets the figure coloring to that used by MATLAB Version 4 (essentially a black background).

colordef(fig,color_option) sets the color scheme of the figure identified by the handle fig to the color option 'white', 'black', or 'none'.

h = colordef('new',color_option) returns the handle to a new figure created with the specified color options (i.e., 'white', 'black', or 'none').

Remarks


colordef affects only subsequently drawn figures, not those currently on the display. This is because colordef works by setting default property values (on the root or figure level). You can list the currently set default values on the root level with the statement:

*

get(0,'defaults')

You can remove all default values using the reset command:

*

reset(0)



colormap

Set and get the current colormap

Syntax


*

colormap(map)
colormap('default')
cmap = colormap

Description

A colormap is an m-by-3 matrix of real numbers between 0.0 and 1.0. Each row is an RGB vector that defines one color. The kth row of the colormap defines the k-th color, where map(k,:) = [r(k) g(k) b(k)]) specifies the intensity of red, green, and blue.

colormap(map) sets the colormap to the matrix map. If any values in map are outside the interval [0 1], MATLAB returns the error: Colormap must have values in [0,1].

colormap('default') sets the current colormap to the default colormap.

cmap = colormap; retrieves the current colormap. The values returned are in the interval [0 1].

Specifying Colormaps

M-files in the color directory generate a number of colormaps. Each M-file accepts the colormap size as an argument. For example,

*

colormap(hsv(128))

creates an hsv colormap with 128 colors. If you do not specify a size, MATLAB creates a colormap the same size as the current colormap.

Supported Colormaps

MATLAB supports a number of colormaps.

* autumn varies smoothly from red, through orange, to yellow.
* bone is a grayscale colormap with a higher value for the blue component. This colormap is useful for adding an "electronic" look to grayscale images.
* colorcube contains as many regularly spaced colors in RGB colorspace as possible, while attempting to provide more steps of gray, pure red, pure green, and pure blue.
* cool consists of colors that are shades of cyan and magenta. It varies smoothly from cyan to magenta.
* copper varies smoothly from black to bright copper.
* flag consists of the colors red, white, blue, and black. This colormap completely changes color with each index increment.
* gray returns a linear grayscale colormap.
* hot varies smoothly from black, through shades of red, orange, and yellow, to white.
* hsv varies the hue component of the hue-saturation-value color model. The colors begin with red, pass through yellow, green, cyan, blue, magenta, and return to red. The colormap is particularly appropriate for displaying periodic functions. hsv(m) is the same as hsv2rgb([h ones(m,2)]) where h is the linear ramp, h = (0:m-1)'/m.
* jet ranges from blue to red, and passes through the colors cyan, yellow, and orange. It is a variation of the hsv colormap. The jet colormap is associated with an astrophysical fluid jet simulation from the National Center for Supercomputer Applications. See the "Examples" section.
* lines produces a colormap of colors specified by the axes ColorOrder property and a shade of gray.
* pink contains pastel shades of pink. The pink colormap provides sepia tone colorization of grayscale photographs.
* prism repeats the six colors red, orange, yellow, green, blue, and violet.
* spring consists of colors that are shades of magenta and yellow.
* summer consists of colors that are shades of green and yellow.
* white is an all white monochrome colormap.
* winter consists of colors that are shades of blue and green.




colormapeditor

Start colormap editor

Syntax


*

colormapeditor


Description

colormapeditor displays the current figure's colormap as a strip of rectangular cells in the colormap editor. Node pointers are colored cells below the colormap strip that indicate points in the colormap where the rate of the variation of R, G, and B values change. You can also work in the HSV colorspace by setting the Interpolating Colorspace selector to HSV.

You can also start the colormap editor by selecting Colormap from the Edit menu.

Node Pointer Operations

You can select and move node pointers to change a range of colors in the colormap. The color of a node pointer remains constant as you move it, but the colormap changes by linearly interpolating the RGB values between nodes.

Change the color at a node by double-clicking the node pointer. MATLAB displays a color picker from which you can select a new color. After you select a new color at a node, MATLAB reinterpolates the colors in between nodes.

Operation
How to Perform
Add a node
Click below the corresponding cell in the colormap strip
Select a node
Left-click on the node
Select multiple nodes
Adjacent: left-click on first node, Shift+click on the last node
Nonadjacent: left-click on first node, Ctrl+click on subsequent nodes
Move a node
Select and drag with the mouse or select and use the left and right arrow keys.
Move multiple nodes
Select multiple nodes and use the left and right arrow keys to move nodes as a group. Movement stops when one of the selected nodes hits an unselected node or an end node.
Delete a node
Select the node and then press the Delete key, or select Delete from the Edit menu, or type Ctrl+x.
Delete multiple nodes
Select the nodes and then press the Delete key, or select Delete from the Edit menu, or type Ctrl+x.
Display color picker for a node
Double click on the node pointer.

Current Color Info


When you put the mouse over a color cell or node pointer, the colormap editor displays the following information about that colormap element:

* The element's index in the colormap
* The value from the graphics object color data that is mapped to the node's color (i.e., data from the CData property of any image, patch, or surface objects in the figure)
* The color's RGB and HSV color value
Interpolating Colorspace

The colorspace determines what values are used to calculate the colors of cells between nodes. For example, in the RGB colorspace, internode colors are calculated by linearly interpolating the red, green, and blue intensity values from one node to the next. Switching to the HSV colorspace causes the colormap editor to recalculate the colors between nodes using the hue, saturation, and value components of the color definition.

Note that when you switch from one colorspace to another, the color editor preserves the number, color, and location of the node pointers, which can cause the colormap to change.

Interpolating in HSV:
Since hue is conceptually mapped about a color circle, the interpolation between hue values can be ambiguous. To minimize this ambiguity, the interpolation uses the shortest distance around the circle. For example, interpolating between two nodes, one with at hue of 2 (slightly orange red) and another with a hue of 356 (slightly magenta red), does not result in hues 3,4,5...353,354,355 (orange/red-yellow-green-cyan-blue-magenta/red). Taking the shortest distance around the circle gives 357,358,1,2 (orange/red-red-magenta/red).

Color Data Min and Max

The Color Data Min and Color Data Max text fields enable you to specify values for the axes CLim property. These values change the mapping of object color data (the CData property of images, patches, and surfaces) to the colormap. See Axes Color Limits -- The Clim Property for discussion and examples of how to use this property.
close

Close Audio Video Interleaved (AVI) file

Syntax

*

aviobj = close(aviobj)

Description


aviobj = close(aviobj) finishes writing and closes the AVI file associated with aviobj, which is an AVI file object, created using the avifile function.


closereq


Default figure close request function

Syntax


*

closereq

Description


closereq delete the current figure.


cmopts

Get name of source control system

Graphical Interface

As an alternative to cmopts, use preferences. Select File -> Preferences in the MATLAB desktop, and then select General -> Source Control.

Syntax


*

cmopts

Description


cmopts returns the name of the source control system you selected using preferences, which is one of the following:

*

clearcase
customverctrl
pvcs
rcs
sourcesafe

If you have not selected a source control system, cmopts returns

*

none

Specifying a Source Control System

To specify the source control system:

1. From the MATLAB Editor window or from a Simulink or Stateflow model window, select File -> Preferences.

The Preferences dialog box opens.

2. In the left pane, click the + for General, and then select Source Control.

The currently selected system is shown.

3. Select the system you want to use from the Source control system list.
4. Click OK.

For more information, see source control preferences.

Examples


Type cmopts and MATLAB returns rcs, meaning the source control system specified in preferences is RCS.



colamd


Column approximate minimum degree permutation

Syntax

*

p = colamd(S)
p = colamd(S,knobs)
[p,stats] = colamd(S)
[p,stats] = colamd(S,knobs)

Description

p = colamd(S) returns the column approximate minimum degree permutation vector for the sparse matrix S. For a non-symmetric matrix S, S(:,p) tends to have sparser LU factors than S. The Cholesky factorization of S(:,p)' * S(:,p) also tends to be sparser than that of S'*S.

knobs is a two-element vector. If S is m-by-n, then rows with more than (knobs(1))*n entries are ignored. Columns with more than (knobs(2))*m entries are removed prior to ordering, and ordered last in the output permutation p. If the knobs parameter is not present, then knobs(1) = knobs(2) = spparms('wh_frac').

stats is an optional vector that provides data about the ordering and the validity of the matrix S.

stats(1)
Number of dense or empty rows ignored by colamd
stats(2)
Number of dense or empty columns ignored by colamd
stats(3)
Number of garbage collections performed on the internal data structure used by colamd (roughly of size 2.2*nnz(S) + 4*m + 7*n integers)
stats(4)
0 if the matrix is valid, or 1 if invalid
stats(5)
Rightmost column index that is unsorted or contains duplicate entries, or 0 if no such column exists
stats(6)
Last seen duplicate or out-of-order row index in the column index given by stats(5), or 0 if no such row index exists
stats(7)
Number of duplicate and out-of-order row indices

Although, MATLAB built-in functions generate valid sparse matrices, a user may construct an invalid sparse matrix using the MATLAB C or Fortran APIs and pass it to colamd. For this reason, colamd verifies that S is valid:

* If a row index appears two or more times in the same column, colamd ignores the duplicate entries, continues processing, and provides information about the duplicate entries in stats(4:7).
* If row indices in a column are out of order, colamd sorts each column of its internal copy of the matrix S (but does not repair the input matrix S), continues processing, and provides information about the out-of-order entries in stats(4:7).
* If S is invalid in any other way, colamd cannot continue. It prints an error message, and returns no output arguments (p or stats) .

The ordering is followed by a column elimination tree post-ordering.

Note
colamd tends to be faster than colmmd and tends to return a better ordering.



colmmd

Sparse column minimum degree permutation

Syntax

*

p = colmmd(S)

Description


p = colmmd(S) returns the column minimum degree permutation vector for the sparse matrix S. For a nonsymmetric matrix S, this is a column permutation p such that S(:,p) tends to have sparser LU factors than S.

The colmmd permutation is automatically used by \ and / for the solution of nonsymmetric and symmetric indefinite sparse linear systems.

Use spparms to change some options and parameters associated with heuristics in the algorithm.

Algorithm

The minimum degree algorithm for symmetric matrices is described in the review paper by George and Liu [1]. For nonsymmetric matrices, the MATLAB minimum degree algorithm is new and is described in the paper by Gilbert, Moler, and Schreiber [2]. It is roughly like symmetric minimum degree for A'*A, but does not actually form A'*A.

Each stage of the algorithm chooses a vertex in the graph of A'*A of lowest degree (that is, a column of A having nonzero elements in common with the fewest other columns), eliminates that vertex, and updates the remainder of the graph by adding fill (that is, merging rows). If the input matrix S is of size m-by-n, the columns are all eliminated and the permutation is complete after n stages. To speed up the process, several heuristics are used to carry out multiple stages simultaneously.
clear (serial)

Remove a serial port object from the MATLAB workspace

Syntax

*

clear obj

Arguments

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

Description


clear obj removes obj from the MATLAB workspace.

Remarks


If obj is connected to the device and it is cleared from the workspace, then obj remains connected to the device. You can restore obj to the workspace with the instrfind function. A serial port object connected to the device has a Status property value of open.

To disconnect obj from the device, use the fclose function. To remove obj from memory, use the delete function. You should remove invalid serial port objects from the workspace with clear.

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

*

help serial/private/clear

Example

This example creates the serial port object s, copies s to a new variable scopy, and clears s from the MATLAB workspace. s is then restored to the workspace with instrfind and is shown to be identical to scopy.

*

s = serial('COM1');
scopy = s;
clear s
s = instrfind;
isequal(scopy,s)
ans =
1

clf

Clear current figure window

Syntax

*

clf
clf reset

Description

clf deletes from the current figure all graphics objects whose handles are not hidden (i.e., their HandleVisibility property is set to on).

clf reset deletes from the current figure all graphics objects regardless of the setting of their HandleVisibility property and resets all figure properties, except Position, Units, PaperPosition, and PaperUnits to their default values.

Remarks

The clf command behaves the same way when issued on the command line as it does in callback routines - it does not recognize the HandleVisibility setting of callback. This means that when issued from within a callback routine, clf deletes only those objects whose HandleVisibility property is set to on.


clipboard

Copy and paste strings to and from the system clipboard.

Graphical Interface

As an alternative to clipboard, use the Import Wizard. To use the Import Wizard to copy data from the clipboard, select Paste Special from the Edit menu.

Syntax

*

clipboard('copy',data)
str = clipboard('paste')
data = clipboard('pastespecial')

Description

clipboard('copy', data) sets the clipboard contents to data. If data is not a character array, clipboard uses mat2str to convert it to a string.

str = clipboard('paste') returns the current contents of the clipboard as a string or as an empty string (' '), if the current clipboard content cannot be converted to a string.

data = clipboard('pastespecial') returns the current contents of the clipboard as an array using uiimport.

Note Requires an active X display on Unix and Java elsewhere.


clock

Current time as a date vector

Syntax

*

c = clock

Description

c = clock returns a 6-element date vector containing the current date and time in decimal form:

*

c = [year month day hour minute seconds]

The first five elements are integers. The seconds element is accurate to several digits beyond the decimal point. The statement fix(clock) rounds to integer display format.


close


Delete specified figure

Syntax


*

close
close(h)
close name
close all
close all hidden
status = close(...)

Description


close deletes the current figure or the specified figure(s). It optionally returns the status of the close operation.

close deletes the current figure (equivalent to close(gcf)).

close(h) deletes the figure identified by h. If h is a vector or matrix, close deletes all figures identified by h.

close name deletes the figure with the specified name.

close all deletes all figures whose handles are not hidden.

close all hidden deletes all figures including those with hidden handles.

status = close(...) returns 1 if the specified windows have been deleted and 0 otherwise.

Remarks

The close function works by evaluating the specified figure's CloseRequestFcn property with the statement:

*

eval(get(h,'CloseRequestFcn'))

The default CloseRequestFcn, closereq, deletes the current figure using delete(get(0,'CurrentFigure')). If you specify multiple figure handles, close executes each figure's CloseRequestFcn in turn. If MATLAB encounters an error that terminates the execution of a CloseRequestFcn, the figure is not deleted. Note that using your computer's window manager (i.e., the Close menu item) also calls the figure's CloseRequestFcn.

If a figure's handle is hidden (i.e., the figure's HandleVisibility property is set to callback or off and the root ShowHiddenHandles property is set on), you must specify the hidden option when trying to access a figure using the all option.

To delete all figures unconditionally, use the statements:

*

set(0,'ShowHiddenHandles','on')
delete(get(0,'Children'))

The delete function does not execute the figure's CloseRequestFcn; it simply deletes the specified figure.

The figure CloseRequestFcn allows you to either delay or abort the closing of a figure once the close function has been issued. For example, you can display a dialog box to see if the user really wants to delete the figure or save and clean up before closing.

continued..

clc

Clear Command Window

Graphical Interface

As an alternative to the clc function, use Clear Command Window in the MATLAB desktop Edit menu.

Syntax

*

clc

Description

clc clears all input and output from the Command Window display, giving you a "clean screen."

After using clc, you cannot use the scroll bar to see the history of functions, but still can use the up arrow to recall statements from the command history.

Examples

Use clc in an M-file to always display output in the same starting position on the screen.



clear

Remove items from workspace, freeing up system memory

Graphical Interface

As an alternative to the clear function, use Clear Workspace in the MATLAB desktop Edit menu, or in the context menu in the Workspace browser.

Syntax

*

clear
clear name
clear name1 name2 name3 ...
clear global name
clear keyword
clear('name1','name2','name3',...)

Description

clear removes all variables from the workspace. This frees up system memory.

clear name removes just the M-file or MEX-file function or variable name from the workspace. You can use wildcards (*) to remove items selectively. For example, clear my* removes any variables whose names begin with the string my. It removes debugging breakpoints in M-files and reinitializes persistent variables, since the breakpoints for a function and persistent variables are cleared whenever the M-file is changed or cleared. If name is global, it is removed from the current workspace, but left accessible to any functions declaring it global. If name has been locked by mlock, it remains in memory.

Use a partial path to distinguish between different overloaded versions of a function. For example, clear inline/display clears only the display method for inline objects, leaving any other implementations in memory.

clear name1 name2 name3 ... removes name1, name2, and name3 from the workspace.

clear global name removes the global variable name. If name is global, clear name removes name from the current workspace, but leaves it accessible to any functions declaring it global. Use clear global name to completely remove a global variable.

clear keyword clears the items indicated by keyword.

Keyword
Items Cleared
all
Removes all variables, functions, and MEX-files from memory, leaving the workspace empty. Using clear all removes debugging breakpoints in M-files and reinitializes persistent variables, since the breakpoints for a function and persistent variables are cleared whenever the M-file is changed or cleared. When issued from the Command Window prompt, also removes the Java packages import list.
classes
The same as clear all, but also clears MATLAB class definitions. If any objects exist outside the workspace (for example, in user data or persistent variables in a locked M-file), a warning is issued and the class definition is not cleared. Issue a clear classes function if the number or names of fields in a class are changed.
functions
Clears all the currently compiled M-functions and MEX-functions from memory. Using clear function removes debugging breakpoints in the function M-file and reinitializes persistent variables, since the breakpoints for a function and persistent variables are cleared whenever the M-file is changed or cleared.
global
Clears all global variables from the workspace.
import
Removes the Java packages import list. It can only be issued from the Command Window prompt. It cannot be used in a function.
variables
Clears all variables from the workspace.

clear('name1','name2','name3',...) is the function form of the syntax. Use this form when the variable name or function name is stored in a string.

Remarks

When you use clear in a function, it has the following effect on items in your function and base workspaces:

* clear name--If name is the name of a function, the function is cleared in both the function workspace and in your base workspace.
* clear functions--All functions are cleared in both the function workspace and in your base workspace.
* clear global--All global variables are cleared in both the function workspace and in your base workspace.
* clear all--All functions, global variables, and classes are cleared in both the function workspace and in your base workspace.

Limitations

clear does not affect the amount of memory allocated to the MATLAB process under UNIX.

Examples

Given a workspace containing the following variables

*

Name Size Bytes Class

c 3x4 1200 cell array
frame 1x1 java.awt.Frame
gbl1 1x1 8 double array (global)
gbl2 1x1 8 double array (global)
xint 1x1 1 int8 array

you can clear a single variable, xint, by typing

*

clear xint

To clear all global variables, type

*

clear global
whos
Name Size Bytes Class

c 3x4 1200 cell array
frame 1x1 java.awt.Frame

To clear all compiled M- and MEX-functions from memory, type clear functions. In the case shown below, clear functions was unable to clear one M-file function from memory, testfun, because the function is locked.

*

clear functions % Attempt to clear all functions.

inmem
ans =
'testfun' % One M-file function remains in memory.

mislocked testfun
ans =
1 % This function is locked in memory.

Once you unlock the function from memory, you can clear it.

*

munlock testfun
clear functions

inmem
ans =
Empty cell array: 0-by-1

continued...

clabel

Contour plot elevation labels

Syntax

*

clabel(C,h)
clabel(C,h,v)
clabel(C,h,'manual')

clabel(C)
clabel(C,v)
clabel(C,'manual')

Description

The clabel function adds height labels to a two-dimensional contour plot.

clabel(C,h) rotates the labels and inserts them in the contour lines. The function inserts only those labels that fit within the contour, depending on the size of the contour.

clabel(C,h,v) creates labels only for those contour levels given in vector v, then rotates the labels and inserts them in the contour lines.

clabel(C,h,'manual') places contour labels at locations you select with a mouse. Press the left mouse button (the mouse button on a single-button mouse) or the space bar to label a contour at the closest location beneath the center of the cursor. Press the Return key while the cursor is within the figure window to terminate labeling. The labels are rotated and inserted in the contour lines.

clabel(C) adds labels to the current contour plot using the contour structure C output from contour. The function labels all contours displayed and randomly selects label positions.

clabel(C,v) labels only those contour levels given in vector v.

clabel(C,'manual') places contour labels at locations you select with a mouse.

Remarks

When the syntax includes the argument h, this function rotates the labels and inserts them in the contour lines (see Example). Otherwise, the labels are displayed upright and a '+' indicates which contour line the label is annotating.

Examples

Generate, draw, and label a simple contour plot.

*

[x,y] = meshgrid(-2:.2:2);
z = x.^exp(-x.^2-y.^2);
[C,h] = contour(x,y,z);
clabel(C,h);

class

Create object or return class of object

Syntax

*

str = class(object)
obj = class(s,'class_name')
obj = class(s,'class_name',parent1,parent2...)
obj = class(struct([]),'class_name',parent1,parent2...)

Description

str = class(object) returns a string specifying the class of object.

The following table lists the object class names that may be returned. All except the last one are MATLAB classes.

logical
Logical array of true and false values
char
Characters array
int8
8-bit signed integer array
uint8
8-bit unsigned integer array
int16
16-bit signed integer array
uint16
16-bit unsigned integer array
int32
32-bit signed integer array
uint32
32-bit unsigned integer array
int64
64-bit signed integer array
uint64
64-bit unsigned integer array
single
Single-precision floating point number array
double
Double-precision floating point number array
cell
Cell array
struct
Structure array
function handle
Array of values for calling functions indirectly
'class_name'
Custom MATLAB object class or Java class

obj = class(s,'class_name') creates an object of MATLAB class 'class_name' using structure s as a template. This syntax is valid only in a function named class_name.m in a directory named @class_name (where 'class_name' is the same as the string passed into class).

obj = class(s,'class_name',parent1,parent2,...) creates an object of MATLAB class 'class_name' that inherits the methods and fields of the parent objects parent1, parent2, and so on. Structure s is used as a template for the object.

obj = class(struct([]),'class_name',parent1,parent2,...) creates an object of MATLAB class 'class_name' that inherits the methods and fields of the parent objects parent1, parent2, and so on. Specifying the empty structure, struct([]), as the first argument ensures that the object created contains no fields other than those that are inherited from the parent objects.

Examples

To return in nameStr the name of the class of Java object j

*

nameStr = class(j)

To create a user-defined MATLAB object of class polynom

*

p = class(p,'polynom')
cholupdate

Rank 1 update to Cholesky factorization

Syntax

*

R1 = cholupdate(R,x)
R1 = cholupdate(R,x,'+')
R1 = cholupdate(R,x,'-')
[R1,p] = cholupdate(R,x,'-')

Description

R1 = cholupdate(R,x) where R = chol(A) is the original Cholesky factorization of A, returns the upper triangular Cholesky factor of A + x*x', where x is a column vector of appropriate length. cholupdate uses only the diagonal and upper triangle of R. The lower triangle of R is ignored.

R1 = cholupdate(R,x,'+') is the same as R1 = cholupdate(R,x).

R1 = cholupdate(R,x,'-') returns the Cholesky factor of A - x*x'. An error message reports when R is not a valid Cholesky factor or when the downdated matrix is not positive definite and so does not have a Cholesky factoriza- tion.

[R1,p] = cholupdate(R,x,'-') will not return an error message. If p is 0, R1 is the Cholesky factor of A - x*x'. If p is greater than 0, R1 is the Cholesky factor of the original A. If p is 1, cholupdate failed because the downdated matrix is not positive definite. If p is 2, cholupdate failed because the upper triangle of R was not a valid Cholesky factor.

Remarks

cholupdate works only for full matrices.

Example

*

A = pascal(4)
A =

1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 20

R = chol(A)
R =

1 1 1 1
0 1 2 3
0 0 1 3
0 0 0 1
x = [0 0 0 1]';

This is called a rank one update to A since rank(x*x') is 1:

*

A + x*x'
ans =

*

1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 21

Instead of computing the Cholesky factor with R1 = chol(A + x*x'), we can use cholupdate:

*

R1 = cholupdate(R,x)
R1 =

*

1.0000 1.0000 1.0000 1.0000
0 1.0000 2.0000 3.0000
0 0 1.0000 3.0000
0 0 0 1.4142

Next destroy the positive definiteness (and actually make the matrix singular) by subtracting 1 from the last element of A. The downdated matrix is:

*

A - x*x'
ans =

1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 19

Compare chol with cholupdate:

*

R1 = chol(A-x*x')
??? Error using ==> chol
Matrix must be positive definite.
R1 = cholupdate(R,x,'-')
??? Error using ==> cholupdate
Downdated matrix must be positive definite.

However, subtracting 0.5 from the last element of A produces a positive definite matrix, and we can use cholupdate to compute its Cholesky factor:

*

x = [0 0 0 1/sqrt(2)]';
R1 = cholupdate(R,x,'-')
R1 =
1.0000 1.0000 1.0000 1.0000
0 1.0000 2.0000 3.0000
0 0 1.0000 3.0000
0 0 0 0.7071

Algorithm

cholupdate uses the algorithms from the LINPACK subroutines ZCHUD and ZCHDD. cholupdate is useful since computing the new Cholesky factor from scratch is an algorithm, while simply updating the existing factor in this way is an algorithm.

circshift

Shift array circularly

Syntax

*

B = circshift(A,shiftsize)

Description

B = circshift(A,shiftsize) circularly shifts the values in the array, A, by shiftsize elements. shiftsize is a vector of integer scalars where the n-th element specifies the shift amount for the n-th dimension of array A. If an element in shiftsize is positive, the values of A are shifted down (or to the right). If it is negative, the values of A are shifted up (or to the left). If it is 0, the values in that dimension are not shifted.

Example

Circularly shift first dimension values down by 1.

*

A = [ 1 2 3;4 5 6; 7 8 9]
A =
1 2 3
4 5 6
7 8 9

B = circshift(A,1)
B =
7 8 9
1 2 3
4 5 6

Circularly shift first dimension values down by 1 and second dimension values to the left by 1.

*

B = circshift(A,[1 -1]);
B =
8 9 7
2 3 1
5 6 4

cla

Clear current axes

Syntax

*

cla
cla reset

Description

cla deletes from the current axes all graphics objects whose handles are not hidden (i.e., their HandleVisibility property is set to on).

cla reset deletes from the current axes all graphics objects regardless of the setting of their HandleVisibility property and resets all axes properties, except Position and Units, to their default values.

Remarks

The cla command behaves the same way when issued on the command line as it does in callback routines - it does not recognize the HandleVisibility setting of callback. This means that when issued from within a callback routine, cla deletes only those objects whose HandleVisibility property is set to on.
chol

Cholesky factorization

Syntax

*

R = chol(X)
[R,p] = chol(X)

Description

The chol function uses only the diagonal and upper triangle of X. The lower triangular is assumed to be the (complex conjugate) transpose of the upper. That is, X is Hermitian.

R = chol(X), where X is positive definite produces an upper triangular R so that R'*R = X. If X is not positive definite, an error message is printed.

[R,p] = chol(X), with two output arguments, never produces an error message. If X is positive definite, then p is 0 and R is the same as above. If X is not positive definite, then p is a positive integer and R is an upper triangular matrix of order q = p-1 so that R'*R = X(1:q,1:q).

Examples

The binomial coefficients arranged in a symmetric array create an interesting positive definite matrix.

*

n = 5;
X = pascal(n)
X =
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70

It is interesting because its Cholesky factor consists of the same coefficients, arranged in an upper triangular matrix.

*

R = chol(X)
R =
1 1 1 1 1
0 1 2 3 4
0 0 1 3 6
0 0 0 1 4
0 0 0 0 1

Destroy the positive definiteness (and actually make the matrix singular) by subtracting 1 from the last element.

*

X(n,n) = X(n,n)-1

X =
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 69

Now an attempt to find the Cholesky factorization fails.

Algorithm

chol uses the the LAPACK subroutines DPOTRF (real) and ZPOTRF (complex).

cholinc

Sparse incomplete Cholesky and Cholesky-Infinity factorizations

Syntax

*

R = cholinc(X,droptol)
R = cholinc(X,options)
R = cholinc(X,'0')
[R,p] = cholinc(X,'0')
R = cholinc(X,'inf')

Description

cholinc produces two different kinds of incomplete Cholesky factorizations: the drop tolerance and the 0 level of fill-in factorizations. These factors may be useful as preconditioners for a symmetric positive definite system of linear equations being solved by an iterative method such as pcg (Preconditioned Conjugate Gradients). cholinc works only for sparse matrices.

R = cholinc(X,droptol) performs the incomplete Cholesky factorization of X, with drop tolerance droptol.

R = cholinc(X,options) allows additional options to the incomplete Cholesky factorization. options is a structure with up to three fields:

droptol
Drop tolerance of the incomplete factorization
michol
Modified incomplete Cholesky
rdiag
Replace zeros on the diagonal of R

Only the fields of interest need to be set.

droptol is a non-negative scalar used as the drop tolerance for the incomplete Cholesky factorization. This factorization is computed by performing the incomplete LU factorization with the pivot threshold option set to 0 (which forces diagonal pivoting) and then scaling the rows of the incomplete upper triangular factor, U, by the square root of the diagonal entries in that column. Since the nonzero entries U(i,j) are bounded below by droptol*norm(X(:,j)) (see luinc), the nonzero entries R(i,j) are bounded below by the local drop tolerance droptol*norm(X(:,j))/R(i,i).

Setting droptol = 0 produces the complete Cholesky factorization, which is the default.

michol stands for modified incomplete Cholesky factorization. Its value is either 0 (unmodified, the default) or 1 (modified). This performs the modified incomplete LU factorization of X and scales the returned upper triangular factor as described above.

rdiag is either 0 or 1. If it is 1, any zero diagonal entries of the upper triangular factor R are replaced by the square root of the local drop tolerance in an attempt to avoid a singular factor. The default is 0.

R = cholinc(X,'0') produces the incomplete Cholesky factor of a real sparse matrix that is symmetric and positive definite using no fill-in. The upper triangular R has the same sparsity pattern as triu(X), although R may be zero in some positions where X is nonzero due to cancellation. The lower triangle of X is assumed to be the transpose of the upper. Note that the positive definiteness of X does not guarantee the existence of a factor with the required sparsity. An error message results if the factorization is not possible. If the factorization is successful, R'*R agrees with X over its sparsity pattern.

[R,p] = cholinc(X,'0') with two output arguments, never produces an error message. If R exists, p is 0. If R does not exist, then p is a positive integer and R is an upper triangular matrix of size q-by-n where q = p-1. In this latter case, the sparsity pattern of R is that of the q-by-n upper triangle of X. R'*R agrees with X over the sparsity pattern of its first q rows and first q columns.

R = cholinc(X,'inf') produces the Cholesky-Infinity factorization. This factorization is based on the Cholesky factorization, and additionally handles real positive semi-definite matrices. It may be useful for finding a solution to systems which arise in interior-point methods. When a zero pivot is encountered in the ordinary Cholesky factorization, the diagonal of the Cholesky-Infinity factor is set to Inf and the rest of that row is set to 0. This forces a 0 in the corresponding entry of the solution vector in the associated system of linear equations. In practice, X is assumed to be positive semi-definite so even negative pivots are replaced with a value of Inf.

Remarks

The incomplete factorizations may be useful as preconditioners for solving large sparse systems of linear equations. A single 0 on the diagonal of the upper triangular factor makes it singular. The incomplete factorization with a drop tolerance prints a warning message if the upper triangular factor has zeros on the diagonal. Similarly, using the rdiag option to replace a zero diagonal only gets rid of the symptoms of the problem, but it does not solve it. The preconditioner may not be singular, but it probably is not useful, and a warning message is printed.

The Cholesky-Infinity factorization is meant to be used within interior-point methods. Otherwise, its use is not recommended.

Examples

Example 1.

Start with a symmetric positive definite matrix, S.

*

S = delsq(numgrid('C',15));

S is the two-dimensional, five-point discrete negative Lapacian on the grid generated by numgrid('C',15).

Compute the Cholesky factorization and the incomplete Cholesky factorization of level 0 to compare the fill-in. Make S singular by zeroing out a diagonal entry and compute the (partial) incomplete Cholesky factorization of level 0.

*

C = chol(S);
R0 = cholinc(S,'0');
S2 = S; S2(101,101) = 0;
[R,p] = cholinc(S2,'0');

Fill-in occurs within the bands of S in the complete Cholesky factor, but none in the incomplete Cholesky factor. The incomplete factorization of the singular S2 stopped at row p = 101 resulting in a 100-by-139 partial factor.

*

D1 = (R0'*R0).*spones(S)-S;
D2 = (R'*R).*spones(S2)-S2;

D1 has elements of the order of eps, showing that R0'*R0 agrees with S over its sparsity pattern. D2 has elements of the order of eps over its first 100 rows and first 100 columns, D2(1:100,:) and D2(:,1:100).

Example 2.

The first subplot below shows that cholinc(S,0), the incomplete Cholesky factor with a drop tolerance of 0, is the same as the Cholesky factor of S. Increasing the drop tolerance increases the sparsity of the incomplete factors, as seen below.

Unfortunately, the sparser factors are poor approximations, as is seen by the plot of drop tolerance versus norm(R'*R-S,1)/norm(S,1) in the next figure.

Example 3.

The Hilbert matrices have (i,j) entries 1/(i+j-1) and are theoretically positive definite:

*

H3 = hilb(3)
H3 =
1.0000 0.5000 0.3333
0.5000 0.3333 0.2500
0.3333 0.2500 0.2000
R3 = chol(H3)
R3 =
1.0000 0.5000 0.3333
0 0.2887 0.2887
0 0 0.0745

In practice, the Cholesky factorization breaks down for larger matrices:

*

H20 = sparse(hilb(20));
[R,p] = chol(H20);
p =
14

For hilb(20), the Cholesky factorization failed in the computation of row 14 because of a numerically zero pivot. You can use the Cholesky-Infinity factorization to avoid this error. When a zero pivot is encountered, cholinc places an Inf on the main diagonal, zeros out the rest of the row, and continues with the computation:

*

Rinf = cholinc(H20,'inf');

In this case, all subsequent pivots are also too small, so the remainder of the upper triangular factor is:

*

full(Rinf(14:end,14:end))
ans =
Inf 0 0 0 0 0 0
0 Inf 0 0 0 0 0
0 0 Inf 0 0 0 0
0 0 0 Inf 0 0 0
0 0 0 0 Inf 0 0
0 0 0 0 0 Inf 0
0 0 0 0 0 0 Inf

Limitations

cholinc works on square sparse matrices only. For cholinc(X,'0') and cholinc(X,'inf'), X must be real.

Algorithm

R = cholinc(X,droptol) is obtained from [L,U] = luinc(X,options), where options.droptol = droptol and options.thresh = 0. The rows of the uppertriangular U are scaled by the square root of the diagonal in that row, and this scaled factor becomes R.

R = cholinc(X,options) is produced in a similar manner, except the rdiag option translates into the udiag option and the milu option takes the value of the michol option.

R = cholinc(X,'0') is based on the "KJI" variant of the Cholesky factorization. Updates are made only to positions which are nonzero in the upper triangle of X.

R = cholinc(X,'inf') is based on the algorithm in Zhang [2].
cgs

Conjugate Gradients Squared method

Syntax

  • x = cgs(A,b)
    cgs(A,b,tol)
    cgs(A,b,tol,maxit)
    cgs(A,b,tol,maxit,M)
    cgs(A,b,tol,maxit,M1,M2)
    cgs(A,b,tol,maxit,M1,M2,x0)
    cgs(afun,b,tol,maxit,m1fun,m2fun,x0,p1,p2,...)
    [x,flag] = cgs(A,b,...)
    [x,flag,relres] = cgs(A,b,...)
    [x,flag,relres,iter] = cgs(A,b,...)
    [x,flag,relres,iter,resvec] = cgs(A,b,...)

Description

x = cgs(A,b) attempts to solve the system of linear equations A*x = b for x. The n-by-n coefficient matrix A must be square and should be large and sparse. The column vector b must have length n. A can be a function afun such that afun(x) returns A*x.

If cgs converges, a message to that effect is displayed. If cgs fails to converge after the maximum number of iterations or halts for any reason, a warning message is printed displaying the relative residual norm(b-A*x)/norm(b) and the iteration number at which the method stopped or failed.

cgs(A,b,tol) specifies the tolerance of the method, tol. If tol is [], then cgs uses the default, 1e-6.

cgs(A,b,tol,maxit) specifies the maximum number of iterations, maxit. If maxit is [] then cgs uses the default, min(n,20).

cgs(A,b,tol,maxit,M) and cgs(A,b,tol,maxit,M1,M2) use the preconditioner M or M = M1*M2 and effectively solve the system inv(M)*A*x = inv(M)*b for x. If M is [] then cgs applies no preconditioner. M can be a function that returns M\x.

cgs(A,b,tol,maxit,M1,M2,x0) specifies the initial guess x0. If x0 is [], then cgs uses the default, an all-zero vector.

cgs(afun,b,tol,maxit,m1fun,m2fun,x0,p1,p2,...) passes parameters p1,p2,... to functions afun(x,p1,p2,...), m1fun(x,p1,p2,...), and m2fun(x,p1,p2,...)

[x,flag] = cgs(A,b,...) returns a solution x and a flag that describes the convergence of cgs.


Flag
Convergence
0
cgs converged to the desired tolerance tol within maxit iterations.
1
cgs iterated maxit times but did not converge.
2
Preconditioner M was ill-conditioned.
3
cgs stagnated. (Two consecutive iterates were the same.)
4
One of the scalar quantities calculated during cgs became too small or too large to continue computing.

Whenever flag is not 0, the solution x returned is that with minimal norm residual computed over all the iterations. No messages are displayed if the flag output is specified.

[x,flag,relres] = cgs(A,b,...) also returns the relative residual norm(b-A*x)/norm(b). If flag is 0, then relres <= tol.

[x,flag,relres,iter] = cgs(A,b,...) also returns the iteration number at which x was computed, where 0 <= iter <= maxit.

[x,flag,relres,iter,resvec] = cgs(A,b,...) also returns a vector of the residual norms at each iteration, including norm(b-A*x0).

Examples

Example 1.

  • A = gallery('wilk',21);
    b = sum(A,2);
    tol = 1e-12; maxit = 15;
    M1 = diag([10:-1:1 1 1:10]);
    x = cgs(A,b,tol,maxit,M1,[],[]);

Alternatively, use this matrix-vector product function

  • function y = afun(x,n)
    y = [ 0;
    x(1:n-1)] + [((n-1)/2:-1:0)';
    (1:(n-1)/2)'] .*x + [x(2:n);
    0 ];

and this preconditioner backsolve function

  • function y = mfun(r,n)
    y = r ./ [((n-1)/2:-1:1)'; 1; (1:(n-1)/2)'];

as inputs to cgs.

  • x1 = cgs(@afun,b,tol,maxit,@mfun,[],[],21);

Note that both afun and mfun must accept cgs's extra input n=21.

Example 2.

  • load west0479
    A = west0479
    b = sum(A,2)
    [x,flag] = cgs(A,b)

flag is 1 because cgs does not converge to the default tolerance 1e-6 within the default 20 iterations.

  • [L1,U1] = luinc(A,1e-5)
    [x1,flag1] = cgs(A,b,1e-6,20,L1,U1)

flag1 is 2 because the upper triangular U1 has a zero on its diagonal, and cgs fails in the first iteration when it tries to solve a system such as U1*y = r for y with backslash.

  • [L2,U2] = luinc(A,1e-6)
    [x2,flag2,relres2,iter2,resvec2] = cgs(A,b,1e-15,10,L2,U2)

flag2 is 0 because cgs converges to the tolerance of 6.344e-16 (the value of relres2) at the fifth iteration (the value of iter2) when preconditioned by the incomplete LU factorization with a drop tolerance of 1e-6. resvec2(1) = norm(b) and resvec2(6) = norm(b-A*x2). You can follow the progress of cgs by plotting the relative residuals at each iteration starting from the initial estimate (iterate number 0) with

  • semilogy(0:iter2,resvec2/norm(b),'-o')
    xlabel('iteration number')
    ylabel('relative residual')



char

Create character array (string)

Syntax

  • S = char(X)
    S = char(C)
    S = char(t1,t2,t3...)

Description

S = char(X) converts the array X that contains positive integers representing character codes into a MATLAB character array (the first 127 codes are ASCII). The actual characters displayed depend on the character set encoding for a given font. The result for any elements of X outside the range from 0 to 65535 is not defined (and may vary from platform to platform). Use double to convert a character array into its numeric codes.

S = char(C) when C is a cell array of strings, places each element of C into the rows of the character array s. Use cellstr to convert back.

S = char(t1,t2,t3,..) forms the character array S containing the text strings T1,T2,T3,... as rows, automatically padding each string with blanks to form a valid matrix. Each text parameter, Ti, can itself be a character array. This allows the creation of arbitrarily large character arrays. Empty strings are significant.

Remarks

Ordinarily, the elements of A are integers in the range 32:127, which are the printable ASCII characters, or in the range 0:255, which are all 8-bit values. For noninteger values, or values outside the range 0:255, the characters printed are determined by fix(rem(A,256)).

Examples

To print a 3-by-32 display of the printable ASCII characters:

  • ascii = char(reshape(32:127,32,3)')
    ascii =
    ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
    @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _
    ' a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~
checkin

Check file into source control system

Graphical Interface

As an alternative to the checkin function, use Source Control Check In in the Editor, Simulink, or Stateflow File menu.

Syntax

  • checkin('filename','comments','string')
    checkin({'filename1','filename2','filename3', ...},'comments',
    'string')
    checkin('filename','option','value', ...)

Description

checkin('filename','comments','string') checks in the file named filename to the source control system. Use the full pathname for the filename. You must save the file before checking it in. The file can be open or closed when you use checkin. The string argument is a MATLAB string containing check-in comments for the source control system. You must supply the comments argument and 'string'.

checkin({'filename1','filename2','filename3', ...},'comments', 'string') checks in the files named filename1 through filenamen to the source control system. Use the full pathnames for the files. Additional arguments apply to all files checked in.

checkin('filename','option','value', ...) provides additional checkin options. The option and value arguments are shown in the table below.


option Argument
Purpose
value Argument
'force'

When set to on, filename is checked in even if the file has not changed since it was checked out. The default value for force is off.

'on'
'off' (default)
'lock'
When set to on, filename remains checked out. Comments are submitted. The default value for lock is off.
'on'
'off' (default)

You can check in a file that you checked out in a previous MATLAB session or that you checked out directly from your source control system.

Examples

Check in a File with Comments

Typing

  • checkin('/matlab/mymfiles/clock.m','comments','Adjustment for
    Y2K')

checks in the file /matlab/mymfiles/clock.m to the source control system with the comment Adjustment for Y2K.

Check in Multiple Files with Comments

Typing

  • checkin({'/matlab/mymfiles/clock.m', ...
    '/matlab/mymfiles/calendar.m'},'comments','Adjustment for Y2K')

checks two files into the source control system using the same comment for each.

Check a File in and Keep It Checked out

Typing

  • checkin('/matlab/mymfiles/clock.m','comments','Adjustment for
    Y2K','lock','on')

checks the file /matlab/mymfiles/clock.m into the source control system and keeps the file checked out.

checkout

Check file out of source control system

Graphical Interface

As an alternative to the checkout function, use Source Control Check Out in the Editor, Simulink, or Stateflow File menu.

Syntax

  • checkout('filename')
    checkout({'filename1','filename2','filename3', ...})
    checkout('filename','option','value', ...)

Description

checkout('filename') checks out the file named filename from the source control system. filename must be the full pathname for the file. The file can be open or closed when you use checkout.

checkout({'filename1','filename2','filename3', ...}) checks out the files named filename1 through filenamen from the source control system. Use the full pathnames for the files. Additional arguments apply to all files checked out.

checkout('filename','option','value', ...) provides additional checkout options. The option and value arguments are shown in the following table.


option Argument
Purpose
value Argument
'force'
When set to on, the checkout is forced, even if you already have the file checked out. This is effectively an undocheckout followed by a checkout. When force is set to off, you can't check out the file if you already have it checked out.
'on'
'off' (default)
'lock'
When set to on, the checkout gets the file, allows you to write to it, and locks the file so that access to the file for others is read only. When set to off, the checkout gets a read-only version of the file, allowing another user to check out the file for updating. With lock set to off, you don't have to check in a file after checking it out.
'on' (default)
'off'
'revision'
Checks out the specified revision of the file.
'version_num'

If you end the MATLAB session, the file remains checked out. You can check in the file from within MATLAB during a later session, or directly from your source control system.

Examples

Check out a File

Typing

  • checkout('/matlab/mymfiles/clock.m')

checks out the file /matlab/mymfiles/clock.m from the source control system.

Check out Multiple Files

Typing

  • checkout({'/matlab/mymfiles/clock.m',...
    '/matlab/mymfiles/calendar.m'})

checks out /matlab/mymfiles/clock.m and
/matlab/mymfiles/calendar.m from the source control system.

Force a Checkout, Even If File Is Already Checked out

Typing

  • checkout('/matlab/mymfiles/clock.m','force','on')

checks out /matlab/mymfiles/clock.m even if clock.m is already checked out to you.

Check out Specified Revision of File

Typing

  • checkout('/matlab/mymfiles/clock.m','revision','1.1')

checks out revision 1.1 of clock.m.

cell

Create cell array

Syntax

  • c = cell(n)
    c = cell(m,n) or c = cell([m n])
    c = cell(m,n,p,...) or c = cell([m n p ...])
    c = cell(size(A))
    c = cell(javaobj)

Description

c = cell(n) creates an n-by-n cell array of empty matrices. An error message appears if n is not a scalar.

c = cell(m,n) or c = cell([m,n]) creates an m-by-n cell array of empty matrices. Arguments m and n must be scalars.

c = cell(m,n,p,...) or c = cell([m n p ...]) creates an m-by-n-by-p-... cell array of empty matrices. Arguments m, n, p,... must be scalars.

c = cell(size(A)) creates a cell array the same size as A containing all empty matrices.

c = cell(javaobj) converts a Java array or Java object, javaobj, into a MATLAB cell array. Elements of the resulting cell array will be of the MATLAB type (if any) closest to the Java array elements or Java object.

Examples

This example creates a cell array that is the same size as another array, A.

  • A = ones(2,2)

    A =
    1 1
    1 1

    c = cell(size(A))

    c =
    [] []
    [] []

The next example converts an array of java.lang.String objects into a MATLAB cell array.

  • strArray = java_array('java.lang.String',3);
    strArray(1) = java.lang.String('one');
    strArray(2) = java.lang.String('two');
    strArray(3) = java.lang.String('three');

    cellArray = cell(strArray)
    cellArray =
    'one'
    'two'
    'three'
cell2mat

Convert cell array of matrices into single matrix

Syntax

  • m = cell2mat(c)

Description

m = cell2mat(c) converts a multidimensional cell array, c, with contents of the same data type into a single matrix, m. The contents of c must be able to concatenate into a hyperrectangle. Moreover, for each pair of neighboring cells, the dimensions of the cell's contents must match, excluding the dimension in which the cells are neighbors.

The example shown below combines matrices in a 3-by-2 cell array into a single 60-by-50 matrix:

  • cell2mat(c)



Remarks

The dimensionality (or number of dimensions) of m will match the highest dimensionality contained in the cell array.

cell2mat is not supported for cell arrays containing cell arrays or objects.

Examples

Combine the matrices in four cells of cell array C into the single matrix, M:

  • C = {[1] [2 3 4]; [5; 9] [6 7 8; 10 11 12]}
    C =
    [ 1] [1x3 double]
    [2x1 double] [2x3 double]

    C{1,1} C{1,2}
    ans = ans =
    1 2 3 4

    C{2,1} C{2,2}
    ans = ans =
    5 6 7 8
    9 10 11 12

    M = cell2mat(C)
    M =
    1 2 3 4
    5 6 7 8
    9 10 11 12
cell2struct

Convert cell array to structure array

Syntax

  • s = cell2struct(c,fields,dim)

Description

s = cell2struct(c,fields,dim) creates a structure array, s, from the information contained within cell array, c.

The fields argument specifies field names for the structure array. fields can be a character array or a cell array of strings.

The dim argument controls which axis of the cell array is to be used in creating the structure array. The length of c along the specified dimension must match the number of fields named in fields. In other words, the following must be true.

  • size(c,dim) == length(fields)       % if fields is a cell array
    size(c,dim) == size(fields,1) % if fields is a char array

Examples

The cell array, c, in this example contains information on trees. The three columns of the array indicate the common name, genus, and average height of a tree.

  • c = {'birch','betula',65;  'maple','acer',50}
    c =
    'birch' 'betula' [65]
    'maple' 'acer' [50]

To put this information into a structure with the fields name, genus, and height, use cell2struct along the second dimension of the 2-by-3 cell array.

  • fields = {'name', 'genus', 'height'};
    s = cell2struct(c, fields, 2);

This yields the following 2-by-1 structure array.

  • s(1)                        s(2)
    ans = ans =
    name: 'birch' name: 'maple'
    genus: 'betula' genus: 'acer'
    height: 65 height: 50
celldisp

Display cell array contents.

Syntax

  • celldisp(C)
    celldisp(C,name)

Description

celldisp(C) recursively displays the contents of a cell array.

celldisp(C,name) uses the string name for the display instead of the name of the first input (or ans).

Example

Use celldisp to display the contents of a 2-by-3 cell array:

  • C = {[1 2] 'Tony' 3+4i; [1 2;3 4] -5 'abc'};
    celldisp(C)

    C{1,1} =
    1 2

    C{2,1} =
    1 2
    3 4

    C{1,2} =
    Tony

    C{2,2} =
    -5

    C{1,3} =
    3.0000+ 4.0000i

    C{2,3} =
    abc
cellfun

Apply a function to each element in a cell array

Syntax

  • D = cellfun('fname',C)
    D = cellfun('size',C,k)
    D = cellfun('isclass',C,classname)

Description

D = cellfun('fname',C) applies the function fname to the elements of the cell array C and returns the results in the double array D. Each element of D contains the value returned by fname for the corresponding element in C. The output array D is the same size as the cell array C.

These functions are supported:


Function
Return Value
isempty
true for an empty cell element
islogical
true for a logical cell element
isreal
true for a real cell element
length
Length of the cell element
ndims
Number of dimensions of the cell element
prodofsize
Number of elements in the cell element

D = cellfun('size',C,k) returns the size along the k-th dimension of each element of C.

D = cellfun('isclass',C,'classname') returns true for each element of C that matches classname. This function syntax returns false for objects that are a subclass of classname.

Limitations

If the cell array contains objects, cellfun does not call overloaded versions of the function fname.

Example

Consider this 2-by-3 cell array:

  • C{1,1} = [1 2; 4 5];
    C{1,2} = 'Name';
    C{1,3} = pi;
    C{2,1} = 2 + 4i;
    C{2,2} = 7;
    C{2,3} = magic(3);

cellfun returns a 2-by-3 double array:

  • D = cellfun('isreal',C)

    D =
    1 1 1
    0 1 1

    len = cellfun('length',C)

    len =
    2 4 1
    1 1 3

    isdbl = cellfun('isclass',C,'double')

    isdbl =
    1 0 1
    1 1 1
cellplot

Graphically display the structure of cell arrays

Syntax

  • cellplot(c)
    cellplot(c,'legend')
    handles = cellplot(...)

Description

cellplot(c) displays a figure window that graphically represents the contents of c. Filled rectangles represent elements of vectors and arrays, while scalars and short text strings are displayed as text.

cellplot(c,'legend') also puts a legend next to the plot.

handles = cellplot(c) displays a figure window and returns a vector of surface handles.

Limitations

The cellplot function can display only two-dimensional cell arrays.

Examples

Consider a 2-by-2 cell array containing a matrix, a vector, and two text strings:

  • c{1,1} = '2-by-2';
    c{1,2} = 'eigenvalues of eye(2)';
    c{2,1} = eye(2);
    c{2,2} = eig(eye(2));

The command cellplot(c) produces:



cellstr

Create cell array of strings from character array

Syntax

  • c = cellstr(S)

Description

c = cellstr(S) places each row of the character array S into separate cells of c. Use the char function to convert back to a string matrix.

Examples

Given the string matrix

  • S=['abc ';'defg';'hi  ']

    S =
    abc
    defg
    hi

    whos S
    Name Size Bytes Class
    S 3x4 24 char array

The following command returns a 3-by-1 cell array.

  • c = cellstr(S)

    c =
    'abc'
    'defg'
    'hi'

    whos c
    Name Size Bytes Class
    c 3x1 294 cell array