Building the Model

Building the Model

Simulink® provides a set of predefined blocks that you can combine to create a detailed block diagram of your system. Tools for hierarchical modeling, data management, and subsystem customization enable you to represent even the most complex system concisely and accurately.

Selecting Blocks

The Simulink Library Browser includes:

[tip]Continuous and discrete dynamics blocks, such as Integration and Unit Delay
Algorithmic blocks, such as Sum, Product, and Lookup Table
Structural blocks, such as Mux, Switch, and Bus Selector
You can build customized functions by using these blocks or by incorporating hand-written MATLAB®, C, Fortran, or Ada code into your model.[/tip]

Your custom blocks can be stored in their own libraries within the Simulink Library Browser.

Simulink add-on products let you incorporate specialized components for aerospace, communications, PID control, control logic, signal processing, video and image processing, and other applications. Add-on products are also available for modeling physical systems with mechanical, electrical, and hydraulic components.

Logical Subscripting

The logical vectors created from logical and relational operations can be used to reference
subarrays. Suppose X is an ordinary matrix and L is a matrix of the same size that is the
result of some logical operation. Then X(L) specifies the elements of X where the
elements of L are nonzero.

This kind of subscripting can be done in one step by specifying the logical operation as the
subscripting expression. Suppose you have the following set of data.

x =
  2.1 1.7 1.6 1.5 NaN 1.9 1.8 1.5 5.1 1.8 1.4 2.2 1.6 1.8

The NaN is a marker for a missing observation, such as a failure to respond to an item on a
questionnaire. To remove the missing data with logical indexing, use finite(x), which is
true for all finite numerical values and false for NaN and Inf.

x = x(finite(x))
x =
  2.1 1.7 1.6 1.5 1.9 1.8 1.5 5.1 1.8 1.4 2.2 1.6 1.8

Now there is one observation, 5.1, which seems to be very different from the others. It is an
outlier. The following statement removes outliers, in this case those elements more than
three standard deviations from the mean.

x = x(abs(x-mean(x)) <= 3*std(x))
x =
  2.1 1.7 1.6 1.5 1.9 1.8 1.5 1.8 1.4 2.2 1.6 1.8

For another example, highlight the location of the prime numbers in Dürer's magic square by
using logical indexing and scalar expansion to set the nonprimes to 0.

A(~isprime(A)) = 0
A =
     0     3     2    13
     5     0    11     0
     0     0     7     0
     0     0     0     0

The find Function

The find function determines the indices of array elements that meet a given logical
condition. In its simplest form, find returns a column vector of indices. Transpose that
vector to obtain a row vector of indices. For example,

k = find(isprime(A))'

picks out the locations, using one-dimensional indexing, of the primes in the magic square.

k =
     2     5     9    10    11    13

Display those primes, as a row vector in the order determined by k, with

A(k)
ans =
     5     3     2    11     7    13

When you use k as a left-hand-side index in an assignment statement, the matrix structure
is preserved.

A(k) = NaN
A =
    16   NaN   NaN   NaN
   NaN    10   NaN     8
     9     6   NaN    12
     4    15    14     1

Linear Algebra

Informally, the terms matrix and array are often used interchangeably. More precisely, a
matrix is a two-dimensional numeric array that represents a linear transformation. The
mathematical operations defined on matrices are the subject of linear algebra.

Dürer’s magic square

A =
    16     3     2    13
     5    10    11     8
     9     6     7    12
     4    15    14     1

provides several examples that give a taste of MATLAB matrix operations. You’ve already
seen the matrix transpose, A’. Adding a matrix to its transpose produces a symmetric matrix.

A + A'
ans =
    32     8    11    17
     8    20    17    23
    11    17    14    26
    17    23    26     2

The multiplication symbol, *, denotes the matrix multiplication involving inner products
between rows and columns. Multiplying the transpose of a matrix by the original matrix also
produces a symmetric matrix.

A'*A
ans =
   378   212   206   360
   212   370   368   206
   206   368   370   212
   360   206   212   378

The determinant of this particular matrix happens to be zero, indicating that the matrix is
singular.

d = det(A)
d =
     0

The reduced row echelon form of A is not the identity.

R = rref(A)
R =
     1     0     0     1
     0     1     0    -3
     0     0     1     3
     0     0     0     0

Since the matrix is singular, it does not have an inverse. If you try to compute the inverse with

X = inv(A)

you will get a warning message

[warning]Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = 1.175530e-017.[/warning]
Roundoff error has prevented the matrix inversion algorithm from detecting exact singularity.
But the value of rcond, which stands for reciprocal condition estimate, is on the order of
eps, the floating-point relative precision, so the computed inverse is unlikely to be of much
use.

The eigenvalues of the magic square are interesting.

e = eig(A)
e =
   34.0000
    8.0000
    0.0000
   -8.0000

One of the eigenvalues is zero, which is another consequence of singularity. The largest
eigenvalue is 34, the magic sum. That’s because the vector of all ones is an eigenvector.

v = ones(4,1)
v =
     1
     1
     1
     1
A*v
ans =
    34
    34
    34
    34

When a magic square is scaled by its magic sum,

P = A/34

the result is a doubly stochastic matrix whose row and column sums are all one.

P =
    0.4706    0.0882    0.0588    0.3824
    0.1471    0.2941    0.3235    0.2353
    0.2647    0.1765    0.2059    0.3529
    0.1176    0.4412    0.4118    0.0294

Such matrices represent the transition probabilities in a Markov process. Repeated powers
of the matrix represent repeated steps of the process. For our example, the fifth power

P^5

is

    0.2507    0.2495    0.2494    0.2504
    0.2497    0.2501    0.2502    0.2500
    0.2500    0.2498    0.2499    0.2503
    0.2496    0.2506    0.2505    0.2493

This shows that as k approaches infinity, all the elements in the kth power, Pk, approach 1/4.

[tip]Finally, the coefficients in the characteristic polynomial[/tip]

poly(A)

are

 1   -34   -64  2176     0

This indicates that the characteristic polynomial

det( A - I )

is

4 - 343 - 642 + 2176

The constant term is zero, because the matrix is singular, and the coefficient of the cubic
term is -34, because the matrix is magic!

Working with 8-Bit and 16-Bit Images

8-Bit and 16-Bit Indexed Images

Double-precision (64-bit) floating-point numbers are the default MATLAB representation for numeric data. However, to reduce memory requirements for working with images, you can store images as 8-bit or 16-bit unsigned integers using the numeric classes uint8 or uint16, respectively. An image whose data matrix has class uint8 is called an 8-bit image; an image whose data matrix has class uint16 is called a 16-bit image.

The image function can display 8- or 16-bit images directly without converting them to double precision. However, image interprets matrix values slightly differently when the image matrix is uint8 or uint16. The specific interpretation depends on the image type.

If the class of X is uint8 or uint16, its values are offset by 1 before being used as colormap indices. The value 0 points to the first row of the colormap, the value 1 points to the second row, and so on. The image command automatically supplies the proper offset, so the display method is the same whether X is double, uint8, or uint16:

image(X); colormap(map);

The colormap index offset for uint8 and uint16 data is intended to support standard graphics file formats, which typically store image data in indexed form with a 256-entry colormap. The offset allows you to manipulate and display images of this form using the more memory-efficient uint8 and uint16 arrays.

Because of the offset, you must add 1 to convert a uint8 or uint16 indexed image to double. For example:

X64 = double(X8) + 1;
	or
X64 = double(X16) + 1;

Conversely, subtract 1 to convert a double indexed image to uint8 or uint16:

X8 = uint8(X64 - 1);
	or
X16 = uint16(X64 - 1);

8-Bit and 16-Bit Intensity Images

The range of double image arrays is usually [0, 1], but the range of 8-bit intensity images is usually [0, 255] and the range of 16-bit intensity images is usually [0, 65535]. Use the following command to display an 8-bit intensity image with a grayscale colormap:

imagesc(I,[0 255]); colormap(gray);

To convert an intensity image from double to uint16, first multiply by 65535:

I16 = uint16(round(I64*65535));

Conversely, divide by 65535 after converting a uint16 intensity image to double:

8-Bit and 16-Bit RGB Images

I64 = double(I16)/65535;

The color components of an 8-bit RGB image are integers in the range [0, 255] rather than floating-point values in the range [0, 1]. A pixel whose color components are (255,255,255) is displayed as white. The image command displays an RGB image correctly whether its class is double, uint8, or uint16:

image(RGB);

To convert an RGB image from double to uint8, first multiply by 255:

RGB8 = uint8(round(RGB64*255));

Conversely, divide by 255 after converting a uint8 RGB image to double:

RGB64 = double(RGB8)/255

To convert an RGB image from double to uint16, first multiply by 65535:

RGB16 = uint16(round(RGB64*65535));

Conversely, divide by 65535 after converting a uint16 RGB image to double:

Mathematical Operations Support for uint8 and uint16

RGB64 = double(RGB16)/65535;

To use the following MATLAB functions with uint8 and uint16 data, first convert the data to type double:

  • conv2
  • convn
  • fft2
  • fftn

For example, if X is a uint8 image, cast the data to type double:

fft(double(X))

In these cases, the output is always double.

The sum function returns results in the same type as its input, but provides an option to use double precision for calculations.

See Arithmetic Operations on Integer Classes for more information on how mathematical functions work with data types that are not doubles.

Most Image Processing Toolbox™ functions accept uint8 and uint16 input. If you plan to do sophisticated image processing on uint8 or uint16 data, consider including that toolbox in your MATLAB computing environment.

Other 8-Bit and 16-Bit Array Support

You can perform several other operations on uint8 and uint16 arrays, including:

  • Reshaping, reordering, and concatenating arrays using the functions reshape, cat, permute, and the [] and ‘ operators
  • Saving and loading uint8 and uint16 arrays in MAT-files using save and load. (Remember that if you are loading or saving a graphics file format image, you must use the commands imread and imwrite instead.)
  • Locating the indices of nonzero elements in uint8 and uint16 arrays using find. However, the returned array is always of class double.
  • Relational operators
  • Converting an 8-Bit RGB Image to Grayscale

You can perform arithmetic operations on integer data, which enables you to convert image types without first converting the numeric class of the image data.

This example reads an 8-bit RGB image into a MATLAB variable and converts it to a grayscale image:

rgb_img = imread('ngc6543a.jpg'); % Load the image
image(rgb_img) % Display the RGB image


Calculate the monochrome luminance by combining the RGB values according to the NTSC standard, which applies coefficients related to the eye’s sensitivity to RGB colors:

I = .2989*rgb_img(:,:,1)...
	+.5870*rgb_img(:,:,2)...
	+.1140*rgb_img(:,:,3);

I is an intensity image with integer values ranging from a minimum of zero:

min(I(:))
ans =
	0

to a maximum of 255:

max(I(:))
ans =
	255

To display the image, use a grayscale colormap with 256 values. This avoids the need to scale the data-to-color mapping, which is required if you use a colormap of a different size. Use the imagesc function in cases where the colormap does not contain one entry for each data value.

Now display the image in a new figure using the gray colormap:

figure; colormap(gray(256)); image(I)

Related Information

Other colormaps with a range of colors that vary continuously from dark to light can produce usable images. For example, try colormap(summer(256)) for a classic oscilloscope look. See colormap for more choices.

The brighten function enables you to increase or decrease the color intensities in a colormap to compensate for computer display differences or to enhance the visibility of faint or bright regions of the image (at the expense of the opposite end of the range).

Summary of Image Types and Numeric Classes

This table summarizes how data matrix elements are interpreted as pixel colors, depending on the image type and data class.

Image Type double Data uint8 or uint16 Data
Indexed Image is an m-by-n array of integers in the range [1, p].

Colormap is a p-by-3 array of floating-point values in the range [0, 1].

Image is an m-by-n array of integers in the range [0, p –1].

Colormap is a p-by-3 array of floating-point values in the range [0, 1].

Intensity

Image is an m-by-n array of floating-point values that are linearly scaled to produce colormap indices. The typical range of values is [0, 1].

Colormap is a p-by-3 array of floating-point values in the range [0, 1] and is typically grayscale.

Image is an m-by-n array of integers that are linearly scaled to produce colormap indices. The typical range of values is [0, 255] or [0, 65535].

Colormap is a p-by-3 array of floating-point values in the range [0, 1] and is typically grayscale.

RGB (Truecolor) Image is an m-by-n-by-3 array of floating-point values in the range [0, 1]. Image is an m-by-n-by-3 array of integers in the range [0, 255] or [0, 65535].

The magic Function

MATLAB actually has a built-in function that creates magic squares of almost any size.
Not surprisingly, this function is named magic.

B = magic(4)
B = 
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

This matrix is almost the same as the one in the Dürer engraving and has all the same “magic” properties; the only difference is that the two middle columns are exchanged.
To make this B into Dürer’s A, swap the two middle columns.

A = B(:,[1 3 2 4])

This says “for each of the rows of matrix B, reorder the elements in the order 1, 3, 2, 4.”
It produces

A = 
    16     3     2    13
     5    10    11     8
     9     6     7    12
     4    15    14     1

Why would Dürer go to the trouble of rearranging the columns when he could have used MATLAB’s ordering? No doubt he wanted to include the date of the engraving, 1514, at the bottom of his magic square.

Matlab Image Types

Indexed Images

An indexed image consists of a data matrix, X, and a colormap matrix, map. map is an m-by-3 array of class double containing floating-point values in the range [0, 1]. Each row of map specifies the red, green, and blue components of a single color. An indexed image uses “direct mapping” of pixel values to colormap values. The color of each image pixel is determined by using the corresponding value of X as an index into map. Values of X therefore must be integers. The value 1 points to the first row in map, the value 2 points to the second row, and so on. Display an indexed image with the statements

image(X); colormap(map)

A colormap is often stored with an indexed image and is automatically loaded with the image when you use the imread function. However, you are not limited to using the default colormap—use any colormap that you choose. The description for the property CDataMapping describes how to alter the type of mapping used.

The next figure illustrates the structure of an indexed image. The pixels in the image are represented by integers, which are pointers (indices) to color values stored in the colormap.

The relationship between the values in the image matrix and the colormap depends on the class of the image matrix. If the image matrix is of class double, the value 1 points to the first row in the colormap, the value 2 points to the second row, and so on. If the image matrix is of class uint8 or uint16, there is an offset—the value 0 points to the first row in the colormap, the value 1 points to the second row, and so on. The offset is also used in graphics file formats to maximize the number of colors that can be supported. In the preceding image, the image matrix is of class double. Because there is no offset, the value 5 points to the fifth row of the colormap.

[warning]When using the painters renderer on the Windows platform, you should only use 256 colors when attempting to display an indexed image. Larger colormaps can lead to unexpected colors because the painters algorithm uses the Windows 256 color palette, which graphics drivers and graphics hardware are known to handle differently. To work around this issue, use the Zbuffer or OpenGL renderer, as appropriate. For more information regarding graphics renderers in MATLAB, see Technical Note 1201: The Technical Support Guide to Graphics Rendering and Troubleshooting.[/warning]

Intensity Images

An intensity image is a data matrix, I, whose values represent intensities within some range. An intensity image is represented as a single matrix, with each element of the matrix corresponding to one image pixel. The matrix can be of class double, uint8, or uint16. While intensity images are rarely saved with a colormap, a colormap is still used to display them. In essence, handles intensity images are treated as indexed images.

This figure depicts an intensity image of class double.

To display an intensity image, use the imagesc (“image scale”) function, which enables you to set the range of intensity values. imagesc scales the image data to use the full colormap. Use the two-input form of imagesc to display an intensity image, for example:

imagesc(I,[0 1]); colormap(gray);

The second input argument to imagesc specifies the desired intensity range. The imagesc function displays I by mapping the first value in the range (usually 0) to the first colormap entry, and the second value (usually 1) to the last colormap entry. Values in between are linearly distributed throughout the remaining colormap colors.

Although it is conventional to display intensity images using a grayscale colormap, it is possible to use other colormaps. For example, the following statements display the intensity image I in shades of blue and green:

imagesc(I,[0 1]); colormap(winter);

To display a matrix A with an arbitrary range of values as an intensity image, use the single-argument form of imagesc. With one input argument, imagesc maps the minimum value of the data matrix to the first colormap entry, and maps the maximum value to the last colormap entry. For example, these two lines are equivalent:

RGB (Truecolor) Images

imagesc(A); colormap(gray)
imagesc(A,[min(A(:)) max(A(:))]); colormap(gray)

An RGB image, sometimes referred to as a truecolor image, is stored as an m-by-n-by-3 data array that defines red, green, and blue color components for each individual pixel. RGB images do not use a palette. The color of each pixel is determined by the combination of the red, green, and blue intensities stored in each color plane at the pixel’s location. Graphics file formats store RGB images as 24-bit images, where the red, green, and blue components are 8 bits each. This yields a potential of 16 million colors. The precision with which a real-life image can be replicated has led to the nickname “truecolor image.”

An RGB MATLAB array can be of class double, uint8, or uint16. In an RGB array of class double, each color component is a value between 0 and 1. A pixel whose color components are (0,0,0) is displayed as black, and a pixel whose color components are (1,1,1) is displayed as white. The three color components for each pixel are stored along the third dimension of the data array. For example, the red, green, and blue color components of the pixel (10,5) are stored in RGB(10,5,1), RGB(10,5,2), and RGB(10,5,3), respectively.

To display the truecolor image RGB, use the image function:

image(RGB)

The next figure shows an RGB image of class double.

To determine the color of the pixel at (2,3), look at the RGB triplet stored in (2,3,1:3). Suppose (2,3,1) contains the value 0.5176, (2,3,2) contains 0.1608, and (2,3,3) contains 0.0627. The color for the pixel at (2,3) is

0.5176 0.1608 0.0627

The Colon Operator

The colon, :, is one of MATLAB’s most important operators. It occurs in several different
forms. The expression

1:10

is a row vector containing the integers from 1 to 10

1     2     3     4     5     6     7     8     9    10

To obtain nonunit spacing, specify an increment. For example,

100:-7:50

is

100    93    86    79    72    65    58    51

and

0:pi/4:pi

is

0    0.7854    1.5708    2.3562    3.1416

Subscript expressions involving colons refer to portions of a matrix.

A(1:k,j)

is the first k elements of the jth column of A. So

sum(A(1:4,4))  

computes the sum of the fourth column. But there is a better way. The colon by itself
refers to all the elements in a row or column of a matrix and the keyword end refers to
the last row or column. So

sum(A(:,end))

computes the sum of the elements in the last column of A.

ans =
     34

Why is the magic sum for a 4-by-4 square equal to 34? If the integers from 1 to 16 are
sorted into four groups with equal sums, that sum must be

sum(1:16)/4

which, of course, is

ans =
     34

Subscripts

The element in row i and column j of A is denoted by A(i,j). For example, A(4,2) is the number in the fourth row and second column. For our magic square, A(4,2) is 15. So it is possible to compute the sum of the elements in the fourth column of A by typing

A(1,4) + A(2,4) + A(3,4) + A(4,4)

This produces

ans =
     34

but is not the most elegant way of summing a single column.

It is also possible to refer to the elements of a matrix with a single subscript, A(k). This is the usual way of referencing row and column vectors. But it can also apply to a fully two-dimensional matrix, in which case the array is regarded as one long column vector formed from the columns of the original matrix. So, for our magic square, A(8) is another way of referring to the value 15 stored in A(4,2).

If you try to use the value of an element outside of the matrix, it is an error.

t = A(4,5)

Index exceeds matrix dimensions.
On the other hand, if you store a value in an element outside of the matrix, the size increases to accommodate the newcomer.

X = A;
X(4,5) = 17
X =
    16     3     2    13     0
     5    10    11     8     0
     9     6     7    12     0
     4    15    14     1    17

Working with Images in MATLAB Graphics

What Is Image Data?

The basic MATLAB data structure is the array, an ordered set of real or complex elements. An array is naturally suited to the representation of images, real-valued, ordered sets of color or intensity data. (An array is suited for complex-valued images.)

In the MATLAB workspace, most images are represented as two-dimensional arrays (matrices), in which each element of the matrix corresponds to a single pixel in the displayed image. For example, an image composed of 200 rows and 300 columns of different colored dots stored as a 200-by-300 matrix. Some images, such as RGB, require a three-dimensional array, where the first plane in the third dimension represents the red pixel intensities, the second plane represents the green pixel intensities, and the third plane represents the blue pixel intensities.

This convention makes working with graphics file format images similar to working with any other type of matrix data. For example, you can select a single pixel from an image matrix using normal matrix subscripting:

I(2,15)

This command returns the value of the pixel at row 2, column 15 of the image I.

The following sections describe the different data and image types, and give details about how to read, write, work with, and display graphics images; how to alter the display properties and aspect ratio of an image during display; how to print an image; and how to convert the data type or graphics format of an image.

Data Types

MATLAB math supports three different numeric classes for image display:

  • double-precision floating-point (double)
  • 16-bit unsigned integer (uint16)
  • 8-bit unsigned integer (uint8)

The image display commands interpret data values differently depending on the numeric class the data is stored in. Working with 8-Bit and 16-Bit Images includes details on the inner workings of the storage for 8- and 16-bit images.

By default, most data occupy arrays of class double. The data in these arrays is stored as double-precision (64-bit) floating-point numbers. All MATLAB functions and capabilities work with these arrays.

For images stored in one of the graphics file formats supported by MATLAB functions, however, this data representation is not always ideal. The number of pixels in such an image can be very large; for example, a 1000-by-1000 image has a million pixels. Since at least one array element represents each pixel , this image requires about 8 megabytes of memory if it is stored as class double.

To reduce memory requirements, you can store image data in arrays of class uint8 and uint16. The data in these arrays is stored as 8-bit or 16-bit unsigned integers. These arrays require one-eighth or one-fourth as much memory as data in double arrays.

Bit Depth

MATLAB input functions read the most commonly used bit depths (bits per pixel) of any of the supported graphics file formats. When the data is in memory, it can be stored as uint8, uint16, or double. For details on which bit depths are appropriate for each supported format, see imread and imwrite.

Supported Image Formats

MATLAB commands read, write, and display several types of graphics file formats for images. As with MATLAB generated images, once a graphics file format image is displayed, it becomes a Handle Graphics image object. MATLAB supports the following graphics file formats, along with others:

  • BMP (Microsoft Windows Bitmap)
  • GIF (Graphics Interchange Files)
  • HDF (Hierarchical Data Format)
  • JPEG (Joint Photographic Experts Group)
  • PCX (Paintbrush)
  • PNG (Portable Network Graphics)
  • TIFF (Tagged Image File Format)
  • XWD (X Window Dump)

For more information about the bit depths and image types supported for these formats, see imread and imwrite.

Functions for Reading, Writing, and Displaying Images

Images are essentially two-dimensional matrices, so many MATLAB functions can operate on and display images. The following table lists the most useful ones. The sections that follow describe these functions in more detail.

Function Purpose Function Group
axis Plot axis scaling and appearance. Display
image Display image (create image object). Display
imagesc Scale data and display as image. Display
imread Read image from graphics file. File I/O
imwrite Write image to graphics file. File I/O
imfinfo Get image information from graphics file. Utility
ind2rgb Convert indexed image to RGB image. Utility

Stream Line Plots of Vector Data

Wind Mapping Data

The MATLAB vector data set called wind represents air currents over North America. This example uses a combination of techniques:

  • Stream lines to trace the wind velocity
  • Slice planes to show cross-sectional views of the data
  • Contours on the slice planes to improve the visibility of slice-plane coloring
  • 1. Determine the Range of the Coordinates

Load the data and determine minimum and maximum values to locate the slice planes and contour plots (load, min, max).

2. Add Slice Planes for Visual Context

load wind
xmin = min(x(:));
xmax = max(x(:));
ymax = max(y(:));
zmin = min(z(:));

Calculate the magnitude of the vector field (which represents wind speed) to generate scalar data for the slice command. Create slice planes along the x-axis at xmin, 100, and xmax, along the y-axis at ymax, and along the z-axis at zmin. Specify interpolated face coloring so the slice coloring indicates wind speed, and do not draw edges (sqrt, slice, FaceColor, EdgeColor).

3. Add Contour Lines to the Slice Planes

wind_speed = sqrt(u.^2 + v.^2 + w.^2);
hsurfaces = slice(x,y,z,wind_speed,[xmin,100,xmax],ymax,zmin);
set(hsurfaces,'FaceColor','interp','EdgeColor','none')

Draw light gray contour lines on the slice planes to help quantify the color mapping (contourslice, EdgeColor, LineWidth).

4. Define the Starting Points for the Stream Lines

hcont = ...
contourslice(x,y,z,wind_speed,[xmin,100,xmax],ymax,zmin);
set(hcont,'EdgeColor',[.7,.7,.7],'LineWidth',.5)

In this example, all stream lines start at an x-axis value of 80 and span the range 20 to 50 in the y-direction and 0 to 15 in the z-direction. Save the handles of the stream lines and set the line width and color (meshgrid, streamline, LineWidth, Color).

5. Define the View

[sx,sy,sz] = meshgrid(80,20:10:50,0:5:15);
hlines = streamline(x,y,z,u,v,w,sx,sy,sz);
set(hlines,'LineWidth',2,'Color','r')

Set up the view, expanding the z-axis to make it easier to read the graph (view, daspect, axis).

view(3)
daspect([2,2,1])
axis tight

[tip]See coneplot for an example of the same data plotted with cones.[/tip]

Displaying Curl with Stream Ribbons

What Stream Ribbons Can Show

Stream ribbons illustrate direction of flow, similar to stream lines, but can also show rotation about the flow axis by twisting the ribbon-shaped flow line. The streamribbon function enables you to specify a twist angle (in radians) for each vertex in the stream ribbons.

When used in conjunction with the curl function, streamribbon is useful for displaying the curl angular velocity of a vector field. The following example illustrates this technique.

1. Select a Subset of Data to Plot

Load and select a region of interest in the wind data set using subvolume. Plotting the full data set first can help you select a region of interest.

2. Calculate Curl Angular Velocity and Wind Speed

load wind
lims = [100.64 116.67 17.25 28.75 -0.02 6.86];
[x,y,z,u,v,w] = subvolume(x,y,z,u,v,w,lims);

Calculate the curl angular velocity and the wind speed.

3. Create the Stream Ribbons

cav = curl(x,y,z,u,v,w);
wind_speed = sqrt(u.^2 + v.^2 + w.^2);
  • Use meshgrid to create arrays of starting points for the stream ribbons. See Specifying Starting Points for Stream Plotsfor information on specifying the arrays of starting points.
  • stream3 calculates the stream line vertices with a step size of .5.
  • streamribbon scales the width of the ribbon by a factor of 2 to enhance the visibility of the twisting (which indicates curl angular velocity).

streamribbon returns the handles of the surface objects it creates, which are then used to set the color to red (FaceColor), the color of the surface edges to light gray (EdgeColor), and slightly increase the brightness of the ambient light reflected when lighting is applied (AmbientStrength).

4. Define the View and Add Lighting

[sx sy sz] = meshgrid(110,20:5:30,1:5);
verts = stream3(x,y,z,u,v,w,sx,sy,sz,.5);
h = streamribbon(verts,x,y,z,cav,wind_speed,2);
set(h,'FaceColor','r',...
	'EdgeColor',[.7 .7 .7],...
	'AmbientStrength',.6)
  • The volumebounds command provides a convenient way to set axis and color limits.
  • Add a grid and set the view for 3-D (streamribbon does not change the current view).

camlight creates a light positioned to the right of the viewplsoint and lighting sets the lighting method to Phong (which requires the Z-buffer renderer).

axis(volumebounds(x,y,z,wind_speed))
grid on
view(3)
camlight right; 
set(gcf,'Renderer','zbuffer'); lighting phong

Matlab GUIDE: Getting Started

GUI Layout

GUIDE, the MATLAB graphical user interface development environment, provides a set of tools for creating graphical user interfaces (GUIs). These tools simplify the process of laying out and programming GUIs.

Using the GUIDE Layout Editor, you can populate a GUI by clicking and dragging GUI components—such as axes, panels, buttons, text fields, sliders, and so on—into the layout area. You also can create menus and context menus for the GUI. From the Layout Editor, you can size the GUI, modify component look and feel, align components, set tab order, view a hierarchical list of the component objects, and set GUI options.

GUI Programming

GUIDE automatically generates a program file containing MATLAB functions that controls how the GUI operates. This code file provides code to initialize the GUI and contains a framework for the GUI callbacks—the routines that execute when a user interacts with a GUI component. Use the MATLAB Editor to add code to the callbacks to perform the actions you want the GUI to perform.

[warning]MATLAB software provides a selection of standard dialog boxes that you can create with a single function call. For information about these dialog boxes and the functions used to create them, see Predefined Dialog Boxes in the GUI Development section of the MATLAB Function Reference documentation.[/warning]

A GUI to Set Simulink Model Parameters Example 2

Running the Simulation from the GUI

The GUI Simulate and store results button callback runs the model simulation and stores the results in the handles structure. Storing data in the handles structure simplifies the process of passing data to other subfunction since this structure can be passed as an argument.

When a user clicks the Simulate and store results button, the callback executes the following steps:

  • Calls sim, which runs the simulation and returns the data that is used for plotting.
  • Creates a structure to save the results of the simulation, the current values of the simulation parameters set by the GUI, and the run name and number.
  • Stores the structure in the handles structure.
  • Updates the list box String to list the most recent run.

Here is the Simulate and store results button callback:

function SimulateButton_Callback(hObject, eventdata, handles)
[timeVector,stateVector,outputVector] = sim('f14');
% Retrieve old results data structure
if isfield(handles,'ResultsData') & 
~isempty(handles.ResultsData)
	ResultsData = handles.ResultsData;
	% Determine the maximum run number currently used.
	maxNum = ResultsData(length(ResultsData)).RunNumber;
	ResultNum = maxNum+1;
else % Set up the results data structure
	ResultsData = struct('RunName',[],'RunNumber',[],...
	              'KiValue',[],'KfValue',[],'timeVector',[],...
	              'outputVector',[]);
	ResultNum = 1;
end
if isequal(ResultNum,1),
	% Enable the Plot and Remove buttons
	set([handles.RemoveButton,handles.PlotButton],'Enable','on')
end
% Get Ki and Kf values to store with the data and put in the 
results list.
Ki = get(handles.KiValueSlider,'Value');
Kf = get(handles.KfValueSlider,'Value');
ResultsData(ResultNum).RunName = ['Run',num2str(ResultNum)];
ResultsData(ResultNum).RunNumber = ResultNum;
ResultsData(ResultNum).KiValue = Ki;
ResultsData(ResultNum).KfValue = Kf;
ResultsData(ResultNum).timeVector = timeVector;
ResultsData(ResultNum).outputVector = outputVector;
% Build the new results list string for the listbox
ResultsStr = get(handles.ResultsList,'String');
if isequal(ResultNum,1)
	ResultsStr = {['Run1',num2str(Kf),' ',num2str(Ki)]};
else
	ResultsStr = [ResultsStr;...
	{['Run',num2str(ResultNum),' ',num2str(Kf),' ', ...
	num2str(Ki)]}];
end
set(handles.ResultsList,'String',ResultsStr);
% Store the new ResultsData
handles.ResultsData = ResultsData;
guidata(hObject, handles)

Removing Results from the List Box

The GUI Remove button callback deletes any selected item from the Results list list box. It also deletes the corresponding run data from the handles structure. When a user clicks the Remove button, the callback executes the following steps:

  • Determines which list box items are selected when a user clicks the Remove button and removes those items from the list box String property by setting each item to the empty matrix [].
  • Removes the deleted data from the handles structure.
  • Displays the string and disables the Remove and Plot buttons (using the Enable property), if all the items in the list box are removed.
  • Save the changes to the handles structure (guidata).

Here is the Remove button callback:

function RemoveButton_Callback(hObject, eventdata, handles)
currentVal = get(handles.ResultsList,'Value');
resultsStr = get(handles.ResultsList,'String');
numResults = size(resultsStr,1);
% Remove the data and list entry for the selected value
resultsStr(currentVal) =[];
handles.ResultsData(currentVal)=[];
% If there are no other entries, disable the Remove and Plot 
button
% and change the list string to 
if isequal(numResults,length(currentVal)),
	resultsStr = {''};
	currentVal = 1;
	
set([handles.RemoveButton,handles.PlotButton],'Enable','off')	
end
% Ensure that list box Value is valid, then reset Value and String
currentVal = min(currentVal,size(resultsStr,1));
set(handles.ResultsList,'Value',currentVal,'String',resultsStr)
% Store the new ResultsData
guidata(hObject, handles)

Plotting the Results Data

The GUI Plot button callback creates a plot of the run data and adds a legend. The data to plot is passed to the callback in the handles structure, which also contains the gain settings used when the simulation ran. When a user clicks the Plot button, the callback executes the following steps:

  • Collects the data for each run selected in the Results list, including two variables (time vector and output vector) and a color for each result run to plot.
  • Generates a string for the legend from the stored data.
  • Creates the figure and axes for plotting and saves the handles for use by the Close button callback.
  • Plots the data, adds a legend, and makes the figure visible.

The figure that contains the plot is created as invisible and then made visible after adding the plot and legend. To prevent this figure from becoming the target for plotting commands issued at the command line or by other GUIs, its HandleVisibility and IntegerHandle properties are set to off. This means the figure is also hidden from the plot and legend commands.

Use the following steps to plot into a hidden figure:

  • Save the handle of the figure when you create it.
  • Create an axes, set its Parent property to the figure handle, and save the axes handle.
  • Create the plot (which is one or more line objects), save these line handles, and set their Parent properties to the handle of the axes.
  • Make the figure visible.

Plot Button Callback Listing

Here is the Plot button callback.

function PlotButton_Callback(hObject, eventdata, handles)
currentVal = get(handles.ResultsList,'Value');
% Get data to plot and generate command string with color 
% specified
legendStr = cell(length(currentVal),1);
plotColor = {'b','g','r','c','m','y','k'};
for ctVal = 1:length(currentVal);
	PlotData{(ctVal*3)-2} = 
handles.ResultsData(currentVal(ctVal)).timeVector;
	PlotData{(ctVal*3)-1} = 
handles.ResultsData(currentVal(ctVal)).outputVector;	
	numColor = ctVal - 7*( floor((ctVal-1)/7) );
	PlotData{ctVal*3} = plotColor{numColor};
	legendStr{ctVal} = ...
      [handles.ResultsData(currentVal(ctVal)).RunName,'; Kf=',...
      num2str(handles.ResultsData(currentVal(ctVal)).KfValue),...
      ';  Ki=', ...
      num2str(handles.ResultsData(currentVal(ctVal)).KiValue)];
end
% If necessary, create the plot figure and store in handles
% structure
if ~isfield(handles,'PlotFigure') ||...
   ~ishandle(handles.PlotFigure),
	handles.PlotFigure = ...
        figure('Name','F14 Simulation Output',...
        'Visible','off','NumberTitle','off',...
        'HandleVisibility','off','IntegerHandle','off');
	handles.PlotAxes = axes('Parent',handles.PlotFigure);
	guidata(hObject, handles)
end
% Plot data
pHandles = plot(PlotData{:},'Parent',handles.PlotAxes);
% Add a legend, and bring figure to the front
legend(pHandles(1:2:end),legendStr{:})
% Make the figure visible and bring it forward
figure(handles.PlotFigure)

The GUI Help Button

The GUI Help button callback displays an HTML file in the MATLAB Help browser. It uses two commands:

  • The which command returns the full path to the file when it is on the MATLAB path
  • The web command displays the file in the Help browser.

This is the Help button callback.

function HelpButton_Callback(hObject, eventdata, handles)
HelpPath = which('f14ex_help.html');
web(HelpPath); 

You can also display the help document in a Web browser or load an external URL. For a description of these options, see the documentation for web.

Closing the GUI

The GUI Close button callback closes the plot figure, if one exists and then closes the GUI. The handle of the plot figure and the GUI figure are available from the handles structure. The callback executes two steps:

  • Checks to see if there is a PlotFigure field in the handles structure and if it contains a valid figure handle (the user could have closed the figure manually).
  • Closes the GUI figure.

This is the Close button callback:

function CloseButton_Callback(hObject, eventdata, handles)
% Close the GUI and any plot window that is open
if isfield(handles,'PlotFigure') && ...
      ishandle(handles.PlotFigure),
   close(handles.PlotFigure);
end
close(handles.F14ControllerEditor); 

The List Box Callback and Create Function

This GUI does not use the list box callback because the actions performed on list box items are carried out by push buttons (Simulate and store results, Remove, and Plot). GUIDE automatically inserts a callback stub when you add the list box and automatically sets the Callback property to execute this subfunction whenever the callback is triggered (which happens when users select an item in the list box).

In this example, there is no need for the list box callback to execute. You can delete it from the GUI code file and at the same time also delete the Callback property string in the Property Inspector so that the software does not attempt to execute the callback.

[important]For more information on how to trigger the list box callback, see the description of list box.[/important]

Setting the Background to White

The list box create function enables you to determine the background color of the list box. The following code shows the create function for the list box that is tagged ResultsList:

function ResultsList_CreateFcn(hObject, eventdata, handles)
% Hint: listbox controls usually have a white background, change
%       'usewhitebg' to 0 to use default. See ISPC and COMPUTER.
usewhitebg = 1;
if usewhitebg
    set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',...
    get(0,'defaultUicontrolBackgroundColor'));
end

A GUI to Set Simulink Model Parameters

About the Simulink Model Parameters Example

This example illustrates how to create a GUI that sets the parameters of a Simulink® model. In addition, the GUI can run the simulation and plot the results in a figure window. The following figure shows the GUI after running three simulations with different values for controller gains.

The example illustrates a number of GUI building techniques:

  • Opening and setting parameters on a Simulink model from a GUI.
  • Implementing sliders that operate in conjunction with text boxes, which display the current value, as well as accepting user input.
  • Enabling and disabling controls, depending on the state of the GUI.
  • Managing a variety of shared data using the handles structure.
  • Directing graphics output to figures with hidden handles.
  • Adding a Help button that displays .html files in the MATLAB Help browser.

View and Run the Simulink Parameters GUI

If you are reading this document in the MATLAB Help browser, you can access the example FIG-file and code file by clicking the following links. If you are reading this on the Web or in PDF form, go to the corresponding section in the MATLAB Help Browser to use the links.

If you intend to modify the layout or code of this GUI example, first save a copy of its code file and FIG-file to your current folder (you need write access to your current folder to do this). Follow these steps to copy the example files to your current folder and then to open them:

  • Click here to copy the files to your current folder.
  • Type guide f14ex or click here to open the FIG-file in GUIDE.
  • Type edit f14ex or click here to open the code file in the Editor.

You can view the properties of any component by double-clicking it in the Layout Editor to open the Property Inspector for it. You can modify either the figure, the code, or both, and then save the GUI in your current folder using File > Save as from GUIDE. This saves both files, allowing you to rename them, if you choose.

To just inspect the GUI in GUIDE and run it, follow these steps instead:

  • Click here to add the example files to the MATLAB path (only for the current session).
  • Click here to run the f14ex GUI.
  • Click here to display the GUI in the GUIDE Layout Editor (read only).
  • Click here to display the GUI code file in the MATLAB Editor (read only).

[warning]Do not save GUI files to the examples folder where you found them or you will overwrite the original files. If you want to save GUI files, use File > Save as from GUIDE, which saves both the GUI FIG-file and the GUI code file.[/warning]

How to Use the Simulink Parameters GUI

[warning]You must have Simulink installed for this GUI to run. The first time you run the GUI, Simulink opens (if it is not already running) and loads the f14 demo model. This can take several seconds.[/warning]

The GUI has a Help button. Clicking it opens an HTML file, f14ex_help.html, in the Help Browser. This file, which resides in the examples folder along with the GUI files, contains the following five sections of help text:

F14 Controller Gain Editor

You can use the F14 Controller Gain Editor to analyze how changing the gains used in the Proportional-Integral Controller affect the aircraft’s angle of attack and the amount of G force the pilot feels.

[warning]That the Simulink diagram f14.mdl must be open to run this GUI. If you close the F14 Simulink model, the GUI reopens it whenever it requires the model to execute.[/warning]

Changing the Controller Gains

You can change gains in two blocks:

  • The Proportional gain (Kf) in the Gain block
  • The Integral gain (Ki) in the Transfer Function block

You can change either of the gains in one of the two ways:

  • Move the slider associated with that gain.
  • Type a new value into the Current value edit field associated with that gain.

The block’s values are updated as soon as you enter the new value in the GUI.

Running the Simulation

Once you have set the gain values, you can run the simulation by clicking the Simulate and store results button. The simulation time and output vectors are stored in the Results list.

Plotting the Results

You can generate a plot of one or more simulation results by selecting the row of results (Run1, Run2, etc.) in the Results list that you want to plot and clicking the Plot button. If you select multiple rows, the graph contains a plot of each result.

The graph is displayed in a figure, which is cleared each time you click the Plot button. The figure’s handle is hidden so that only the GUI can display graphs in this window.

Removing Results

To remove a result from the Results list, select the row or rows you want to remove and click the Remove button.

Running the GUI

The GUI is nonblocking and nonmodal because it is designed to be used as an analysis tool.

GUI Options Settings

This GUI uses the following GUI option settings:

  • Resize behavior: Non-resizable
  • Command-line accessibility: Off

GUI Options selected:

  • Generate callback function prototypes
  • GUI allows only one instance to run

Opening the Simulink Block Diagrams

This example is designed to work with the f14 Simulink model. Because the GUI sets parameters and runs the simulation, the f14 model must be open when the GUI is displayed. When the GUI runs, the model_open subfunction executes. The purpose of the subfunction is to:

  • Determine if the model is open (find_system).
  • Open the block diagram for the model and the subsystem where the parameters are being set, if not open already (open_system).
  • Change the size of the controller Gain block so it can display the gain value (set_param).
  • Bring the GUI forward so it is displayed on top of the Simulink diagrams (figure).
  • Set the block parameters to match the current settings in the GUI.

Here is the code for the model_open subfunction:

function model_open(handles)
if  isempty(find_system('Name','f14')),
	open_system('f14'); open_system('f14/Controller')
	set_param('f14/Controller/Gain','Position',[275 14 340 56])
	figure(handles.F14ControllerEditor)
	set_param('f14/Controller Gain','Gain',...
		get(handles.KfCurrentValue,'String'))
	set_param(...
      'f14/Controller/Proportional plus integral compensator',...
      'Numerator',...
      get(handles.KiCurrentValue,'String'))
end

Programming the Slider and Edit Text Components

In the GUI, each slider is coupled to an edit text component so that:

  • The edit text displays the current value of the slider.
  • The user can enter a value into the edit text box and cause the slider to update to that value.
  • Both components update the appropriate model parameters when activated by the user.

Slider Callback

The GUI uses two sliders to specify block gains because these components enable the selection of continuous values within a specified range. When a user changes the slider value, the callback executes the following steps:

  • Calls model_open to ensure that the Simulink model is open so that simulation parameters can be set.
  • Gets the new slider value.
  • Sets the value of the Current value edit text component to match the slider.
  • Sets the appropriate block parameter to the new value (set_param).

Here is the callback for the Proportional (Kf) slider:

function KfValueSlider_Callback(hObject, eventdata, handles)
% Ensure model is open.
model_open(handles)
% Get the new value for the Kf Gain from the slider.
NewVal = get(hObject, 'Value');
% Set the value of the KfCurrentValue to the new value 
% set by slider.
set(handles.KfCurrentValue,'String',NewVal)
% Set the Gain parameter of the Kf Gain Block to the new value.
set_param('f14/Controller/Gain','Gain',num2str(NewVal))

While a slider returns a number and the edit text requires a string, uicontrols automatically convert the values to the correct type.

The callback for the Integral (Ki) slider follows an approach similar to the Proportional (Kf) slider’s callback.

Current Value Edit Text Callback

The edit text box enables users to enter a value for the respective parameter. When the user clicks another component in the GUI after entering data into the text box, the edit text callback executes the following steps:

  • Calls model_open to ensure that the Simulink model is open so that it can set simulation parameters.
  • Converts the string returned by the edit box String property to a double (str2double).

Checks whether the value entered by the user is within the range of the slider:

If the value is out of range, the edit text String property is set to the value of the slider (rejecting the number entered by the user).

If the value is in range, the slider Value property is updated to the new value.

  • Sets the appropriate block parameter to the new value (set_param).

Here is the callback for the Kf Current value text box:

function KfCurrentValue_Callback(hObject, eventdata, handles)
% Ensure model is open.
model_open(handles)
% Get the new value for the Kf Gain.
NewStrVal = get(hObject, 'String');
NewVal = str2double(NewStrVal);
% Check that the entered value falls within the allowable range.
if  isempty(NewVal) || (NewVal< -5) || (NewVal>0),
   % Revert to last value, as indicated by KfValueSlider.
   OldVal = get(handles.KfValueSlider,'Value');
   set(hObject, 'String',OldVal)
else % Use new Kf value
   % Set the value of the KfValueSlider to the new value.
   set(handles.KfValueSlider,'Value',NewVal)
   % Set the Gain parameter of the Kf Gain Block 
   % to the new value.
   set_param('f14/Controller/Gain','Gain',NewStrVal)
end

The callback for the Ki Current value follows a similar approach.

Matlab Using FFT

This demonstration uses the FFT function to analyze the variations in sunspot activity over the last 300 years.

Sunspot activity is cyclical, reaching a maximum about every 11 years. Let’s confirm that. Here is a plot of a quantity called the Zurich sunspot relative number, which measures both number and size of sunspots. Astronomers have tabulated this number for almost 300 years.

load sunspot.dat
year=sunspot(:,1);
relNums=sunspot(:,2);
plot(year,relNums)
title('Sunspot Data')


Here is a closer look at the first 50 years.

plot(year(1:50),relNums(1:50),'b.-');


The fundamental tool of signal processing is the FFT, or fast Finite Fourier Transform. To take the FFT of the sunspot data type the following.

The first component of Y, Y(1), is simply the sum of the data, and can be removed.

Y = fft(relNums);
Y(1)=[];

A graph of the distribution of the Fourier coefficients (given by Y) in the complex plane is pretty, but difficult to interpret. We need a more useful way of examining the data in Y.

plot(Y,'ro')
title('Fourier Coefficients in the Complex Plane');
xlabel('Real Axis');
ylabel('Imaginary Axis');


The complex magnitude squared of Y is called the power, and a plot of power versus frequency is a “periodogram”.

n=length(Y);
power = abs(Y(1:floor(n/2))).^2;
nyquist = 1/2;
freq = (1:n/2)/(n/2)*nyquist;
plot(freq,power)
xlabel('cycles/year')
title('Periodogram')


The scale in cycles/year is somewhat inconvenient. We can plot in years/cycle and estimate the length of one cycle.

plot(freq(1:40),power(1:40))
xlabel('cycles/year')


Now we plot power versus period for convenience (where period=1./freq). As expected, there is a very prominent cycle with a length of about 11 years.

period=1./freq;
plot(period,power);
axis([0 40 0 2e+7]);
ylabel('Power');
xlabel('Period (Years/Cycle)');


Finally, we can fix the cycle length a little more precisely by picking out the strongest frequency. The red dot locates this point.

hold on;
index=find(power==max(power));
mainPeriodStr=num2str(period(index));
plot(period(index),power(index),'r.', 'MarkerSize',25);
text(period(index)+2,power(index),['Period = ',mainPeriodStr]);
hold off;

Using .NET from MATLAB

What Is the Microsoft .NET Framework?

The Microsoft .NET Framework is an integral Windows component that provides a large body of precoded solutions to common program requirements, and manages the execution of programs written specifically for the Framework.

MATLAB software supports the .NET Framework on the Windows platform only.

Benefits of the MATLAB .NET Interface

The MATLAB .NET interface enables you to:

  • Create instances of .NET classes.
  • Interact with .NET applications via their class members.
  • Why Use the MATLAB .NET Interface?

Use the MATLAB .NET interface to take advantage of the capabilities of the Microsoft .NET Framework. For example:

  • You have a professionally developed .NET assembly and want to use it to do certain operations, such as access hardware.
  • You want to leverage the capabilities of programming in .NET (for example, you have existing C# programs).
  • You want to access existing Microsoft-supplied classes for .NET.
  • Limitations to .NET Support

MATLAB supports the .NET features C# supports, except for the limits noted in the following table.

What’s the Difference Between the MATLAB .NET Interface and MATLAB Builder NE?

The MATLAB .NET interface is for MATLAB users who want to use .NET assemblies in MATLAB.

MATLAB® Builder™ NE (previously called .NET Builder) packages MATLAB functions so that .NET programmers can access them. It brings MATLAB into .NET applications. For more information about this product, follow the instructions for accessing Product Documentation at the MathWorks Web Site in the MATLAB Desktop Tools and Development Environment documentation.

Requirements

The MATLAB interface to .NET is available on the Windows platform only.

You must have the Microsoft .NET Framework installed on your system. The MATLAB interface supports the features of the .NET Framework Version 2.0, and works with Version 2.0 or above.

To use a .NET application, refer to your product documentation for information about how to install the program and for details about its functionality.

Using a .NET assembly in MATLAB

For an example of using .NET in MATLAB, see:

  • Getting Started with .NET

For detailed information, see:

  • Loading .NET Assemblies into MATLAB
  • Using a .NET Object
  • To Learn More About the .NET Framework

For a complete description of the .NET Framework, you need to consult outside resources.

[important]One source of information is the Microsoft Developer Network at http://msdn.microsoft.com/en-us/default.aspx. You can explore the .NET Framework Development Center or search the MSDN® site for the term “.NET Framework”. The .NET Framework Class Library is a programming reference manual. Many examples in this documentation refer to classes in this library. There are different versions of the .NET Framework documentation. See Requirements for information about version support in MATLAB.[/important]

Displaying Graphics Images

Image Types and Display Methods

To display a graphics file image, use either image or imagesc. For example, assuming RGB is an image,

figure('Position',[100 100 size(RGB,2) size(RGB,1)]);
image(RGB); set(gca,'Position',[0 0 1 1])


[warning]This image was created with the support of the Space Telescope Science Institute, operated by the Association of Universities for Research in Astronomy, Inc., from NASA contract NAs5-26555, and is reproduced with permission from AURA/STScI. Digital renditions of images produced by AURA/STScI are obtainable royalty-free. Credits: J.P. Harrington and K.J. Orkowski (University of Maryland), and NASA.)[/warning]

This table summarizes display methods for the three types of images.

Image Type Display Commands Uses Colormap Colors
Indexed image(X); colormap(map) Yes
Intensity imagesc(I,[0 1]); colormap(gray) Yes
RGB (truecolor) image(RGB) No

Controlling Aspect Ratio and Display Size

The image function displays the image in a default-sized figure and axes. The image stretches or shrinks to fit the display area. Sometimes you want the aspect ratio of the display to match the aspect ratio of the image data matrix. The easiest way to do this is with the axis image command.

For example, these commands display the earth image in the demos folder using the default figure and axes positions:

load earth
image(X); colormap(map)


The elongated globe results from stretching the image display to fit the axes position. Use the axis image command to force the aspect ratio to be one-to-one.

axis image


The axis image command works by setting the DataAspectRatio property of the axes object to [1 1 1]. See axis and axes for more information on how to control the appearance of axes objects.

Sometimes you want to display an image so that each element in the data matrix corresponds to a single screen pixel. To display an image with this one-to-one matrix-element-to-screen-pixel mapping, you need to resize the figure and axes. For example, these commands display the earth image so that one data element corresponds to one screen pixel:

[m,n] = size(X);
figure('Units','pixels','Position',[100 100 n m])
image(X); colormap(map)
set(gca,'Position',[0 0 1 1])

The figure’s Position property is a four-element vector that specifies the figure’s location on the screen as well as its size. The figure command positions the figure so that its lower left corner is at position (100,100) on the screen and so that its width and height match the image width and height. Setting the axes position to [0 0 1 1] in normalized units creates an axes that fills the figure. The resulting picture is shown.

Reading, Writing, and Querying Graphics Image Files

Working with Image Formats

In its native form, a graphics file format image is not stored as a MATLAB matrix, or even necessarily as a matrix. Most graphics files begin with a header containing format-specific information tags, and continue with bitmap data that can be read as a continuous stream. For this reason, you cannot use the standard MATLAB I/O commands load and save to read and write a graphics file format image.

Call special MATLAB functions to read and write image data from graphics file formats:

  • To read a graphics file format image use imread.
  • To write a graphics file format image, use imwrite.
  • To obtain information about the nature of a graphics file format image, use imfinfo.

This table gives a clearer picture of which MATLAB commands should be used with which image types.

Procedure Functions to Use
Load or save a matrix as a MAT-file. load

save

Load or save graphics file format image, e.g., BMP, TIFF. imwrite

imread

Display any image loaded into the MATLAB workspace. image

imagesc

Utilities imfinfo

ind2rgb

Reading a Graphics Image

The imread function reads an image from any supported graphics image file in any of the supported bit depths. Most of the images that you read are 8-bit. When these are read into memory, they are stored as class uint8. The main exception to this rule is MATLAB support for 16-bit data for PNG and TIFF images; if you read a 16-bit PNG or TIFF image, it is stored as class uint16.

Note For indexed images, imread always reads the colormap into an array of class double, even though the image array itself can be of class uint8 or uint16.

[warning]For indexed images, imread always reads the colormap into an array of class double, even though the image array itself can be of class uint8 or uint16.[/warning]

The following commands read the image ngc6543a.jpg into the workspace variable RGB and then displays the image using the image function:

RGB = imread('ngc6543a.jpg');
image(RGB)

You can write (save) image data using the imwrite function. The statements

load clown % An image that is included with MATLAB
imwrite(X,map,'clown.bmp')

create a BMP file containing the clown image.

Writing a Graphics Image

When you save an image using imwrite, the default behavior is to automatically reduce the bit depth to uint8. Many of the images used in MATLAB are 8-bit, and most graphics file format images do not require double-precision data. One exception to the rule for saving the image data as uint8 is that PNG and TIFF images can be saved as uint16. Because these two formats support 16-bit data, you can override the MATLAB default behavior by specifying uint16 as the data type for imwrite. The following example shows writing a 16-bit PNG file using imwrite.

Subsetting a Graphics Image (Cropping)

imwrite(I,'clown.png','BitDepth',16);

Sometimes you want to work with only a portion of an image file or you want to break it up into subsections. Specify the pixel coordinates of the rectangular subsection you want to work with and save it to a file from the command line. If you do not know the coordinates of the corner points of the subsection, choose them interactively, as the following example shows:

% Read demo RGB image from graphics file.
im = imread('street2.jpg'); 

% Display image with true aspect ratio
image(im); axis image

% Use ginput to select corner points of a rectangular
% region by pointing and clicking the mouse twice
p = ginput(2); 

% Get the x and y corner coordinates as integers
sp(1) = min(floor(p(1)), floor(p(2))); %xmin
sp(2) = min(floor(p(3)), floor(p(4))); %ymin
sp(3) = max(ceil(p(1)), ceil(p(2)));   %xmax
sp(4) = max(ceil(p(3)), ceil(p(4)));   %ymax

% Index into the original image to create the new image
MM = im(sp(2):sp(4), sp(1): sp(3),:);

% Display the subsetted image with appropriate axis ratio
figure; image(MM); axis image

% Write image to graphics file.
imwrite(MM,'street2_cropped.tif')

If you know what the image corner coordinates should be, you can manually define sp in the preceding example rather than using ginput.

You can also display a “rubber band box” as you interact with the image to subset it. See the code example for rbbox for details. For further information, see the documentation for the ginput and image functions.

Obtaining Information About Graphics Files

The imfinfo function enables you to obtain information about graphics files in any of the standard formats listed earlier. The information you obtain depends on the type of file, but it always includes at least the following:

  • Name of the file, including the folder path if the file is not in the current folder
  • File format
  • Version number of the file format
  • File modification date
  • File size in bytes
  • Image width in pixels
  • Image height in pixels
  • Number of bits per pixel
  • Image type: RGB (truecolor), intensity (grayscale), or indexed

Matlab Annotation Objects and Example

Users typically create annotation objects from the Plot Edit toolbar or the Insert menu (select Plot Edit in the View menu to display the Plot Edit toolbar). However, you can also create annotation objects using the annotation function.

Annotation objects are created in a hidden axes that extends the full width and height of the figure. This lets you specify the locations of annotation objects anywhere in the figure using normalized coordinates (the lower-left corner is the point 0,0, the upper-right corner is the point 1,1).

Annotation Object Properties

[warning]Don’t change any of the properties of the annotation axes or parent any graphics objects to this axes. Use the annotation function or the graphics tools to create annotation objects.[/warning]

The following links access descriptions of the properties you can set on the respective annotation objects:

  • Annotation arrow properties
  • Annotation doublearrow properties
  • Annotation ellipse properties
  • Annotation line properties
  • Annotation rectangle properties
  • Annotation textarrow properties
  • Annotation textbox properties

To modify the appearance of annotation objects created with the plotting tools, use The Property Editor.

Annotation Layer

All annotation objects are displayed in an overlay axes that covers the figure. This layer is designed to display only annotation objects. You should not parent objects to this axes nor set any properties of this axes.

Objects in the Plotting Axes

You can create lines, text, rectangles, and ellipses in data coordinates in the axes of a graph using the line, text, and rectangle functions. These objects are not placed in the annotation axes and must be located inside their parent axes.

Deleting Annotations

Existing annotations persist on a plot when you replace its data. This might not be what you want to do. If it is not, or if you want to remove annotation objects for any reason, you can do so manually, or sometimes programmatically, in several ways:

To manually delete, click the Edit Plot tool or invoke plottools, select the annotation(s) you want to remove, and do one of the following:

  • Press the Delete key.
  • Press the Backspace key.
  • Select Clear from the Edit menu.
  • Select Delete from the context menu (one annotation at a time).

If you obtained a handle for the annotation when you created it, use the delete function:

delete(anno_obj_handle)

There is no reliable way to obtain handles for annotations from a figure’s property set; you must keep track of them yourself.

To delete all annotations at once (as well as all plot contents), type

clf

Normalized Coordinates

By default, annotation objects use normalized coordinates to specify locations within the figure. In normalized coordinates, the point 0,0 is always the lower left corner and the point 1,1 is always the upper right corner of the figure window, regardless of the figure size and proportions. Set the Units property of annotation objects to change their coordinates from normalized to inches, centimeters, points, pixels, or characters.

When their Units property is other than normalized, annotation objects have absolute positions with respect to the figure’s origin, and fixed sizes. Therefore, they will shift position with respect to axes when you resize figures. When units are normalized, annotations shrink and grow when you resize figures; this can cause lines of text in textbox annotations to wrap. However, if you set the FontUnits property of an annotation textbox object to normalized, the text changes size rather than wraps if the textbox size changes.

You can use either the set command or the Inspector to change a selected annotation object’s Units property:

set(gco,'Units','inches')  % or
inspect(gco)

[help]For more information see Positioning Annotations in Data Space in the MATLAB Graphics documentation.[/help]

Example — Enclosing Subplots with an Annotation Rectangle

The following example shows how to create a rectangle annotation object and use it to highlight two subplots in a figure. This example uses the axes properties Position and TightInset to determine the location and size of the annotation rectangle.

Create an array of subplots:

x = -2*pi:pi/12:2*pi;
y = x.^2;
subplot(2,2,1:2)
plot(x,y)
h1=subplot(223);
y = x.^4;
plot(x,y)
h2=subplot(224);
y = x.^5;
plot(x,y)

Determine the location and size of the annotation rectangle required to enclose axes, tick mark labels, and title using the axes Position and TightInset properties:

p1 = get(h1,'Position'); 
t1 = get(h1,'TightInset');
p2 = get(h2,'Position');
t2 = get(h2,'TightInset');
x1 = p1(1)-t1(1); y1 = p1(2)-t1(2); 
x2 = p2(1)-t2(1); y2 = p2(2)-t2(2); 
w = x2-x1+t1(1)+p2(3)+t2(3); h = p2(4)+t2(2)+t2(4);

Create the annotation rectangle to enclose the lower two subplots. Make the rectangle a translucent red with a solid border:

annotation('rectangle',[x1,y1,w,h],...
 'FaceAlpha',.2,'FaceColor','red','EdgeColor','red');

Linking Graphs to Variables & Data Source Properties

Plot objects let you link a MATLAB expression with properties that contain data. For example, the lineseries object has data source properties associated with the XData, YData, and ZData properties. These properties are called XDataSource, YDataSource, and ZDataSource.

To use a data source property:

  • Assign the name of a variable to the data source property that you want linked to an expression.
  • Calculate a new value for the variable.
  • Call refreshdata to update the plot object data.

refreshdata lets you specify whether to use a variable in the base workspace or the workspace of the function from which you call refreshdata.

Data Source Example

The following example illustrates how to use this technique:

Changing the Size of Data Variables

function datasource_ex
t = 0:pi/20:2*pi;
y = exp(sin(t));
h = plot(t,y,'YDataSource','y');
for k = 1:.1:10
	y = exp(sin(t.*k));
	refreshdata(h,'caller') % Evaluate y in the function workspace
	drawnow; pause(.1)
end

If you change one data source property to a variable that contains data of a different dimension, you might cause the function to generate a warning and not render the graph until you have changed all data source properties to appropriate values.

Matlab Plot Objects

A number of high-level plotting functions create plot objects. The properties of plot objects provide easy access to the important properties of the core graphics objects that the plot objects contain.

Plot object parents can be axes or group objects (hggroup or hgtransform). See Objects That Can Contain Other Objects for examples.

This table lists the plot objects and the graphing functions that use them. Click the object names to see a description of their properties.
Plot Objects

Object Purpose
areaseries Used to create area graphs.
barseries Used to create bar graphs.
contourgroup Used to create contour graphs.
errorbarseries Used to create errorbar graphs.
lineseries Used by line plotting functions (plot, plot3, etc.).
quivergroup Used to create quiver and quiver3 graphs.
scattergroup Used to create scatter and scatter3 graphs.
stairseries Used to create stairstep graphs (stairs).
stemseries Used to create stem and stem3 graphs.
surfaceplot Used by the surf and mesh group of functions.

Creating a Plot Object

For example, the following statements create a contour graph of the peaks function and then set the line style and width of the contour lines:

[x,y,z] = peaks;
[c,h] = contour(x,y,z);
set(h,'LineWidth',3,'LineStyle',':')


The contour plot object lets you set the line width and style of the contour graph by setting two properties. Looking at the core objects contained in the contour plot object reveals a number of patch objects whose edges are used to implement the contour line, which you would otherwise need to set individually.

Identifying Plot Objects Programmatically

child_handles = get(h,'Children');
get(child_handles,'Type')
ans =
    'patch'
    'patch'
    'patch'
    'patch'
    'patch'
    'patch'
    'patch'
    'patch'
    'patch'
    'patch'
    'patch'
    'patch'

Plot objects all return hggroup as the value of the Type property. If you want to be able to identify plot objects programmatically but do not have access to the object’s handle, set a value for the object’s Tag property.

For example, the following statements create a bar graph with five barseries objects and assign a different value for the Tag property on each object:

h = bar(rand(5));
set(h,{'Tag'},{'bar1','bar2','bar3','bar4','bar5'}')

The cell array of property values must be transposed (‘) to have the proper shape. See the set function for more information on setting properties.

No User Default Values

You cannot define default values for plot objects.

Plot Objects and Backward Compatibility

[warning]The v6 option discussed in this section is now obsolete and will be removed in a future version of MATLAB.[/warning]

Plotting functions that create plot objects can introduce incompatibilities with code written before MATLAB Version 7.x. However, all plotting functions that return handles to plot objects support an optional argument (‘v6’) that forces the functions to use core objects, as was the case in MATLAB before Version 7.

  • See Plot Objects for a list of functions that create plot objects.
  • See Core Graphics Objects for a list of core graphics objects.

Saving Figures That Are Compatible with Previous Version of MATLAB

Create backward-compatible FIG-files by following these two steps:

  • Ensure that any plotting functions used to create the contents of the figure are called with the ‘v6’ argument, where applicable.
  • Use the ‘-v6’ option with the hgsave command.

For example:

h = figure;
t = 0:pi/20:2*pi;
plot('v6',t,sin(t).*2)
hgsave(h,'myFigFile','-v6')

You can set a general MATLAB preference to ensure that figures saved by selecting File>Save are backward compatible. To access MATLAB preferences, select Preferences from the Desktop File menu. Expand the General node and select MAT Files. Click Ensure backward compatibility (-v6). This setting affects all FIG-files and MAT-files that you create.

Matlab Core Graphics Objects

Core graphics objects include basic drawing primitives:

  • Line, text, and polygon shells (patch objects)
  • Specialized objects like surfaces, which are composed of a rectangular grid of vertices
  • Images
  • Light objects, which are not visible but affect the way some objects are colored

Axes contain objects that represent data, such as line, surfaces, contourgroups, etc.

The following table lists the core graphics objects and contains links to the reference pages of the functions used to create each object.

Core Graphics Objects

Function Purpose
axes Axes objects define the coordinate system for displaying graphs. Axes are always contained within a figure.
image 2-D representation of a matrix where numeric values are mapped to colors. Images can also be 3-D arrays of RGB values.
light Directional light source located within the axes. Lights affect patches and surfaces, but cannot themselves be seen.
line A line is drawn by connecting the data points that define it.
patch Filled polygons with separate edge properties. A single patch can contain multiple faces, each colored independently with solid or interpolated colors.
rectangle 2-D object that has settable edge and face color, and variable curvature (can draw ellipses).
surface 3-D grid of quadrilaterals created by plotting the value of each element in a matrix as a height above the x-y plane.
text Character strings positioned in the coordinate system defined by the axes.

The following picture illustrates some typical core graphics objects.

Core Graphics Objects

This section describes the core graphics objects.

Axes

Axes objects define a frame of reference in a figure window for the display objects that are generally defined by data. For example, MATLAB creates a line by connecting each data point with a line segment. The axes determines the location of each data point in the figure by defining axis scales (x, y, and z, or radius and angle, etc.)

Axes are children of figures and are parents of core, plot, and group objects.

While annotation objects are also children of axes, they can be parented only to the hidden annotation axes. (See the annotation function for more information.)

All functions that draw graphics (e.g., plot, surf, mesh, and bar) create an axes object if one does not exist. If there are multiple axes within the figure, one axes is always designated as the “current” axes, and is the target for display of the above-mentioned graphics objects. (Uicontrols and uimenus are not children of axes.)

Image

A MATLAB image consists of a data matrix and possibly a colormap. There are three basic image types that differ in the way that data matrix elements are interpreted as pixel colors—indexed, intensity, and truecolor. Since images are strictly 2-D, you can view them only at the default 2-D view.

Light

Light objects define light sources that affect all patch and surface objects within the axes. You cannot see lights, but you can set properties that control the style of light source, color, location, and other properties common to all graphics objects.

Line

Line objects are the basic graphics primitives used to create most 2-D and some 3-D plots. High-level functions plot, plot3, and loglog (and others) create line objects. The coordinate system of the axes positions and orients the line.

Patch

Patch objects are filled polygons with edges. A single patch can contain multiple faces, each colored independently with solid or interpolated colors. fill, fill3, and contour3 create patch objects. The coordinate system of the axes positions and orients the patch.

Rectangle

Rectangle objects are 2-D filled areas having a shape that can range from a rectangle to an ellipse. Rectangles are useful for creating flowchart-type drawings.

Surface

Surface objects are 3-D representations of matrix data created by plotting the value of each matrix element as a height above the x-y plane. Surface plots are composed of quadrilaterals whose vertices are specified by the matrix data. MATLAB can draw surfaces with solid or interpolated colors or with only a mesh of lines connecting the points. The coordinate system of the axes positions and orients the surface.

The high-level function pcolor and the surf and mesh group of functions create surface objects.

Text

Text objects are character strings. The coordinate system of the parent axes positions the text. The high-level functions title, xlabel, ylabel, zlabel, and gtext create text objects.

Example — Creating Core Graphics Objects

Object creation functions have a syntax of the form

handle = function('propertyname',propertyvalue,...)

You can specify a value for any object property (except those that are read only) by passing property name/value pairs as arguments. The function returns the handle of the object it creates, which you can use to query and modify properties after creating the object.

This example evaluates a mathematical function and creates three graphics objects using the property values specified as arguments to the figure, axes, and surface commands. MATLAB uses default values for all other properties.

[x,y] = meshgrid([-2:.4:2]);
Z = x.*exp(-x.^2-y.^2);
fh = figure('Position',[350 275 400 300],'Color','w');
ah = axes('Color',[.8 .8 .8],'XTick',[-2 -1 0 1 2],...
          'YTick',[-2 -1 0 1 2]);
sh = surface('XData',x,'YData',y,'ZData',Z,...
             'FaceColor',get(ah,'Color')+.1,...
             'EdgeColor','k','Marker','o',...
             'MarkerFaceColor',[.5 1 .85]);


The surface function does not use a 3-D view like the high-level surf functions. Object creation functions simply add new objects to the current axes without changing axes properties, except the Children property, which now includes the new object and the axis limits (XLim, YLim, and ZLim), if necessary.

You can change the view using the camera commands or use the view command.
view(3)

Parenting

view(3)

By default, all statements that create graphics objects do so in the current figure and the current axes (if the object is an axes child). However, you can specify the parent of an object when you create it. For example,

axes('Parent',figure_handle,...)

creates an axes in the figure identified by figure_handle. You can also move an object from one parent to another by redefining its Parent property:

High-Level Versus Low-Level Functions

set(gca,'Parent',figure_handle)

Many MATLAB graphics functions call the object creation functions to draw graphics objects. However, high-level routines also clear the axes or create a new figure, depending on the settings of the axes and figure NextPlot properties.

In contrast, core object creation functions simply create their respective graphics objects and place them in the current parent object. They do not respect the settings of the figure or axes NextPlot property.

For example, if you call the line function,

line('XData',x,'YData',y,'ZData',z,'Color','r')

MATLAB draws a red line in the current axes using the specified data values. If there is no axes, MATLAB creates one. If there is no figure window in which to create the axes, MATLAB creates it as well.

If you call the line function a second time, MATLAB draws the second line in the current axes without erasing the first line. This behavior is different from high-level functions like plot that delete graphics objects and reset all axes properties (except Position and Units). You can change the behavior of high-level functions by using the hold command or by changing the setting of the axes NextPlot property.

See Controlling Graphics Output for more information on this behavior and on using the NextPlot property.

Simplified Calling Syntax

Object creation functions have convenience forms that allow you to use a simpler syntax. For example,

text(.5,.5,.5,'Hello')

is equivalent to

text('Position',[.5 .5 .5],'String','Hello')

Using the convenience form of an object creation function can cause subtle differences in behavior when compared to formal property name/property value syntax.

[note]

A Note About Property Names

[/note]

By convention, MATLAB documentation capitalizes the first letter of each word that makes up a property name, such as LineStyle or XTickLabelMode. While this makes property names easier to read, MATLAB does not check for uppercase letters. In addition, you need to use only enough letters to identify the name uniquely, so you can abbreviate most property names.

In your code, however, using the full property name can prevent problems with futures releases of MATLAB if a shortened name is no longer unique because of the addition of new properties.

Matlab Graphics Windows & the Figure

Figures are the windows in which MATLAB displays graphics. Figures contain menus, toolbars, user-interface objects, context menus, axes and, as axes children, all other types of graphics objects.

MATLAB places no limits on the number of figures you can create. (Your computer systems might impose limitations, however.)

Figures play two distinct roles in MATLAB:

  • Containing data graphs
  • Containing graphical user interfaces

Figures can contain both graphs and GUIs components at the same time. For example, a GUI might be designed to plot data and therefore contain an axes as well as user interface objects.
[note]See Example — Using Figure Panels for an example of such a GUI.[/note]

The following diagram illustrates the types of objects that figures can contain.

Both figures and axes have children that act as containers. A uipanel can contain user interface objects and be parented to a figure and group objects (hggroup and hgtransform) can contain axes children (except light objects) and be parented to an axes.

See Objects That Can Contain Other Objects for more information.

Figures Used for Graphing Data

MATLAB functions that draw graphics (e.g., plot and surf) create figures automatically if none exist. If there are multiple figures open, one figure is always designated as the “current” figure, and is the target for graphics output.

The gcf command returns the handle of the current figure or creates a new figure if one does not exist. For example, enter the following command to see a list of figure properties:

get(gcf)

The root object CurrentFigure > property returns the handle of the current figure, if one exists, or returns empty if there are no figures open:

get(0,'CurrentFigure')
ans =
[]

See Controlling Graphics Output for more information on how MATLAB determines where to display graphics.

Figures that display graphs need to contain axes to provide the frame of reference for objects such as lines and surfaces, which are used to represent data. These data representing objects can be contained in group objects or contained directly in the axes. See Example — Transforming a Hierarchy of Objects for an example of how to use group objects.

Figures can contain multiple axes arranged in various locations within the figure and can be of various sizes. See Automatic Axes Resize and Multiple Axes per Figure for more information on axes.

Figures Used for GUIs

GUIs range from sophisticated applications to simple warning dialog boxes. You can modify many aspects of the figure to fit the intended use by setting figure properties. For example, the following figure properties are often useful when creating GUIs:

  • Show or hide the figure menu, while displaying custom-designed menus (MenuBar).
  • Change the figure title (Name).
  • Control user access to the figure handle (HandleVisibility).
  • Create a callback that executes whenever the user resizes the figure (ResizeFcn).
  • Control display of the figure toolbar (Toolbar).
  • Assign a context menu (UIContextMenu).
  • Define callbacks that execute when users click drag or release the mouse over the figure (WindowButtonDownFcn, WindowButtonMotionFcn, WindowButtonUpFcn). See also the ButtonDownFcn property.
  • Specify whether the figure is modal (WindowStyle).

See the Figure Properties reference page for more information on figure characteristics you can specify.

See the Creating Graphical User Interfaces documentation for more information about using figure to create GUIs.

Root Object — The Figure Parent

The parent of a figure is the root object. You cannot instantiate the root object because its purpose is only to store information. It maintains information on the state of MATLAB, your computer system, and some MATLAB defaults.

There is only one root object, and all other objects are its descendants. You do not create the root object; it exists when you start MATLAB. You can, however, set the values of root properties and thereby affect the graphics display.

[help]For more information, see Root Properties object properties.[/help]

More Information on Figures

See the figure reference page for information on creating figures.

See Callback Properties for Graphics Objects for information on figure events for which you can define callbacks.

See Figure Properties for information on other figure properties.

Generating MATLAB Code to Reproduce a Graph

Create a Stem Plot and Generate Code for It

Suppose you have created the following graph.

t = 0:.2:20;
alpha =.055;
stem(t,exp(-alpha*t).*sin(5*t))

Use the Property Editor to modify the graph. Select the stemseries and change the marker fill color to dark red, and marker edge color and line color to dark green. Remove the axes box, and change the font size for the axes labels to 8 to look like the following picture:

You can generate code to reproduce this graph by selecting Generate M-File from the Figure menu. MATLAB code generation software composes a function that recreates the graph and opens the generated file in the editor.

This feature is particularly useful for capturing property settings and other modifications you make using the plot tools GUI.

The file appears in an editor window and consists of the following code:

function createfigure(X1, Y1)
%CREATEFIGURE(X1,Y1)
%  X1:  stem x
%  Y1:  stem y

%  Auto-generated by MATLAB on 24-May-2006 14:23:45

% Create figure
figure1 = figure('Color',[1 1 1]);

% Create axes
axes('Parent',figure1,'FontSize',8);
hold('all');

% Create stem
stem(X1,Y1,'MarkerFaceColor',[0.8471 0.1608 0],...
    'MarkerEdgeColor',[0.1686 0.5059 0.3373],...
    'Color',[0 0.498 0]);

You must save the file before exiting MATLAB if you want to use it in future sessions.

Data Arguments

Generated functions do not store the data necessary to recreate the graph. You must supply the data arguments t as X1 and exp(-alpha*t).*sin(5*t) as Y1 to the function to recreate your graph. Of course, you can call the generated function with other argument pairs too.

Limitations

Attempting to generate code for graphs containing a large number of graphics objects (e.g., greater than 20 plotted lines) might be impractical.

Matlab Editing Plots

Why Edit Plots?

MATLAB graphs are formatted to provide readability, setting the scale of axes, including tick marks on the axes, and using color and line style to distinguish the plots in the graph. However, if you are creating presentation graphics, you might want to change this default formatting or add descriptive labels, titles, legends, and other annotations to help explain your data.

You can edit the plots you create two ways:

  • Using the mouse to select and edit objects interactively
  • Using MATLAB functions at the command line or in a MATLAB code file
  • Interactive Plot Editing

If you enable plot editing mode in the MATLAB figure window, you can perform point-and-click editing of your graph. In this mode, you can modify the appearance of a graphics object by double-clicking on the object and changing the values of its properties. You access the properties through a graphical user interface called the Property Editor.

[important]For more information about interactive editing, see Working in Plot Edit Mode. [/important]

For information about editing object properties in plot editing mode, see The Property Editor.

Using Functions to Edit Graphs

If you prefer to work from the MATLAB command line or if you are creating a code file, you can use MATLAB commands to edit the graphs you create. Taking advantage of the MATLAB Handle Graphics® system, you can use the set and get commands to change the properties of the objects in a graph.

[warning]Plot editing mode provides an alternative way to access the properties of MATLAB graphic objects. However, you can only access a subset of object properties through this mechanism. You might need to use a combination of interactive editing and command-line editing to achieve the effect you desire.[/warning]

Controlling the Number of Instances

Limiting Instances

You can limit the number of instances of a class that can exist at any one time. For example, a singleton class can have only one instance and provides a way to access this instance. You can create a singleton class using these elements:

  • A persistent variable to contain the instance
  • A sealed class (Sealed attribute set to true) to prevent subclassing
  • A private constructor (Access attribute set to private)
  • A static method to return the handle to the instance, if it exists, or to create the instance when needed.

Implementing a Singleton Class

The following skeletal class definition shows how you can approach the implementation of a class that allows you to create only one instance at a time:

classdef (Sealed) SingleInstance < handle
   methods (Access = private)
      function obj = SingleInstance
      end
   end
   methods (Static)
      function singleObj = getInstance
         persistent localObj
         if isempty(localObj) || ~isvalid(localObj)
            localObj = SingleInstance;
         end
         singleObj = localObj;
      end
   end
end

The getInstance static method returns a handle to the object created, which the class stores in a persistent variable. getInstance creates an instance only the first time called in a session or when the object becomes invalid. For example:

sobj = SingleInstance.getInstance
sobj = 
  SingleInstance handle with no properties.
  Methods, Events, Superclasses

As long as sobj exists as a valid handle, calling getInstance returns a handle to the same object. If you delete sobj, then calling getInstance creates an object and returns the handle.

delete(sobj)
isvalid(sobj)
ans =

     0
sobj = SingleInstance.getInstance;
isvalid(sobj)
ans =

     1

Implementing a Set/Get Interface for Properties

The Standard Set/Get Interface

The MATLAB Handle Graphics system implements an interface based on set and get methods. These methods enable you to set or query the value of graphics object properties. The hgsetget subclass of the handle class provides implementations of these methods that your class can inherit to provide the same set and get functionality.

[warning]The set and get methods referred to in this section are different from the property set access and property get access methods. See Controlling Property Access for information on property access methods.[/warning]

Property Get Method

The get method returns property values from a handle array.

function SV = get(H)
function CV = get(H,prop)
  • If you do not specify property names, get returns a struct array in which each element corresponds to the element in H. Each field in the struct corresponds to a property defined by the class of H. The value of each field is the value of the corresponding property.
  • If you specify prop as a char array, then MATLAB interprets it as a property name. get returns the value of that property if H is scalar, or returns a cell array of property values if H is an array of handles. The cell array is always a column vector regardless of the shape of H. If prop is a cell array of string property values, then get returns a cell array of values where each row in the cell corresponds to an element in H and each column in the cell corresponds to an element in prop.
  • Property Set Method

The set method assigns values to properties for handles in array H.

function S = set(H)
function info = set(H, prop)
function set(H,'PropertyName',PropertyValue)

If you do not specify property values, set returns a cell array of possible values for each requested property when the property value is a finite enumeration of possible values.

  • If you specify only H, set returns a struct with one field for each property in the class of H. Each field contains either an empty cell array or a cell array of possible property values (if such a finite set exists).
  • If you specify prop as a string containing a property name, then set returns either a cell array of possible values or an empty cell.
  • If you specify prop as a cell array of property names, then set returns a cell column vector. Each cell corresponds to a property in prop and each cell value is a cell array of possible values, or empty if there is no finite enumeration of possible values.

You can also pass property-value pairs to set using cell arrays and structures as described for the built–in set function.

Subclassing hgsetget

This example creates a class with the set/get interface and illustrates the behavior of the inherited methods:

classdef MyAccount < hgsetget % subclass hgsetget
   properties 
      AccountNumber
      AccountBalance = 0;
      AccountStatus
   end % properties
   methods 
      function obj = MyAccount(actnum,intamount,status)
         obj.AccountNumber = actnum;
         obj.AccountBalance = intamount;
         obj.AccountStatus = status;
      end % MyAccount
      function obj = set.AccountStatus(obj,val)
         if ~(strcmpi(val,'open') ||... 
               strcmpi(val,'deficit') ||... 
               strcmpi(val,'frozen'))
            error('Invalid value for AccountStatus ')
         end
      obj.AccountStatus = val;
      end % set.AccountStatus
   end % methods
end % classdef

Create an instance of the class and save its handle:

h = MyAccount(1234567,500,'open');

You can query the value of any object property using the inherited get method:

get(h,'AccountBalance')
ans =

   500

You can set the value of any property using the inherited set method:

set(h,'AccountStatus','frozen')

MATLAB calls the property set function (set.AccountStatus) when you use the set method:

set(h,'AccountStatus','closed')
??? Error using ==> MyAccount.MyAccount>MyAccount.set.AccountStatus at 19
Invalid value for AccountStatus

Listing All Properties

The standard set/get interface enables you to display all object properties and their current values using get with no output argument and only a handle as input. For example,

get(h)
   AccountNumber: 1234567
   AccountBalance: 500
   AccountStatus: 'open'

Similarly, you can list the setable properties of the object using set:

set(h)
   AccountNumber: {}
   AccountBalance: {}
   AccountStatus: {}

Customizing the Property List

You can customize the way property lists are displayed by redefining the following methods in your subclass:

  • setdisp — Called by set when you call set with no output arguments and a single input parameter containing the handle array.
  • getdisp — Called by get when you call get with no output arguments and a single input parameter containing the handle array.

Finding Handle Objects and Properties

Finding Handle Objects

The findobj method enables you to locate handle objects that meet certain conditions.

function HM = findobj(H,) 

The findobj method returns an array of handles matching the conditions specified.

Finding Handle Object Properties

The findprop method returns the meta.property object for the specified object and property.

function mp = findprop(h,'PropertyName') 

The findprop method returns the meta.property object associated with the PropertyName property defined by the class of h. The property can also be a dynamic property created by the addprop method of the dynamicprops class.

You can use the returned meta.property object to obtain information about the property, such as querying the settings of any of its attributes. For example, the following statements determine that the setting of the AccountStatus property’s Dependent attribute is false.

ba = BankAccount(007,50,'open');
mp = findprop(ba,'AccountStatus'); % get meta.property object
mp.Dependent
ans =
     0

Working with Meta-Classes provides more information on meta-classes.

Comparing Handle and Value Classes

Why Select Handle or Value

MATLAB support two kinds of classes — handle classes and value classes. The kind of class you use depends on the desired behavior of the class instances and what features you want to use.

Use a handle class when you want to create a reference to the data contained in an object of the class, and do not want copies of the object to make copies of the object data. For example, use a handle class to implement an object that contains information for a phone book entry. Multiple application programs can access a particular phone book entry, but there can be only one set of underlying data.

The reference behavior of handles enables these classes to support features like events, listeners, and dynamic properties.

Use value classes to represent entities that do not need to be unique, like numeric values. For example, use a value class to implement a polynomial data type. You can copy a polynomial object and then modify its coefficients to make a different polynomial without affecting the original polynomial.

Which Kind of Class to Use describes how to select the kind of class to use for your application.

Passing Objects to Functions compares handle and value object behavior when used as arguments to functions.

Behavior of MATLAB Built-In Classes

If you create an object of the class int32 and make a copy of this object, the result is two independent objects having no data shared between them. The following code example creates an object of class int32 and assigns it to variable a, and then copies it to b. When you raise a to the fourth power and assign the value again to the variable a, MATLAB creates an object with the new data and assigns it to the variable a, overwriting the previous assignment. The value of b does not change.

a = int32(7);
b = a;
a = a^4;
b
   7

MATLAB copies the value of a to b, which results in two independent versions of the original object. This behavior is typical of MATLAB numeric classes.

Handle Graphics classes return a handle to the object created. A handle is a variable that references an instance of a class. If you copy the handle, you have another variable that refers to the same object. There is still only one version of the object data. For example, if you create a Handle Graphics line object and copy its handle to another variable, you can set the properties of the same line using either copy of the handle.

x = 1:10; y = sin(x);
h1 = line(x,y);
h2 = h1;

>>set(h2,'Color','red') % line is red
>>set(h1,'Color','green') % line is green
>>delete(h2)
>>set(h1,'Color','blue')
??? Error using ==> set
Invalid handle object.

[help]Note also, if you delete one handle, all copies are now invalid because you have deleted the single object that all copies point to.[/help]

Behavior of User-Defined Classes

Value class instances behave like built-in numeric classes and handle class instances behave like Handle Graphics objects, as illustrated in Behavior of MATLAB Built-In Classes.

Value Classes

MATLAB associates objects of value classes with the variables to which you assign them. When you copy a value object, MATLAB also copies the data contained by the object. The new object is independent of changes to the original object. Instances behave like standard MATLAB numeric and struct classes. Each property behaves essentially like a MATLAB array See Memory Allocation for Arrays for more information.

Value Class Behavior

Use value classes when assigning an object to a variable and passing an object to a function must make a copy of the function. Value objects are always associated with one workspace or temporary variable and go out of scope when that variable goes out of scope or is cleared. There are no references to value objects, only copies which are themselves objects.

For example, suppose you define a polynomial class whose Coefficients property stores the coefficients of the polynomial. Note how copies of these value-class objects are independent of each other:

p = polynomial([1 0 -2 -5]);
p2 = p;
p.Coefficients = [2 3 -1 -2 -3];
p2.Coefficients
ans = 
   1 0 -2 -5

Creating a Value Class

All classes that are not subclasses of the handle class are value classes. Therefore, the following classdef creates a value class named myValueClass:

classdef myValueClass 
   ...
end 

Handle Classes

Objects of handle classes use a handle to reference objects of the class. A handle is a variable that identifies an instance of a class. When you copy a handle object, MATLAB copies the handle, but not the data stored in the object properties. The copy refers to the same data as the original handle. If you change a property value on the original object, the copied object reflects the same change.

All handle classes are subclasses of the abstract handle class. In addition to providing handle copy semantics, deriving from the handle class enables your class to:

  • Inherit a number of useful methods (Handle Class Methods)
  • Define events and listeners (Defining Events and Listeners — Syntax and Techniques)
  • Define dynamic properties (Dynamic Properties — Adding Properties to an Instance)
  • Implement Handle Graphics type set and get methods (Implementing a Set/Get Interface for Properties)

Creating a Handle Class

Subclass the handle class explicitly to create a handle class:

classdef myClass < handle
   ...
end 

[important]See The Handle Superclass for more information on the handle class and its methods.[/important]

Subclasses of Handle Classes

If you subclass a class that is itself a subclass of the handle class, your subclass is also a handle class. You do not need to specify the handle superclass explicitly in your class definition. For example, the employee class is a subclass of the handle class:

classdef employee < handle 
...
end

Create a subclass of the employee class for engineer employees, which is also a handle class. You do not need to specify handle as a superclass in the classdef:

classdef engineer < employee 
...
end

Handle Class Behavior

A handle is an object that references its data indirectly. When constructing a handle, the MATLAB runtime creates an object with storage for property values and the constructor function returns a handle to this object. When you assign the handle to a variable or when you pass the handle to a function, MATLAB copies the handle, but not the underlying data.

For example, suppose you have defined a handle class that stores data about company employees, such as the department in which they work:

classdef employee < handle 
   properties
      Name = ''
      Department = '';
   end
   methods
      function e = employee(name,dept)
         e.Name = name;
         e.Department = dept;
      end % employee
      function transfer(obj,newDepartment)
         obj.Department = newDepartment;
      end % transfer
   end
end

The transfer method in the previous code changes the employee's department (the Department property of an employee object). In the following statements, e2 is a copy of the handle object e. Notice that when you change the Department property of object e, the property value also changes in object e2.

e = employee('Fred Smith','QE');
e2 = e; % Copy handle object
transfer(e,'Engineering')
e2.Department
ans =
Engineering

The variable e2 is an alias for e and refers to the same property data storage as e.

Initializing Properties to Handle Objects

See How to Initialize Property Values for information on the differences between initializing properties to default values in the properties block and initializing properties from within the constructor. Also, see Arrays of Handle Objects for related information on working with handle classes.

employee as a Value Class

If the employee class was a value class, then the transfer method would modify only its local copy of the employee object. In value classes, methods like transfer that modify the object must return a modified object to copy over the existing object variable:

function obj = transfer(obj,newDepartment)
   obj.Department = newDepartment;
end

When you call transfer, assign the output argument to create the modified object.

e = transfer(e,'Engineering');

In a value class, the transfer method does not affect the variable e2, which is a different employee object. In this example, having two independent copies of objects representing the same employee is not a good design. Hence, implement the employee class as a handle class.

Deleting Handles

You can destroy handle objects before they become unreachable by explicitly calling the delete function. Deleting the handle of a handle class object makes all handles invalid. For example:

delete(e2)
e.Department
??? Invalid or deleted object.

Calling the delete function on a handle object invokes the destructor function or functions for that object. See Handle Class Delete Methods for more information.

Specifying Class Precedence

InferiorClasses Attribute

You can specify the relative precedence of user-defined classes using the class InferiorClasses attribute. Assign a cell array of class names (represented as meta.class objects) to this attribute to specify classes that are inferior to the class you are defining. For example, the following classdef declares that myClass is dominant over class1 and class2.

classdef (InferiorClasses = {?class1,?class2}) myClass
   ...
end

The ? operator combined with a class name creates a meta.class object. This syntax enables you to create a meta.class object without requiring you to construct an actual instance of the class.

MATLAB built-in classes are always inferior to user-defined classes and should not be used in this list.

The built-in classes include: double, single, char, logical, int64, uint64, int32, uint32, int16, uint16, int8, uint8, cell, struct, and function_handle.

Dominant Class

MATLAB defines a class as dominant when evaluating expression involving objects of more than one class. The dominant class determines which method MATLAB calls and the class of arrays that are form by combining objects of different classes, assuming MATLAB convert to inferior objects to the dominant class. See Concatenating Objects of Different Classes for more information on creating object arrays.

More Information

[important]
See Determining Which Method Is Invoked for more on how the MATLAB classes dispatch when evaluating expressions containing objects.[/important]
[important]
See Class Precedence and MATLAB Path for information on how the location of a class definition on the MATLAB path determines its precedence.[/important]

[important]See Working with Meta-Classes for information on meta-class objects.[/important]

No Attribute Inheritance

Subclasses do not inherit a superclass InferiorClasses attribute. Only instances of the classes specified in the subclass InferiorClasses attribute are inferior to subclass objects.

Scoping Classes with Packages

Package Folders

Packages are special folders that can contain class folders, function and class definition files, and other packages. Packages define a scope (sometimes called a namespace) for the contents of the package folder. This means function and class names need to be unique only within the package. Using a package provides a means to organize classes and functions and to select names for these components that other packages can reuse.

[warning]Packages are not supported for classes created prior to MATLAB Version 7.6 (i.e., classes that do not use classdef).[/warning]

Package folders always begin with the + character. For example,

+mypack
+mypack/pkfcn.m % a package function
+mypack/@myClass % class folder in a package

The top-level package folder’s parent folder must be on the MATLAB path.

List the contents of a package using the what command:

what event

Classes in directory Y:xxx\matlab\toolbox\matlab\lang\+event

EventData      PropertyEvent  listener       proplistener  

Referencing Package Members Within Packages

All references to packages, functions, and classes in the package must use the package name prefix, unless you import the package. (See Importing Classes.) For example, call a package function with this syntax:

z = mypack.pkfcn(x,y);

Note that definitions do not use the package prefix. For example, the function definition line of the pkfcn.m function would include only the function name:

function z = pkfcn(x,y)

Similarly, a package class would be defined with only the class name:

classdef myClass

but would be called with the package prefix:

obj = mypack.myClass(arg1,arg2,...);

Calling class methods does not require the package name because you have an instance of the class:

obj.myMethod(arg) or 
myMethod(obj,arg)

A static method requires the full class name:

Referencing Package Members from Outside the Package

mypack.myClass.stMethod(arg)

Because functions, classes, and other packages contained in a package are scoped to that package, to reference any of the package members, you must prefix the package name to the member name, separated by a dot. For example, the following statement creates an instance of myClass, which is contained in mypack package.

obj = mypack.myClass;

This section shows you how to access various package members from outside a package. Suppose you have a package mypack with the following contents:

+mypack
+mypack/myfcn.m
+mypack/@myfirstclass
+mypack/@myfirstclass/myfcn.m
+mypack/@myfirstclass/otherfcn.m
+mypack/@myfirstclass/myfirstclass.m
+mypack/@mysecondclass
+mypack/@mysecondclass/mysecondclass.m
+mypack/+mysubpack
+mypack/+mysubpack/myfcn.m

Invoke the myfcn function in mypack:

mypack.myfcn(arg)

Create an instance of each class in mypack:

obj1 = mypack.myfirstclass;
obj2 = mypack.mysecondclass(arg);

Invoke the myfcn function in mysubpack:

mypack.mysubpack.myfcn(arg1,arg2);

If mypack.myfirstclass has a method called myfcn, it is called as any method call on an object:

obj = mypack.myfirstclass;
myfcn(obj,arg);

If mypack.myfirstclass has a property called MyProp, it can be assigned using dot notation and the object:

Packages and the MATLAB Path

obj = mypack.myfirstclass;
obj.MyProp = some_value;

You cannot add package folders to the MATLAB path, but you must add the package’s parent folder to the path. Even if a package folder is the current folder, its parent folder must still be on the MATLAB path or the package members are not accessible.

Package members remain scoped to the package even if the package folder is the current folder. You must, therefore, always refer to the package members using the package name.

Package folders do not shadow other package folders that are positioned later on the path, unlike classes, which do shadow other classes.

Suppose a package and a class have the same name. For example:

fldr1/+foo
fldr2/@foo/foo.m

A call to which foo returns the path to the executable class constructor:

>> which foo
fldr2/@foo/foo.m

A function and a package can have the same name. However, a package name by itself is not an identifier so if a redundant name occurs alone, it identifies the function. Executing a package name alone returns an error.

In cases where a package and a class have the same name, a static method takes precedence over a package function. For example:

fldr1/+foo/bar.m % bar is a function in package foo
fldr2/@foo/bar.m % bar is a static method of class foo

A call to which foo.bar returns the path to the static method:

>> which foo.bar
fldr2/@foo/bar.m

In cases where a path folder contains both package and class folders with the same name, the class static method takes precedence over the package method:

A call to which foo.bar returns the path to the static method:

fldr1/@foo/bar.m % bar is a static method of class foo
fldr1/+foo/bar.m % bar is a function in package foo
>> which foo.bar
fldr1/@foo/bar.m

Matlab Class for Graphing Functions

Display Fully Commented Example Code

The class block is the code that starts with the classdef key word and terminates with the end key word. The following example illustrated a simple class definition that uses:

  • Handle class
  • Property set and get functions
  • Use of a delete method for the handle object
  • Static method syntax

Display Fully Commented Example Code

You can display this class definition in a separate window that contains links to related sections in the documentations by clicking this link:

Open class definition file in the MATLAB editor. — Use this link if you want to save and modify your own version of the class.

Class Definition Block

The following code defines a class called topo. It is derived from handle so it is a handle class, which means it references the data it contains. See Using the topo Class for information on how this class behaves.

Using the topo Class

classdef topo < handle
% topo is a subclass of handle
   properties
      FigHandle % Store figure handle
      FofXY % function handle
      Lm = [-2*pi 2*pi]; % Initial limits
   end % properties 

   properties (Dependent = true, SetAccess = private) 
      Data
   end % properties Dependent = true, SetAccess = private

   methods
      function obj = topo(fnc,limits)
      % Constructor assigns property values
         obj.FofXY = fnc;
         obj.Lm = limits;
      end % topo

      function set.Lm(obj,lim)
      % Lm property set function
         if  ~(lim(1) < lim(2))
            error('Limits must be monotonically increasing')
         else
               obj.Lm = lim;
         end
      end % set.Lm

      function data = get.Data(obj)
      % get function calculates Data
      % Use class name to call static method
         [x,y] = topo.grid(obj.Lm);
         matrix = obj.FofXY(x,y);
         data.X = x;
         data.Y = y;
         data.Matrix = matrix;% Return value of property
      end % get.Data

      function surflight(obj)
      % Graph function as surface
         obj.FigHandle = figure;
         surfc(obj.Data.X,obj.Data.Y,obj.Data.Matrix,...
            'FaceColor',[.8 .8 0],'EdgeColor',[0 .2 0],...
            'FaceLighting','phong');
         camlight left; material shiny; grid off
         colormap copper
      end % surflight method
   
      function delete(obj)
      % Delete the figure
         h = obj.FigHandle;
         if ishandle(h)
            delete(h); 
         else
            return
         end
      end % delete
   end % methods

   methods (Static = true) % Define static method 
     function [x,y] = grid(lim)        
        inc = (lim(2)-lim(1))/35;
        [x,y] = meshgrid(lim(1):inc:lim(2));
     end % grid
   end % methods Static = true
end % topo class

[important]
See Display Fully Commented Example Code for information on using this class.[/important]

This class is designed to display a combination surface/contour graph of mathematical functions of two variables evaluated on a rectangular domain of x and y. For example, any of the following functions can be evaluated over the specified domain (note that x and y have the same range of values in this example just for simplicity).

x.*exp(-x.^2 - y.^2); [-2 2]
sin(x).*sin(y); [-2*pi 2*pi]
sqrt(x.^2 + y.^2); [-2*pi 2*pi]

To create an instance of the class, passing a function handle and a vector of limits to the constructor. The easiest way to create a function handle for these functions is to use an anonymous function:

tobj = topo(@(x,y) x.*exp(-x.^2-y.^2),[-2 2]);

The class surflight method uses the object to create a graph of the function. The actual data required to create the graph is not stored. When the surflight method accesses the Data property, the property's get function performs the evaluation and returns the data in the Data property structure fields. This data is then plotted. The advantage of not storing the data is the reduced size of the object.

Behavior of the Handle Class

The topo class is defined as a handle class. This means that instances of this class are handle objects that reference the underlying data store created by constructing the object. For example, suppose you create an instance of the class and create a copy of the object:

tobj = topo(@(x,y) x.*exp(-x.^2-y.^2),[-2 2]);
a = tobj;
surflight(a) % Call class method to create a graph


Now suppose you change the FofXY property so that it contains a function handle that points to another function:

tobj.FofXY = @(x,y) y.*exp(-x.^2-y.^2); % now multiply exp by y instead of x
surflight(a)


Because a is a copy of the handle object tobj, changes to the data referenced by tobj also change the data referenced by a.

How a Value Class Differs

If topo were a value class, the objects tobj and a would not share data; each would have its own copy of the property values.

Matlab Implementing Linked Lists

Displaying Fully Commented Example Code

Open class code in a popup window — Use this link if you want to see the code for this class annotated with links to descriptive sections.

Open class definition file in the MATLAB editor. — Use this link if you want to save and modify your version of the class.

To use the class, create a folder named @dlnode and save dlnode.m to this folder. The parent folder of @dlnode must be on the MATLAB path. Alternatively, save dlnode.m to a path folder.

Important Concepts Demonstrated

This section discusses concepts that are important in object-oriented design, and which are illustrated in this example.

Encapsulation

This example shows how classes encapsulate the internal structure used to implement the class design (a doubly linked lists). Encapsulation conceals the internal workings of the class from other code and provides a stable interface to programs that use this class. It also prevents client code from misusing the class because only class methods can access certain class data.

Class methods define the operations that you can perform on nodes of this class. These methods hide the potentially confusing process of inserting and removing nodes, while at the same time providing an interface that performs operations simply:

  • Creating a node by passing the constructor a data value
  • Inserting nodes with respect to other nodes in the list (before or after)
  • Removing nodes from the list

See Defining the dlnode Class for the implementation details.

Handle Class Behavior

This example shows an application of a handle class and explains why this is the best choice for the class. See Why a Handle Class for Doubly Linked Lists?.

dlnode Class Design

This example defines a class for creating the nodes of doubly linked lists in which each node contains:

  • Data array
  • Link to the next node
  • Link to the previous node

Each node has methods that enables the node to be:

  • Disconnected from a linked list
  • Connected before a specified node in a linked list
  • Connected after a specific node in a linked list

Class Properties

The dlnode class implements each node as a handle object with three properties:

  • Data — Contains the data for this node
  • Next — Contains the handle of the next node in the list (SetAccess = private)
  • Prev — Contains the handle of the previous node in the list (SetAccess = private)

This diagram shows a three-node list n1, n2, and n3. It also shows how the nodes reference the next and previous nodes.

Class Methods

The dlnode class implements the following methods:

  • dlnode — Constructs a node and assigns the value passed as input to the Data property
  • insertAfter — Inserts this node after the specified node
  • insertBefore — Inserts this node before the specified node
  • disconnect — Removes this node from the list
  • disp — Overloads default disp function so that the Data property displays on the command line for scalar objects and the dimension of the array displays for object arrays
  • delete — Removes this node from the list before it is destroyed
  • Creating Doubly Linked Lists

You create a node by passing the node’s data to the dlnode class constructor. For example, these statements create three nodes with sequential integer data just for simplicity:

n1=dlnode(1);
n2=dlnode(2);
n3=dlnode(3);

You build these nodes into a doubly linked list using the class methods:

n2.insertAfter(n1)
n3.insertAfter(n2)

Now the three nodes are linked. The dlnode disp method returns the data for the node referred to:

Why a Handle Class for Doubly Linked Lists?

n1.Next % Points to n2
ans =
Doubly-linked list node with data:
     2
n2.Next.Prev % Points back to n2
ans =
Doubly-linked list node with data:
     2 
n1.Next.Next % Points to n3
ans =
Doubly-linked list node with data:
     3 
n3.Prev.Prev % Points to n1
ans =
Doubly-linked list node with data:
     1  

Each node is unique in that no two nodes can be previous to or next to the same node. Suppose a node object, node, contains in its Next property the handle of the next node object, node.Next. Similarly, the Prev property contains the handle of the previous node, node.Prev. Using the three-node linked list defined in the previous section, you can demonstrate that the following statements are true:

n1.Next == n2
n2.Prev == n1

Now suppose you assign n2 to x:

x = n2;

The following two equalities are then true:

x == n1.Next
x.Prev == n1

But each instance of a node is unique so there is only one node in the list that can satisfy the conditions of being equal to n1.Next and having a Prev property that contains a handle to n1. Therefore, x must point to the same node as n2.

This means there has to be a way for multiple variables to refer to the same object. The MATLAB handle class provides a means for both x and n2 to refer to the same node. All instances of the handle class are handles that exhibit the copy behavior described previously.

Notice that the handle class defines the eq method (use methods(‘handle’) to list the handle class methods), which enables the use of the == operator with all handle objects.

[important]See Comparing Handle and Value Classes for more information on kinds of MATLAB classes.[/important]

[important]See The Handle Superclass for more information about the handle class.[/important]

Defining the dlnode Class

The following examples use this doubly linked list (see Displaying Fully Commented Example Code before using this class):

n1 = dlnode(1);
n2 = dlnode(2);
n3 = dlnode(3);
n2.insertAfter(n1)
n3.insertAfter(n2)

Class Properties

The dlnode class is itself a handle class because it is derived from the handle class. Note that only class methods can set the Next and Prev properties (SetAccess = private). Using private set access prevents client code from performing any incorrect operation with these properties. The dlnode class defines methods that perform all the operations that are allowed on these nodes. Here are the property definition blocks:

classdef dlnode < handle
   properties
      Data
   end 
   properties (SetAccess = private)
      Next
      Prev
   end 

Creating a Node Object

To create a node object, you need to specify only the node's data.

function node = dlnode(Data)
   if nargin > 0
      node.Data = Data;
   end
end

Disconnecting Nodes

When you add the node to a list, the class methods that perform the insertion set the Next and Prev properties. See Inserting Nodes.

The disconnect method removes a node from a list and repairs the list by reconnecting the appropriate nodes. The insertBefore and insertAfter methods always call disconnect on the node to insert before attempting to connect it to a linked list. This ensures the node is in a known state before assigning it to the Next or Prev property:

function disconnect(node)
   if ~isscalar(node)
      error('Nodes must be scalar')
   end
   prevNode = node.Prev;
   nextNode = node.Next;
   if ~isempty(prevNode)
      prevNode.Next = nextNode;
   end
   if ~isempty(nextNode)
      nextNode.Prev = prevNode;
   end
   node.Next = [];
   node.Prev = [];
end

For example, suppose you remove n2 from the three-node list discussed above (n1–n2–n3):

n2.disconnect;

disconnect removes n2 from the list and repairs the list with the following steps:

n1 = n2.Prev;
n3 = n2.Next;
if n1 exists, then
   n1.Next = n3;
if n3 exists, then
   n3.Prev = n1

Now the list is rejoined because n1 connects to n3 and n3 connects to n1. The final step is to ensure that n2.Next and n2.Prev are both empty (i.e., n2 is not connected):

% These properties have private SetAccess
% so they can be set only within class methods
n2.Next = [];
n2.Prev = [];

Inserting Nodes

There are two methods for inserting nodes into the list—insertAfter and insertBefore. These methods perform similar operations, so this section describes only insertAfter in detail.

methods
   function insertAfter(newNode,nodeBefore)
      disconnect(newNode);
      newNode.Next = nodeBefore.Next;
      newNode.Prev = nodeBefore;
      if ~isempty(nodeBefore.Next)
         nodeBefore.Next.Prev = newNode;
      end
      nodeBefore.Next = newNode;
   end

How insertAfter Works: First insertAfter calls the disconnect method to ensure that the new node is not connected to any other nodes. Then, it assigns the newNode Next and Prev properties to the handles of the nodes that are after and before the newNode location in the list.

For example, suppose you want to insert a new node, nnew, after an existing node, n1, in a list containing n1—n2.

First, create nnew:

nnew = dlnode(rand(3));

Next, call insertAfter to insert nnew into the list after n1:

nnew.insertAfter(n1)

The insertAfter method performs the following steps to insert nnew in the list between n1 and n2:

% n1.Next is currently n2, set nnew.Next to n1.Next (which is n2)
   nnew.Next = n1.Next; 
% nnew.Prev must be set to n1
   nnew.Prev = n1;
% if n1.Next is not empty, then
% n1.Next is still n2, so n1.Next.Prev is n2.Prev, which is set to nnew
   n1.Next.Prev = nnew; 
% n1.Next is now set to nnew
   n1.Next = nnew; 

Displaying a Node on the Command Line

All objects call a default disp function, which displays information about the object on the command line (unless display is suppressed with a semicolon). The default disp function is not useful in this case because the Next and Prev properties contain other node objects. Therefore, the dlnode class overloads the default disp function by implementing its own disp class method. This disp method displays only a text message and the value of the Data property, when used with scalar objects, and array dimensions when used with object arrays.

function disp(node)
% DISP  Display a link node
   if (isscalar(node))
      disp('Doubly-linked list node with data:')
      disp(node.Data)
   else 
      % If node is an object array, display dimensions
      dims = size(node);
      ndims = length(dims);
      % Counting down in for loop avoids need to preallocate dimcell
      for k = ndims-1:-1:1
         dimcell{k} = [num2str(dims(k)) 'x'];
      end
      dimstr = [dimcell{:} num2str(dims(ndims))];
      disp([dimstr ' array of doubly-linked list nodes']);
   end
end

Deleting a Node Object

MATLAB destroys a handle object when you reassign or delete its variable or when there are no longer any references to the object (see Handle Class Delete Methods for more information). When you define a delete method for a handle class, MATLAB calls this method before destroying the object.

The dlnode class defines a delete method because each dlnode object is a node in a doubly linked list. If a node object is going to be destroyed, the delete method must disconnect the node and repair the list before allowing MATLAB to destroy the node.

The disconnect method already performs the necessary steps, so the delete method can simply call disconnect:

Specializing the dlnode Class

function delete(node)
   disconnect(node);
end    

The dlnode class implements a doubly linked list and provides a convenient starting point for creating more specialized types of linked lists. For example, suppose you want to create a list in which each node has a name.

Rather than copying the code used to implement the dlnode class, and then expanding upon it, you can derive a new class from dlnode (i.e., subclass dlnode) to create a class that has all the features of dlnode and more. And because dlnode is a handle class, this new class is a handle class too.

The following class definition shows how to derive the NamedNode class from the dlnode class:

classdef NamedNode < dlnode
   properties
      Name = ''; % property to contain node name
   end 
   methods
      function n = NamedNode (name,data)
         if nargin == 0   % allow for the no argument case
            name = '';
            data = [];
         end
         n = n@dlnode(data); % Initialize a dlnode object
         n.Name = name;
      end 
      function disp(node) % Extend the dlnode disp method
         if (isscalar(node))
            disp(['Node Name: ' n.Name])
            disp@dlnode(node); % Call dlnode disp method
         else
            disp@dlnode(node);
         end
      end
   end % methods
end % classdef

The NamedNode class adds a Name property to store the node name and extends the disp method defined in the dlnode class.

The constructor calls the class constructor for the dlnode class, and then assigns a value to the Name property. The NamedNode class defines default values for the properties for cases when MATLAB calls the constructor with no arguments.

See Basic Structure of Constructor Methods for more information on defining class constructor methods.

Using the NamedNode Class to Create a Doubly Linked List

Use the NamedNode class like the dlnode class, except you specify a name for each node object. For example:

n(1) = NamedNode('First Node',100);
n(2) = NamedNode('Second Node',200);
n(3) = NamedNode('Third Node',300);

Now use the insert methods inherited from dlnode to build the list:

n(2).insertAfter(n(1))
n(3).insertAfter(n(2))

A single node displays its name and data when you query its properties:

>> n(1).Next
ans = 
Node Name: Second Node
Doubly-linked list node with data:
   200
>> n(1).Next.Next
ans = 
Node Name: Third Node
Doubly-linked list node with data:
   300
>> n(3).Prev.Prev
ans = 
Node Name: First Node
Doubly-linked list node with data:
   100

If you display an array of nodes, the NamedNode disp method displays only the dimensions of the array:

>> n
n = 
1x3 array of doubly-linked list nodes

Matlab Defining Classes — Syntax

classdef Syntax

Class definitions are blocks of code that are delineated by the classdef keyword at the beginning and the end keyword at the end. Files can contain only one classes definition.

The following diagram shows the syntax of a classdef block. Only comments and blank lines can precede the classdef key word.

See the following links for examples of class definitions:

  • Example — Representing Structured Data
  • Example — Implementing Linked Lists
  • Developing Classes — Typical Workflow
  • Example — A Polynomial Class

Matlab Class Overview

MATLAB User-Defined Classes

A MATLAB class definition is a template whose purpose is to provide a description of all the elements that are common to all instances of the class. Class members are the properties, methods, and events that define the class.

MATLAB classes are defined in code blocks, with sub-blocks delineating the definitions of various class members. See classdef Syntax for details on the classdef block.

Attributes for Class Members

Attributes modify the behavior of classes and the members defined in the class-definition block. For example, you can specify that methods are static or that properties are abstract, and so on. The following sections describe these attributes:

  • Class Attributes
  • Method Attributes
  • Property Attributes
  • Event Attributes

Class definitions can provide information, such as inheritance relationships or the names of class members without actually constructing the class. See Working with Meta-Classes.

[important]See Specifying Attributes for more on attribute syntax.[/important]

Kinds of Classes

There are two kinds of MATLAB classes—handle and value classes.

  • Handle classes create objects that reference the data contained. Copies refer to the same data.
  • Value classes make copies of the data whenever the object is copied or passed to a function. MATLAB numeric types are value classes.

See Comparing Handle and Value Classes for a more complete discussion.

Constructing Objects

For information on class constructors, see Class Constructor Methods

For information on creating arrays of objects, see Creating Object Arrays

Creating Class Hierarchies

For more information on how to define class hierarchies, see Building on Other Classes.

Using the Editor and Debugger with Classes

Referring to Class Files

Define classes in M-files just like scripts and functions. To use the editor or debugger with a class file, use the full class name. For example, suppose the file for a class, myclass.m is in the following location:

+PackFld1/+PackFld2/@myclass/myclass.m

To open myclass.m in the MATLAB editor, you could reference the file using dot-separated package names:

edit PackFld1.PackFld2.myclass

You could also use path notation:

edit +PackFld1/+PackFld2/@myclass/myclass

If myclass.m is not in an @-folder, then enter:

edit +PackFld1/+PackFld2/myclass

To refer to functions inside a package folder, use dot or path separators:

edit PackFld1.PackFld2.packFunction
edit +PackFld1/+PackFld2/packFunction

To refer to a function defined in its own file inside of a class @-folder, use:

edit +PackFld1/+PackFld2/@myclass/myMethod

For debugging, dbstop accepts any of the file specifications used by the edit command.

[important]See Modifying and Reloading Classes for information about clearing class.[/important]

Understanding Code Analyzer Warnings

Syntax Warnings and Property Names

The MATLAB code analyzer helps you optimize your code and avoid syntax errors while you write code. It is useful to understand some of the rules that the Code Analyzer applies in its analysis of class definition code. This understanding helps you avoid situations in which MATLAB allows code that is undesirable.

Warnings Caused by Variable/Property Name Conflicts

The Code Analyzer warns about the use of variable names in methods that match the names of properties. For example, suppose a class defines a property called EmployeeName and in this class, there is a method that uses EmployeeName as a variable:

properties
   EmployeeName
end
methods
   function someMethod(obj,n)
      EmployeeName = n;
   end
end

While the previous function is legal MATLAB code, it results in Code Analyzer warnings for two reasons:

  • The value of EmployeeName is never used
  • EmployeeName is the name of a property that is used as a variable

If the function someMethod contained the following statement instead:

obj.EmployeeName = n;

The Code Analyzer generates no warnings.

If you change someMethod to:

function EN = someMethod(obj)
   EN = EmployeeName;
end

The Code Analyzer returns only one warning, suggesting that you might actually want to refer to the EmployeeName property.

While this version of someMethod is legal MATLAB code, it is confusing to give a property the same name as a function. Therefore, the Code Analyzer provides a warning suggesting that you might have intended the statement to be:

Exception to Variable/Property Name Rule

EN = obj.EmployeeName;

Suppose you define a method that returns a value of a property and uses the name of the property for the output variable name. For example:

function EmployeeName = someMethod(obj)
   EmployeeName = obj.EmployeeName;
end

M-Lint does not warn when a variable name is the same as a property name when the variable is:

  • An input or output variable
  • A global or persistent variable

In these particular cases, M-Lint does not warn you that you are using a variable name that is also a property name. Therefore, a coding error like the following:

function EmployeeName = someMethod(obj)
   EmployeeName = EmployeeName; % Forgot to include obj.
end

[warning]
does not trigger a warning from M-Lint. [/warning]

Modifying and Reloading Classes

Ensuring MATLAB Uses Your Changes

There is only one class definition for a given class in MATLAB at any given time. When you create an instance of a class, MATLAB loads the class definition. So as long as instances of that class exist, MATLAB does not reload the class definition.

Clear Class Instances

When you modify a class definition, the current MATLAB session continues to use the original class definition until you clear all objects of that class. For example, if obj1 and obj2 are instances of a class for which you have modified the class definition, clear those objects so MATLAB can use your changes. Use the clear command to remove only those instances:

clear obj1 obj2

Modifying a class definition includes doing any of the following:

  • Changing class member attributes
  • Adding, deleting, or changing the names of properties, methods, or events
  • Changing class inheritance
  • Changing the definition of a superclass (requires you to clear subclass objects)

Clear Classes

If there are no class instances, MATLAB applies changes in the code immediately. If there are instances, you must clear those objects before MATLAB applies your changes.

When you issue the clear classes command, MATLAB clears:

  • The current workspace of all variables
  • All functions, which can have persistent variables holding class instances (unless the function is locked)
  • All classes that are not instantiated

However, it is possible that your MATLAB session is holding instances of the class that the clear classes command does not clear. For example, suppose you change the definition of MyClass after saving an instance of this class in a Handle Graphics® object’s UserData property:

obj = MyClass; % User-defined class that you are editing
h = uicontrol('Style','pushbutton');
set(h,'UserData',obj)
clear classes
Warning: Objects of 'MyClass' class exist. Cannot clear this class or any of its
super-classes.

MATLAB issues a warning stating that it cannot apply your changes because it cannot clear the class. Clear the instance of MyClass before calling clear classes. For example, you can use the close all command to remove the object or reset the UserData property to another value:

% First, get the handle of the uicontrol, which was cleared
h = findobj('Type','uicontrol','Style','pushbutton');
set(h,'UserData',[])

[help]Now you can issue the clear classes command.[/help]

Places That Can Hold Instances

You can remove class instances from your workspace using the clear obj… command. However, as the preceding example shows, objects can be held in various ways. Clear all instances before MATLAB applies your new class definition.

Here are some suggestions for finding and clearing class instances:

Persistent Variables: Persistent variables can hold objects. Clear persistent variables using clear functions. If the function containing the persistent variable is locked, then unlock the function (using munlock) before clearing it.

Locked Functions: Functions can contain objects in their workspace. If the function is locked (with mlock), unlock it (using munlock) so that MATLAB can clear the instance. Use clear functions once you have unlocked the function.

Default Property Values: When you specify a default value in a properties definition block, MATLAB evaluates the expression that defines the default value once when loading the class. Clear this value using the clear classes command.

Constant Properties: When you define a constant property (property Constant attribute set to true) whose value is an object, MATLAB creates the instance when loading the class. Clear this instance using the clear classes command.

Handle Graphics Objects: Handle Graphics objects can contain class instances in UserData properties, in Application Data, or created in callback functions. Issuing the close all command removes the Handle Graphics objects, unless these objects enable hidden handles. See the close command for more information. You can remove Application Data using the rmappdata function.

Simulink Models: Models can contain class instances. Use close_system to close the model so that MATLAB can apply your changes.

Example of Class Definition Syntax

Example of Class Definition Syntax

The following code shows the syntax of a typical class definition. This example is not a functioning class because it references functions that it does not implement. The purpose of this section is to illustrate various syntactic constructions.

classdef (ConstructOnLoad) employee < handle
   % Class help goes here
   properties
      Name % Property help goes here
   end 

   properties (Dependent)
      JobTitle
   end 

   properties (Transient)
      OfficeNumber
   end 

   properties (SetAccess = protected, GetAccess = private)
      EmpNumber
   end 

   events
      BackgroundAlert
   end 

   methods
      function Eobj = employee(name)
         % Method help here
            Eobj.Name = name;
            Eobj.EmpNumber = employee.getEmpNumber;
      end

      function result = backgroundCheck(obj)
         result = queryGovDB(obj.Name,obj.SSNumber);
           if result == false
              notify(obj,'BackgroundAlert');
           end
      end

      function jobt = get.JobTitle(obj)
         jobt = currentJT(obj.EmpNumber);
      end

      function set.OfficeNumber(obj,setvalue)
         if isInUse(setvalue)
            error('Not available')
         else
            obj.OfficeNumber = setvalue;
         end
      end
   end

   methods (Static)
      function num = getEmpNumber
         num = queryDB('LastEmpNumber') + 1;
      end
   end
end

Calling Superclass Methods on Subclass Objects

Calling a Superclass Constructor

If you create a subclass object, MATLAB calls the superclass constructor to initialize the superclass part of the subclass object. By default, MATLAB calls the superclass constructor without arguments. If you want the superclass constructor called with specific arguments, explicitly call the superclass constructor from the subclass constructor. The call to the superclass constructor must come before any other references to the object.

The syntax for calling the superclass constructor uses an @ symbol:

classdef MySub < MySuperClass
   function obj = MySub(arg1,arg2,...)
      obj = obj@MySuperClass(SuperClassArguments);
         ...
   end
end

Interpret this syntax as meaning, the MySub object arrives at the MySuperClass constructor , which constructs the MySuperClass part of the object using the specified arguments.

See Constructing Subclasses for more information.

Calling Superclass Methods

You can call a superclass method from a subclass method if both methods have the same name. From the subclass, reference the method name and superclass name with the @ symbol. See Modifying Superclass Methods for more information on when to call superclass methods.

For example, a subclass can call a superclass disp method to implement the display of the superclass part of the object, and then add code to display the subclass part:

classdef MySub < MySuperClass 
   function disp(obj)
      disp@MySuperClass(obj)
         ...
   endend

This diagram illustrates how to call the superMethod defined at MySuperClass.

Syntax Reference & Specifying Attributes

Attribute Syntax

For a quick reference to all attributes, see Attribute Tables.

Attributes modify the behavior of classes and class components (properties, methods, and events). Attributes enable you to define useful behaviors without writing complicated code. For example, you can create a read-only property by setting its SetAccess attribute to private, but leaving its GetAccess attribute set to public (the default):

properties (SetAccess = private)
   ScreenSize = getScreenSize;
end

All class definition blocks (classdef, properties, methods, and events) support specific attributes and all attributes have default values. Specify attribute values only in cases where you want to change from the default value to another predefined value.

Attribute Descriptions

For lists of supported attributes, see:

  • Class Attributes
  • Property Attributes
  • Method Attributes
  • Event Attributes
  • Specifying Attribute Values

When you specify attribute values, these values affect all the components defined within the definition block. For example, the following property definition blocks set the:

  • AccountBalance property SetObservable attribute to true
  • SSNumber and CreditCardNumber properties’ Hidden attribute to true and SetAccess attribute to private.

Defining properties with different attribute settings requires multiple properties blocks.

properties (SetObservable = true) 
   AccountBalance
end
properties (SetAccess = private, Hidden = true)
   SSNumber
   CreditCardNumber
end

Specified multiple attributes in a comma-separated list, as shown in the previous example.

When specifying class attributes, place the attribute list directly after the classdef keyword:

Simpler Syntax for true/false Attributes

classdef (Sealed = true) myclass
   ...
end

You can use a simpler syntax for attributes whose values are true or false — the attribute name alone implies true and adding the not operator (~) to the name implies false. For example:

methods (Static)
   ...
end

is the same as:

methods (Static = true)
   ...
end

Use the not operator before an attribute name to define it as false:

is the same as:

methods (~Static) 
   ...
end

All attributes that take a logical value (that is, true or false) have a default value of false. Therefore, specify an attribute only if you want to set it to true.

methods (Static = false)
   ...
end

Matlab Events and Listeners

Specifying Events

To define an event, you declare a name for the event in the events block. Then one of the class methods triggers the event using the notify method, which is method inherited from the handle class. Only classes derived from the handle class can define events.

For example, the following class:

  • Defines an event named StateChange
  • Triggers the event using the inherited notify method.
  • classdef class_name < handle % Subclass handle
       events % Define an event called StateChange
          StateChange
       end
       ...
       methods
          function upDateGUI(obj)
             ...
             % Broadcast notice that StateChange event has occurred
             notify(obj,'StateChange');
          end
       end
    end

    Listening for Events

Any number of objects can be listening for the StateChange event to occur. When notify executes, MATLAB calls all registered listener callbacks and passes the handle of the object generating the event and an event structure to these functions. To register a listener callback, use the addlistener method of the handle class.

addlistener(event_obj,'StateChange',@myCallback)

[important]See Defining Events and Listeners — Syntax and Techniques[/important]

Matlab Syntax Reference & Specifying Methods and Functions

The Methods Block

Define methods as MATLAB functions within a methods block, inside the classdef block. The constructor method has the same name as the class and returns an object. You can assign values to properties in the class constructor. Terminate all method functions with an end statement.

classdef ClassName
   methods
      function obj = ClassName(arg1,arg2,...)
         obj.Prop1 = arg1;
         ...
      end
      function normal_method(obj,arg1,...)
         ...
      end
   end
   methods (Static = true)
      function static_method(arg1,...)
         ...
      end
   end
end

Method Calling Syntax

MATLAB differs from languages like C++ and Java™ in that there is no special hidden class instance passed to all methods. You must pass an object of the class explicitly to the method. The left most argument does not need to be the class instance, and the argument list can have multiple objects.

See Determining Which Method Is Invoked for more information.

See alsoStatic Methods for information on methods that do not require instances of their class.

[warning]Always use case sensitive method names in your MATLAB code.[/warning]

Methods In Separate Files

You can define class methods in files that are separate from the class definition file, with certain exceptions (see Methods That Must Be In the classdef File). To use multiple files for a class definition, put the class files in a folder having a name beginning with the @ character followed by the name of the class. Ensure that the parent folder of the @-folder is on the MATLAB path.

For example, the folder @MyClass must contain the file MyClass.m (which contains the classdef block) and can contain other methods and function defined in files having a .m extension. For example, the folder @MyClass might contain a number of files:

@MyClass/MyClass.m
@MyClass/subsref.m
@MyClass/subsasgn.m
@MyClass/horzcat.m
@MyClass/vertcat.m
@MyClass/myFunc.m

To define a method in a separate file in the class @-folder, create the function in a separate file, but do not use a method block in that file. Name the file with the function name, as with any function.

You must put the following methods in the classdef file, not in separate files:

  • Class constructor
  • Delete method

All functions that use dots in their names, including:

  • Converter methods that convert to classes contained in packages, which must use the package name as part of the class name.
  • Property set and get access methods (Property Access Methods)

If you specify method attributes for a method that you define in a separate file, include the method signature in a methods block in the classdef block. For example, the following code shows a method with Access set to private in the methods block. The method implementation resides in a separate file. Do not include the function or end keywords in the methods block, just the function signature showing input and output arguments.

classdef ClassName
% In a methods block, set the method attributes
% and add the function signature
   methods (Access = private)
      output = myFunc(obj,arg1,arg2)
   end
end

In a file named myFunc.m, in the @ClassName folder, define the function:

function output = myFunc(obj,arg1,arg2)
   ...
end

Include the method signature in the file with the classdef block only if you want to specify attributes for that method. Otherwise, you can implement the method as a function in a separate file in the @-folder.

To create a static method, set the function’s Static attribute to true. List any static methods that you define in separate files in the @-class folder. List these methods in the static methods block in the classdef file. Include the input and output arguments with the function name. For example:

classdef ClassName
...
   methods (Static)
      output = staticFunc1(arg1,arg2)
      staticFunc2
   end

You would then define the functions in separate files using the same function signature. For example:

function output = staticFunc1(arg1,arg2)
   ...
end

The example, Example — Using Events to Update Graphs uses multiple files for class definition.

Defining Private Methods

Use the Access method attribute to create a private method. You do not need to use a private folder.

[important]See Method Attributes for a list of method attributes.[/important]

More Detailed Information On Methods

See Class Methods for more information about methods.

Defining Class-Related Functions

You can define functions that are not class methods in the file that contains the class definition (classdef). Define subfunctions outside of the classdef – end block, but in the same file as the class definition. Subfunctions defined in classdef files work like subfunctions. You can call these subfunctions from anywhere in the same file, but they are not visible outside of the file in which you define them.

Subfunctions in classdef files are useful for utility functions that you use only within that file. These functions can take or return arguments that are instances of the class but, it is not necessary, as in the case of ordinary methods. For example, the following code defines myUtilityFcn outside the classdef block:

classdef MyClass
   properties
      PropName
   end
   methods
      function obj = MyClass(arg1)
         obj.PropName = arg1;
      end 
   end % methods
end % classdef
function myUtilityFcn
   ...
end

You also can create package functions, which require you to use the package name when calling these functions. See Scoping Classes with Packages for more information on packages

Class Definition-Syntax Reference & Specifying Properties

What You Can Define

You can control aspects of property definitions in the following ways:

  • Specifying a default value for each property individually
  • Assigning attribute values on a per block basis
  • Defining methods that execute when the property is set or queried

Note Always use case sensitive property names in your MATLAB code.

How to Initialize Property Values

There are two basic approaches to initializing property values:

  • In the property definition — MATLAB evaluates the expression only once and assigns the same value to the property of every instance. See Defining Default Values.
  • In the class constructor — MATLAB evaluates the assignment expression for each instance, which ensures that each instance has a unique value. See Assigning Property Values from Within the Constructor.
  • Defining Default Values

Within a properties block, you can control an individual property’s default value. Default values can be constant values or MATLAB expressions. Expressions cannot reference variables. For example:

classdef class_name
   properties
      PropertyName % No default value assigned
      PropertyName = 'some text'; 
      PropertyName = sin(pi/12); % Expression returns default value
   end
end

Evaluation of property default values occurs only when the value is first needed, and only once when MATLAB first initializes the class. MATLAB does not reevaluate the expression each time you create a class instance.

See Using Expressions in Class Definitions for more information on how MATLAB evaluates expressions that you use to assign property default values.

MATLAB sets property values not specified in the class definition to empty ([]).

Assigning Property Values from Within the Constructor

To assign values to a property from within the class constructor, reference the object that the constructor returns (the output variable obj):

classdef MyClass
   properties
      PropertyOne 
   end
   methods
      function obj = MyClass(intval)
         obj.PropertyOne = intval;
      end
   end
end

When you assign an object property from the class constructor, MATLAB evaluates the assignment statement for each instance created. Assign property values in the constructor if you want each object to contain a unique instance of a handle object.

[important]See Referencing the Object in a Constructor for more information on constructor methods.[/important]

Initializing Properties to Unique Values

MATLAB assigns properties to the specified default values only once when MATLAB loads the class definition. Therefore, if you initialize a property value with a handle-class constructor, MATLAB calls this constructor only once and every instance references the same handle object. If you want a property value to be initialized to a new instance of a handle object each time you create an object, assign the property value in the constructor.

Property Attributes

All properties have attributes that modify certain aspects of the property’s behavior. Specified attributes apply to all properties in a particular properties block. For example:

classdef class_name
   properties
      PropertyName % No default value assigned
      PropertyName = sin(pi/12); % Expression returns default value
   end
   properties (SetAccess = private, GetAccess = private)
      Stress
      Strain
   end
end

In this case, only methods in the same class definition can modify and query the Stress and Strain properties. This restriction exists because the class defines these properties in a properties block with SetAccess and GetAccess attributes set to private.

Table of Property Attributes provides a description of property attributes.

Property Access Methods

You can define methods that MATLAB calls whenever setting or querying a property value. Define property set access or get access methods in methods blocks that specify no attributes and have the following syntax:

methods
   function value = get.PropertyName(object)
      ...
   end

   function obj = set.PropertyName(obj,value)
      ...
   end
end

MATLAB does not call the property set access method when assigning the default value specified in the property’s definition block.

If a handle class defines the property, the set access method does not need to return the modified object.

Property Access Methods for more information on these methods.

Defining Properties for information on properties.

Referencing Object Properties Using Variables

MATLAB can resolve a property name from a char variable using an expression of the form:

object.(PropertyNameVar)

where PropertyNameVar is a variable containing the name of a valid object property. Use this syntax when passing property names as arguments:

PropName = 'KeyType';
function o = getPropValue(obj,PropName)
   ...
   o = obj.(PropName); % Returns value of KeyType property
   ...
end

Matlab Class Definition & The Classdef Block

Specifying Attributes and Superclasses

The classdef block contains the class definition. The classdef line is where you specify:

  • Class attributes
  • Superclasses

The classdef block contains the properties, methods, and events subblocks.

Assigning Class Attributes

Class attributes modify class behavior in some way. Assign values to class attributes only when you want to change their default value.

No change to default attribute values:

classdef class_name
   ...
end

One or more attribute values assigned:

classdef (attribute1 = value,...)
   ...
end

See Class Attributes for a list of attributes and a discussion of the behaviors they control.

Specifying Superclasses

To define a class in terms of one or more other classes by specifying the superclasses on the classdef line:

classdef class_name < superclass_name
   ...
end

See Creating Subclasses — Syntax and Techniques for more information.

Matlab Syntax Reference & Class Components

Class Building Blocks

The basic components in the class definition are blocks describing the whole class and specific aspects of its definition:

classdef block contains the class definition within a file that starts with the classdef keyword and terminates with the end keyword. See The Classdef Block for more syntax information.

classdef ClassName
   ...
end

properties block (one for each unique set of attribute specifications) contains property definitions, including optional initial values. The properties block starts with the properties keyword and terminates with the end keyword. See Specifying Properties for more syntax information.

classdef ClassName
   properties
      ...
   end
   ...
end

methods block (one for each unique set of attribute specifications) contains function definitions for the class methods. The methods block starts with the methods keyword and terminates with the end keyword. See The Methods Block for more syntax information.

classdef ClassName
   methods
      ...
   end
   ...
end

events block (one for each unique set of attribute specifications) contains the names of events that this class declares. The events blocks starts with the events keyword and terminates with the end keyword. See Specifying Events for more syntax information.

classdef ClassName
   events
      ...
   end
   ...
end

properties, methods, and events are keywords only within a classdef block.

More In Depth Information

Defining Classes — Syntax for more detail on class syntax.

Defining Properties for information on specifying properties.

Class Methods for information on specifying methods.

Defining Events and Listeners — Syntax and Techniques for information on the use of events.

Attribute Tables for a list of all attributes.

Class Definition-Syntax Reference & Class Folders

Options for Class Folders

There are two basic ways to specify classes with respect to folders:

  • Creating a single, self-contained class definition file in a folder on the MATLAB path.
  • Distributing a class definition to multiple files in an @ folder inside a path folder.

Creating a Single, Self-Contained Class Definition File

Create a single, self-contained class definition file in a folder on the MATLAB® path. The name of the file must match the class (and constructor) name and must have the .m extension. Define the class entirely in this file. You can put other single-file classes in this folder.

The following diagram shows an example of this folder organization. pathfolder is a directory on the MATLAB path.

See Methods in Separate Files for more information on using multiple files to define classes.

Distributing the Class Definition to Mulitple Files

If you use multiple files to define a class, put all the class-definition files (the file containing the classdef and all class method files) in a single @ClassName folder. That @-folder must be inside a folder that is on the MATLAB path. You can define only one class in an @-folder.

A path folder can contain classes defined in both @-folders and single files without an @-folder.

Grouping Classes with Package Folders

The parent folder to a package folder is on the MATLAB path, but the package folder is not. Package folders (which always begin with a “+” character) can contain multiple class definitions, package-scoped functions, and other packages. A package folder defines a new name space in which you can reuse class names. Use the package name to refer to classes and functions defined in package folders (for example, packagefld1.ClassNameA(), packagefld2.packageFunction()).

More Information on Class Folders

[note]See Organizing Classes in Folders for more information on class folders and see Scoping Classes with Packages for information on using classes contained in package folders[/note].

[important]See Methods In Separate Files for the syntax used to define methods external to the classdef file.[/important]

Why Use Object-Oriented Design

Approaches to Writing MATLAB Programs

Creating software applications typically involves designing how to represent the application data and determining how to implement operations performed on that data. Procedural programs pass data to functions, which perform the necessary operations on the data. Object-oriented software encapsulates data and operations in objects that interact with each other via the object’s interface.

The MATLAB language enables you to create programs using both procedural and object-oriented techniques and to use objects and ordinary functions in your programs.

Procedural Program Design

In procedural programming, your design focuses on steps that must be executed to achieve a desired state. You typically represent data as individual variables or fields of a structure and implement operations as functions that take the variables as arguments. Programs usually call a sequence of functions, each one of which is passed data, and then returns modified data. Each function performs an operation or perhaps many operations on the data.

Object-Oriented Program Design

The object-oriented program design involves:

  • Identifying the components of the system or application that you want to build
  • Analyzing and identifying patterns to determine what components are used repeatedly or share characteristics
  • Classifying components based on similarities and differences

After performing this analysis, you define classes that describe the objects your application uses.

Classes and Objects

A class describes a set of objects with common characteristics. Objects are specific instances of a class. The values contained in an object’s properties are what make an object different from other objects of the same class (an object of class double might have a value of 5). The functions defined by the class (called methods) are what implement object behaviors that are common to all objects of a class (you can add two doubles regardless of their values).

Using Objects in MATLAB Programs

The MATLAB language defines objects that are designed for use in any MATLAB code. For example, consider the try-catch programming construct.

If the code executed in the try block generates an error, program control passes to the code in the catch block. This behavior enables your program to provide special error handling that is more appropriate to your particular application. However, you must have enough information about the error to take the appropriate action.

MATLAB provides detailed information about the error by passing an MException object to functions executing the try-catch blocks.

The following try-catch blocks display the error message stored in an MException object when a function (surf in this case) is called without the necessary arguments:

try
   surf
catch ME
   disp(ME.message)
end
Not enough input arguments.

In this code, ME is an object of the MException class, which is returned by the catch statement to the function’s workspace. Displaying the value of the object’s message property returns information about the error (the surf function requires input arguments). However, this is not all the information available in the MException object.

You can list the public properties of an object with the properties function:

properties(ME)
Properties for class MException:
    identifier
    message
    cause
    stack

Objects Organize Data

The information returned in an MException object is stored in properties, which are much like structure fields. You reference a property using dot notation, as in ME.message. This reference returns the value of the property. For example,

class(ME.message)
ans =
char

shows that the value of the message property is an array of class char (a text string). The stack property contains a MATLAB struct:

ME.stack
ans = 
    file: 'U:\bat\A\perfect\matlab\toolbox\matlab\graph3d\surf.m'
    name: 'surf'
    line: 50

You can simply treat the property reference, ME.stack as a structure and reference its fields:

ME.stack.file
ans =
D:\myMATLAB\matlab\toolbox\matlab\graph3d\surf.m

The file field of the struct contained in the stack property is a character array:

class(ME.stack.file)
ans =
char

You could, for example, use a property reference in MATLAB functions:

strcmp(ME.stack.name,'surf')
ans =
     1

Object properties can contain any class of value and can even determine their value dynamically. This provides more flexibility than a structure and is easier to investigate than a cell array, which lacks fieldnames and requires indexing into various cells using array dimensions.

Objects Manage Their Own Data

You could write a function that generates a report from the data returned by MException object properties. This function could become quite complicated because it would have to be able to handle all possible errors. Perhaps you would use different functions for different try-catch blocks in your program. If the data returned by the error object needed to change, you would have to update the functions you have written to use the new data.

Objects provide an advantage in that objects define their own operations. A requirement of the MException object is that it can generate its own report. The methods that implement an object’s operations are part of the object definition (i.e., specified by the class that defines the object). The object definition might be modified many times, but the interface your program (and other programs) use does not change. Think of your program as a client of the object, which isolates your code from the object’s code.

To see what methods exist for MException objects, use the methods function:

methods(ME)
Methods for class MException:

addCause    eq          isequal     rethrow     throwAsCaller  
disp        getReport   ne          throw          

Static methods:
last   

You can use these methods like any other MATLAB statement when there is an MException object in the workspace. For example:

ME.getReport
ans =
??? Error using ==> surf at 50
Not enough input arguments.

Objects often have methods that overload (redefined for the particular object) MATLAB functions (e.g., isequal, fieldnames, etc.). This enables you to use objects just like other values. For example, MException objects have an isequal method. This method enables you to compare these objects in the same way you would compare variables containing doubles. If ME and ME2 are MException objects, you can compare them with this statement:

isequal(ME,ME2)

However, what really happens in this case is MATLAB calls the MException isequal method because you have passed MException objects to isequal.

Similarly, the eq method enables you to use the == operator with MException objects:

ME == ME2

Of course, objects should support only those methods that make sense. For example, it would probably not make sense to multiply MException objects so the MException class does not implement methods to do so.

When Should You Start Creating Object-Oriented Programs

Objects are well integrated into the MATLAB language, regardless of whether you are writing simple functions, working interactively in the command window, or creating large applications.

Simple programming tasks are easily implemented as simple functions, but as the magnitude and complexity of your tasks increase, functions become more complex and difficult to manage.

As functions become too large, you might break them into smaller functions and pass data from one to the other. However, as the number of functions becomes large, designing and managing the data passed to functions becomes difficult and error prone. At this point, you should consider moving your MATLAB programming tasks to object-oriented designs.

Thinking in terms of things or objects is simpler and more natural for some problems. You might think of the nouns in your problem statement as the objects you need to define and the verbs as the operations you must perform.

For example, consider performing an analysis of economic institutions. It would be difficult to represent the various institutions as procedures even though they are all actors in the overall economy. Consider banks, mortgage companies, credit unions. You can represent each institution as an object that performs certain actions and contains certain data. The process of designing the objects involves identifying the characteristics of these institutions that are important to your application.

Identify Commonalities. All of these institutions belong in the general class of lending institutions, so all objects might provide a loan operation and have a Rate property that stores the current interest rate.

Identify Differences. You must also consider how each institution differs. A mortgage company might provide only home mortgage loans. Therefore, the loan operation might need be specialized for mortgage companies to provide fixRateLoan and varRateLoan methods to accommodate two loan types.

Consider Interactions. Institutions can interact, as well. For example, a mortgage company might sell a mortgage to a bank. To support this activity, the mortgage company object would support a sellMortgage operation and the bank object would support a buyMortgage operation.

You might also define a loan object, which would represent a particular loan. It might need Amount, Rate, and Lender properties. When the loan is sold to another institution, the Lender property could be changed, but all other information is neatly packaged within the loan object.

Add Only What Is Necessary. It is likely that these institutions engage in many activities that are not of interest to your application. During the design phase, you need to determine what operations and data an object needs to contain based on your problem definition.

Managing Data. Objects encapsulate the model of what the object represents. If the object represents a kind of lending institution, all the behaviors of lending institutions that are necessary for your application are contained by this object. This approach simplifies the management of data that is necessary in a typical procedural program.

Objects Manage Internal State

In the simplest sense, objects are data structures that encapsulate some internal state, which you access via its methods. When you invoke a method, it is the object that determines exactly what code to execute. In fact, two objects of the same class might execute different code paths for the same method invocation because their internal state is different. The internal workings of the object need not be of concern to your program — you simply use the interface the object provides.

Hiding the internal state from general access leads to more robust code. If a loan object’s Lender property can be changed only by the object’s newLender method, then inadvertent access is less likely than if the loan data were stored in a cell array where an indexing assignment statement could damage the data.

Objects provide a number of useful features not available from structures and cell arrays. For example, objects provide the ability to:

  • Constrain the data assigned to any given property by executing a function to test values whenever an assignment is made
  • Calculate the value of a property only when it is queried and thereby avoid storing data that might be dependent on the state of other data
  • Broadcast notices when any property value is queried or changed, to which any number of listeners can respond by executing functions
  • Restrict access to properties and methods

Reducing Redundancy

As the complexity of your program increases, the benefits of an object-oriented design become more apparent. For example, suppose you need to implement the following procedure as part of your application:

  • Check inputs
  • Perform computation on the first input argument
  • Transform the result of step 2 based on the second input argument
  • Check validity of outputs and return values

This simple procedure is easily implemented as an ordinary function. But now suppose you need to use this procedure again somewhere in your application, except that step 2 must perform a different computation. You could simply copy and paste the first implementation, and then rewrite step 2. Or you could create a function that accepted an option indicating which computation to make, and so on. However, these options lead to more and more complicated code.

An object-oriented design could result in a simpler solution by factoring out the common code into what is called a base class. The base class would define the algorithm used and implement whatever is common to all cases that use this code. Step 2 could be defined syntactically, but not implemented, leaving the specialized implementation to the classes that you then derive from this base class.

Step 1
function checkInputs()
   % actual implementation
end

Step 2
function results = computeOnFirstArg()
   % specify syntax only
end

Step 3
function transformResults()
   % actual implementation
end
 
Step 4
function out = checkOutputs()
   % actual implementation
end

The code in the base class is not copied or modified, it is inherited by the various classes you derive from the base class. This reduces the amount of code to be tested, and isolates your program from changes to the basic procedure.

Defining Consistent Interfaces

The use of a class as the basis for similar, but more specialized classes is a useful technique in object-oriented programming. This class is often called an interface class. Incorporating this kind of class into your program design enables you to:

  • Identify the requirements of a particular objective
  • Encode these requirements into your program as an interface class

For example, suppose you are creating an object to return information about errors that occur during the execution of specific blocks of code. There might be functions that return special types of information that you want to include in an error report only when the error is generated by these functions.

The interface class, from which all error objects are derived, could specify that all error objects must support a getReport method, but not specify how to implement that method. The class of error object created for the functions returning special information could implement its version of the getReport method to handle the different data.

The requirement defined by the interface class is that all error objects be able to display an error report. All programs that use this feature can rely on it being implement in a consistent way.

All of the classes derived from the interface class can create a method called getReport without any name conflicts because it is the class of the object that determines which getReport is called.

Reducing Complexity

Objects reduce complexity by reducing what you need to know to use a component or part of a system. This happens in a couple of ways:

  • Implementation details are hidden behind the interfaces defined by objects.
  • Rules controlling how objects interact are enforced by object design and, therefore, not left to object users to enforce.

To illustrate these advantages, consider the implementation of a data structure called a doubly linked list.

To add a new node to the list, the following steps must occur. First disconnect the nodes:

  • Unlink n2.Prev from n1
  • Unlink n2.Next from n3
  • Unlink n3.Prev from n2
  • Unlink n1.Next from n2


Now connect the new node and renumber:

  • Link new.Prev to n1
  • Link new.Next to n3 (was n2)
  • Link n1.Next to new (will be n2)
  • Link n3.Prev to new (will be n2)


The act of inserting a new node in an existing doubly linked list requires a number of steps. Any application code using a data structure like this can perform these operations. However, defining the linked list nodes as objects enables all the operations like adding, deleting, and rearranging nodes to be encapsulated in methods. The code that implements these operations can be well tested, implemented in an optimal way, always up to date with the current version of the class, and can even automatically update old-versions of the objects when they are loaded from MAT-files.

The objects enforce the rules for how the nodes interact by implementing methods to carry out these operations. A single addNode method would perform all the steps listed above. This removes the responsibility for enforcing constraints from the applications that use the objects. It also means the application is less likely to generate errors in its own implementation of the process.

This approach can reduce the complexity of your application code, provide greater consistency across applications, and reduce testing and maintenance requirements.

As you decompose a system into objects (car –> engine –> fuel system –> oxygen sensor), you form modules around natural boundaries. These objects provide interfaces by which they interact with other modules (which might be other objects or functions). Often the data and operations behind the interface are hidden from other modules to segregate implementation from interface.

Classes provide three levels of control over code modularity:

  • Public — Any code can access this particular property or call this method.
  • Protected — Only the object’s own methods and those of the object’s whose class has been derived from this object’s class can access this property or call this method.
  • Private — Only the object’s own methods can access this property or call this method.

When you define a class, you can overload existing MATLAB functions to work with your new object. For example, the MATLAB serial port class overloads the fread function to read data from the device connected to the port represented by this object. You can define various operations, such as equality (eq) or addition (plus), for a class you have defined to represent your data.

Suppose your application requires a number of dialog windows to interact with users. By defining a class containing all the common aspects of the dialog windows, and then deriving the specific dialog classes from this base class, you can:

  • Reuse code that is common to all dialog window implementations
  • Reduce code testing effort due to common code
  • Provide a common interface to dialog developers
  • Enforce a consistent look and feel
  • Apply global changes to all dialog windows more easily

[important]See MATLAB Classes to learn more about writing object-oriented MATLAB programs.[/important]

Adding Text Annotations to Graphs

What Are Text Annotations?

Text annotations are boxes containing text strings that you compose. The box can have a border and a background, or be invisible. The text can be in any installed text font, and can include TeX or LaTeX markup. You can add free-form text annotations anywhere in a MATLAB figure to help explain your data or bring attention to specific points in your data sets.

As the following example shows, annotating a graph manually is easy in plot edit mode. When you enable plot editing, you can create text annotations by selecting the appropriate kind of annotation from the Insert menu, clicking in the graph or the figure background and then entering text. To insert textarrow annotations, you first drag out an arrow from tail to head, then type the text at the text cursor next to the tail,

You can also add text annotations from the command line, using the text or gtext function. The example illustrates how to use text.

Using plot editing mode or gtext makes it easy to place a text annotation where you want in a graph. Use the text function when you want to position a text annotation at a specific point within an axes for which you know the coordinates.

[warning]Text annotations created using the text or gtext function are anchored to the axes. Text annotations created in plot edit mode are not. If you move or resize your axes, you will have to reposition your text annotations. For more information, see Positioning Annotations in Data Space.[/warning]

Creating Text Annotations with the text or gtext Function

To create a text annotation using the text function, you must specify the text and its location within the axes, providing the x- and y-coordinates in the same Units that the graph uses (pixels, normalized, etc.).

Use the gtext function when you want to position a text annotation at a specific point in the data space with the mouse.

The following example adds text annotation, a title, and a legend to a graph of output from the Lotka-Volterra predator-prey population model. It also illustrates how to create multiline text annotations using cell arrays (also see the following section Text in Cell Arrays).

% Define initial conditions
t0 = 0;
tfinal = 15;
y0 = [20 20]';
% Simulate the differential equation
tfinal = tfinal*(1+eps);
[t,y] = ode23('lotka',[t0 tfinal],y0);
% Plot the two curves, storing handles to them
% so their DisplayNames can be set
hlines = plot(t,y);
% Compose and display two multiline text
% annotations as cell arrays
str1(1) = {'Many Predators;'};
str1(2) = {'Prey Population'};
str1(3) = {'Will Decline'};
text(7,220,str1)
str2(1) = {'Few Predators;'};
str2(2) = {'Prey Population'};
str2(3) = {'Will Increase'};
text(5.5,125,str2)
% Set DisplayNames for the lines for use by the legend
set(hlines(1),'Displayname','Prey')
set(hlines(2),'Displayname','Predator')
% Center a legend at the top of the graph
legend('Location','north')
% Add a title with bold style
title('Lotka-Volterra Predator-Prey Population Model',... 
  'FontWeight','bold')

To connect the text with the appropriate points on the plot, draw two annotation arrows by hand. First enter plot edit mode, either by typing

plotedit

in the Command Window or by clicking the Edit Plot icon in the figure toolbar. (Type plotedit again or click the icon again when you want to exit plot edit mode.)

Select Arrow from the Insert menu. Draw an arrow from each block of text to point to the lines, as shown here.

Calculating the Positions of Text Annotations

You can also calculate the positions of text annotations in a graph. The following code adds annotations at three data points on a graph.

t=0:pi/64:2*pi; 
plot(t,sin(t)); 
title('The Sine of 0 to 2\pi')
xlabel('t = 0 to 2\pi')
ylabel('sin(t)')

text(3*pi/4,sin(3*pi/4),...
     '\leftarrowsin(t) = .707',...
     'FontSize',16)

text(pi,sin(pi),'\leftarrowsin(t) = 0',...
     'FontSize',16)

text(5*pi/4,sin(5*pi/4),'sin(t) = -.707\rightarrow',... 
     'HorizontalAlignment','right',...
     'FontSize',16)

The HorizontalAlignment of the text string ‘sin(t) = -.707 \rightarrow’- is set to right to place it on the left side of the point [5*pi/4,sin(5*pi/4)] on the graph. For more information about aligning text annotations, see Text Alignment.

[help]Defining Symbols. For information on using symbols in text strings, see Mathematical Symbols, Greek Letters, and TEX Characters.[/help]

You can use text objects to annotate axes at arbitrary locations. Text is positioned using the data units of the axes. For example, suppose you plot the function y=Ae-αt with A = 0.25, α = 0.005, and t = 0 to 900.

t = 0:900;
plot(t,0.25*exp(-0.005*t))
xlabel('Time \musec')
ylabel('Amplitude')
title('\itAe^\alpha^t')


To annotate the point where the value of t = 300, calculate the text coordinates using the function you are plotting.

text(300,.25*exp(-0.005*300),...
title('\itAe^\alpha^t')['\bullet\leftarrow\...
fontname{times}0.25{\ite}^{-0.005{\itt}}' ...
' at {\itt} = 300'],'FontSize',14)

This statement defines the text Position property as

x = 300, y = 0.25e-0.005 × 300

The default text alignment places this point to the left of the string and centered vertically with the rectangle defined by the text Extent property. The following section provides more information about changing the default text alignment.

Text Alignment

The HorizontalAlignment and the VerticalAlignment properties control the placement of the text characters with respect to the specified x-, y-, and z-coordinates. The following diagram illustrates the options for each property and the corresponding placement of the text.

The default alignment is

  • HorizontalAlignment = ‘left’
  • VerticalAlignment = ‘middle’

The text String is not placed exactly on the specified Position. For example, the previous section showed a plot with a point annotated with text. Zooming in on the plot enables you to see the actual positioning of the text.

The small dot is the point specified by the text Position property. The larger dot is the bullet defined as the first character in the text String property.

Example — Aligning Text

Suppose you want to label the minimum and maximum values in a plot with text that is anchored to these points and that displays the actual values. This example uses the plotted data to determine the location of the text and the values to display on the graph. One column from the peaks matrix generates the data to plot.

Z = peaks;
h = plot(Z(:,33));

The first step is to find the indices of the minimum and maximum values to determine the coordinates needed to position the text at these points (get, find). Then create the string by concatenating the values with a description of what the values are.

x = get(h,'XData'); 		% Get the plotted data
y = get(h,'YData');
imin = find(min(y) == y);		% Find the index of the min and max
imax = find(max(y) == y);
text(x(imin),y(imin),[' Minimum = ',num2str(y(imin))],...
	'VerticalAlignment','middle',...
	'HorizontalAlignment','left',...
	'FontSize',14)
text(x(imax),y(imax),['Maximum =  ',num2str(y(imax))],...
	'VerticalAlignment','bottom',...
	'HorizontalAlignment','right',...
	'FontSize',14)


The text function positions the string relative to the point specified by the coordinates, in accordance with the settings of the alignment properties. For the minimum value, the string appears to the right of the text position point; for the maximum value the string appears above and to the left of the text position point. The text always remains in the plane of the computer screen, regardless of the view.

Editing Text Objects

You can edit any of the text labels or annotations in a graph:

  • Start plot edit mode.

Double-click the string, or right-click the string and select Edit from the context menu.

An editing bar (|) appears next to the text.

  • Make any changes to the text.
  • Click anywhere outside the text edit box to end text editing.

[warning]To create special characters in text, such as Greek letters or mathematical symbols, use TEX sequences. See the text string property for a table of characters you can use. If you create special characters by using the Font dialog box (available via text objects’ context menus, and also found in the Property Editor) and selecting the Symbol font family, you cannot edit that text object using MATLAB commands.[/warning]

Mathematical Symbols, Greek Letters, and TEX Characters

You can include mathematical symbols and Greek letters in text using TEX-style character sequences. This section describes how to construct a TEX character sequence.

Two Levels of MATLAB TEX Support

There are two levels of TEX support, controlled by the text Interpreter property:

  • ‘tex’ — Support for a subset of TEX markup
  • ‘latex’ — Support for TEX and LATEX markup

If you do not want the characters interpreted as TEX markup, then set the interpreter property to ‘none’.

Available Symbols and Greek Letters

For a list of symbols and the character sequences used to define them, see the table of available TEX characters in the Text Properties reference page.

In general, you can define text that includes symbols and Greek letters using the text function, assigning the character sequence to the String property of text objects. You can also include these character sequences in the string arguments of the title, xlabel, ylabel, and zlabel functions.

Example — Using a Mathematical Expression to Title a Graph

This example uses TEX character sequences to create graph labels. The following statements add a title and x- and y-axis labels to an existing graph.

title('{\itAe}^{-\alpha\itt}sin\beta{\itt} \alpha<<\beta')
xlabel('Time \musec.')
ylabel('Amplitude')


The backslash character (\) precedes all TEX character sequences. Looking at the string defining the title illustrates how to use these characters.

Controlling the Interpretation of TEX Characters

The text Interpreter property controls the interpretation of TEX characters. If you set this property to none, MATLAB interprets the special characters literally.

Specifying Text Color in TeX Strings

Use the \color modifier to change the color of characters following it from the previous color (which is black by default). Syntax is:

\color{colorname} for the eight basic named colors (red, green, yellow, magenta, blue, black, white), and plus the four Simulink® colors (gray, darkGreen, orange, and lightBlue)

Note that short names (one-letter abbreviations) for colors are not supported by the \color modifier.

  • \color[rgb]{r g b} to specify an RGB triplet with values between 0 and 1 as a cell array

For example,

text(.1,.5,['\fontsize{16}black {\color{magenta}magenta '...
'\color[rgb]{0 .5 .5}teal \color{red}red} black again'])

Specifying Subscript and Superscript Characters

The subscript character "_" and the superscript character "^" modify the character or substring defined in braces immediately following.

To print the special characters used to define the TeX strings when Interpreter is Tex, prefix them with the backslash "\" character: \\, \{, \} \_, \^.

[important]See the text reference page for more information.[/important]

When Interpreter is set to none, no characters in the String are interpreted, and all are displayed when the text is drawn.

When Interpreter is set to latex, MATLAB provides a complete LaTEX interpreter for text objects. See the Interpreter property for more information.

Using Character and Numeric Variables in Text

Any string variable is a valid specification for the text String property. This section illustrates how to use matrix, cell array, and numeric variables as arguments to the text function.

Text in Character Arrays

For example, each row of the matrix PersonalData contains specific information about a person, padding all but the longest row with a space so that each has the same number of columns).

PersonalData = ['Jack Straw ';'489 Main St';'Wichita KS '];

To display the data, index into the desired row.

text(.3,.5,['Name: ',PersonalData(1,:)])
text(.3,.45,['Address: ',PersonalData(2,:)])
text(.3,.4,['City and State: ',PersonalData(3,:)])

Text in Cell Arrays

Using a cell array enables you to create multiline text with a single text object. Each cell does not need to be the same number of characters. For example, the following statements,

key(1)={'{\itAe}^{-\alpha\itt}sin\beta{\itt}'};
key(2)={'Time in \musec'};
key(3)={'Amplitude in volts'};
text(.1,.8,key)

produce this output.

Numeric Variables

You can specify numeric variables in text strings using the num2str (number to string) function. For example, if you type on the command line

x = 21;
['Today is the ',num2str(x),'st day.']

The three separate strings concatenate into one.

Today is the 21st day.

Since the result is a valid string, you can specify it as a value for the text String property.

text(xcoord,ycoord,['Today is the ',num2str(x),'st day.'])

Example — Multiline Text

You can input multiline text strings using cell arrays. Simply define a string variable as a cell array with one line per cell. This example defines two cell arrays, one used for a uicontrol and the other as text.

str1(1) = {'Center each line in the Uicontrol'};
str1(2) = {'Also check out the textwrap function'};
str2(1) = {'Each cell is a quoted string'};
str2(2) = {'You can specify how the string is aligned'};
str2(3) = {'You can use LaTeX symbols like \pi \chi \Xi'};
str2(4) = {'\bfOr use bold \rm\itor italic font\rm'};
str2(5) = {'\fontname{courier}Or even change fonts'};
plot(0:6,sin(0:6))
uicontrol('Style','text','Position',[80 80 200 30],...
          'String',str1);
text(5.75,sin(2.5),str2,'HorizontalAlignment','right')

Example — Using LaTeX to Format Math Equations

The LaTeX markup language evolved from TEX, and has a superset of its capabilities. LaTeX gives you more elaborate control over specifying and styling mathematical symbols.

The following example illustrates some LaTeX typesetting capabilities when used with the text function. Because the default interpreter is for TEX, you need to specify the parameter-value pair 'interpreter','latex' when typesetting equations such as are contained in the following script:

%% LaTeX Examples--Some well known equations rendered in LaTeX
%
figure('color','white','units','inches','position',[2 2 4 6.5]);
axis off

%% A matrix; LaTeX code is
% \hbox {magic(3) is } \left( {\matrix{ 8 & 1 & 6 \cr 
% 3 & 5 & 7 \cr 4 & 9 & 2 } } \right)
h(1) = text('units','inch', 'position',[.2 5], ...
    'fontsize',14, 'interpreter','latex', 'string',...
    ['$$\hbox {magic(3) is } \left( {\matrix{ 8 & 1 & 6 \cr'...
    '3 & 5 & 7 \cr 4 & 9 & 2 } } \right)$$']);

%% A 2-D rotation transform; LaTeX code is
%  \left[ {\matrix{\cos(\phi) & -\sin(\phi) \cr
%  \sin(\phi) & \cos(\phi) \cr}}
%  \right] \left[ \matrix{x \cr y} \right]  
%  
%  $$ \left[ {\matrix{\cos(\phi) 
%  & -\sin(\phi) \cr \sin(\phi) & \cos(\phi)  % \cr}}
%  \right] \left[ \matrix{x \cr y} \right] $$ 
%
h(2) = text('units','inch', 'position',[.2 4], ...
    'fontsize',14, 'interpreter','latex', 'string',...
    ['$$\left[ {\matrix{\cos(\phi) & -\sin(\phi) \cr'...
    '\sin(\phi) & \cos(\phi) \cr}} \right]'...
    '\left[ \matrix{x \cr y} \right]$$']);

%% The Laplace transform; LaTeX code is
%  L\{f(t)\}  \equiv  F(s) = \int_0^\infty\!\!{e^{-st}f(t)dt}  
%  $$ L\{f(t)\} \equiv  F(s) = \int_0^\infty\!\!{e^{-st}f(t)dt} $$
%  The Initial Value Theorem for the Laplace transform:
%  \lim_{s \rightarrow \infty} sF(s) = \lim_{t \rightarrow 0} f(t)
%  $$ \lim_{s \rightarrow \infty} sF(s) = \lim_{t \rightarrow 0}
%  f(t) $$
%
h(3) = text('units','inch', 'position',[.2 3], ...
    'fontsize',14, 'interpreter','latex', 'string',...
    ['$$L\{f(t)\}  \equiv  F(s) = \int_0^\infty\!\!{e^{-st}'...
    'f(t)dt}$$']);

%% The definition of e; LaTeX code is
%  e = \sum_{k=0}^\infty {1 \over {k!} }
%  $$ e = \sum_{k=0}^\infty {1 \over {k!} } $$
%
h(4) = text('units','inch', 'position',[.2 2], ...
    'fontsize',14, 'interpreter','latex', 'string',...
    '$$e = \sum_{k=0}^\infty {1 \over {k!} } $$');

%% Differential equation
% The equation for motion of a falling body with air resistance
% LaTeX code is
%  m \ddot y = -m g + C_D \cdot {1 \over 2} \rho {\dot y}^2 \cdot A
%  $$ m \ddot y = -m g + C_D \cdot {1 \over 2} \rho {\dot y}^2
%  \cdot A  $$
%
h(5) = text('units','inch', 'position',[.2 1], ...
    'fontsize',14, 'interpreter','latex', 'string',...
    ['$$m \ddot y = -m g + C_D \cdot {1 \over 2}'...
    '\rho {\dot y}^2 \cdot A$$']); 

%% Integral Equation; LaTeX code is
%  \int_{0}^{\infty} x^2 e^{-x^2} dx = \frac{\sqrt{\pi}}{4}  
%  $$ \int_{0}^{\infty} x^2 e^{-x^2} dx = \frac{\sqrt{\pi}}{4} $$  
%  
h(6) = text('units','inch', 'position',[.2 0], ...
    'fontsize',14, 'interpreter','latex', 'string',...
    '$$\int_{0}^{\infty} x^2 e^{-x^2} dx = \frac{\sqrt{\pi}}{4}$$');   


[tip]You can find out more about the LaTeX system at The LaTeX Project Web site,
latex-project.org[/tip]

Drawing Text in a Box

When you use the text function to display a character string, the string's position is defined by a rectangle called the Extent of the text. You can display this rectangle either as a box or a filled area. For example, you can highlight contour labels to make the text easier to read.

[x,y] = meshgrid(-1:.01:1);
z = x.*exp(-x.^2-y.^2);
[c,h]=contour(x,y,z);
h = clabel(c,h);
set(h,'BackgroundColor',[1 1 .6])


For additional features, see the following text properties:

  • BackgroundColor — Color of the rectangle's interior ('none' by default)
  • EdgeColor — Color of the rectangle's edge ('none' by default)
  • LineStyle — Style of the rectangle's edge line (first set EdgeColor)
  • LineWidth — Width of the rectangle's edge line (first set EdgeColor)
  • Margin — Increase the size of the rectangle by adding a margin to the text extent.

Starting Simulink Software

Opening the Simulink Library Browser

Your MATLAB environment must be running before you can open Simulink software. You start Simulink from within MATLAB.

To start Simulink and open the Simulink Library Browser:

  • Start MATLAB. For more information, see Starting a MATLAB Session in the MATLAB Getting Started Guide.

Enter simulink in the MATLAB Command Window.

The Simulink Library Browser opens.

[warning]You can also start Simulink by:

  • Clicking the Simulink icon in the MATLAB toolbar
  • Clicking the MATLAB Start button, then selecting Simulink > Library Browser

[/warning]

Opening a Model

You can open existing Simulink models or create new models from the Simulink Library Browser.

To create a new model:

Select File > New > Model in the Simulink Library Browser.

The software opens an empty model window.

To open an existing model:

Select File > Open in the Simulink Library Browser.

The Open dialog box appears.

Select the model (.mdl file) you want to open, then click Open.

The software opens the selected model in the model window.

What Is Model-Based Design?

Model-Based Design

Model-Based Design is a process that enables faster, more cost-effective development of dynamic systems, including control systems, signal processing, and communications systems. In Model-Based Design, a system model is at the center of the development process, from requirements development, through design, implementation, and testing. The model is an executable specification that is continually refined throughout the development process. After model development, simulation shows whether the model works correctly.

When software and hardware implementation requirements are included, such as fixed-point and timing behavior, you can automatically generate code for embedded deployment and create test benches for system verification, saving time and avoiding the introduction of manually coded errors.

Model-Based Design allows you to improve efficiency by:

  • Using a common design environment across project teams
  • Linking designs directly to requirements
  • Integrating testing with design to continuously identify and correct errors
  • Refining algorithms through multidomain simulation
  • Automatically generating embedded software code
  • Developing and reusing test suites
  • Automatically generating documentation
  • Reusing designs to deploy systems across multiple processors and hardware targets
  • Modeling Process

There are six steps to modeling any system:

  • Defining the System
  • Identifying System Components
  • Modeling the System with Equations
  • Building the Simulink Block Diagram
  • Running the Simulation
  • Validating the Simulation Results

You perform the first three steps of this process outside of the Simulink software before you begin building your model.

Defining the System

The first step in modeling a dynamic system is to fully define the system. If you are modeling a large system that can be broken into parts, you should model each subcomponent on its own. Then, after building each component, you can integrate them into a complete model of the system.

For example, the demo model used later in this guide models the heating system of a house. This system can be broken down into three main parts:

  • Heater subsystem
  • Thermostat subsystem
  • Thermodynamic model subsystem

The most effective way to build a model of this system is to consider each of these subsystems independently.

Identifying System Components

The second step in the modeling process is to identify the system components. Three types of components define a system:

  • Parameters — System values that remain constant unless you change them
  • States — Variables in the system that change over time
  • Signals — Input and output values that change dynamically during the simulation

In Simulink, parameters and states are represented by blocks, while signals are represented by the lines that connect blocks.

For each subsystem that you identified, ask yourself the following questions:

  • How many input signals does the subsystem have?
  • How many output signals does the subsystem have?
  • How many states (variables) does the subsystem have?
  • What are the parameters (constants) in the subsystem?
  • Are there any intermediate (internal) signals in the subsystem?

Once you have answered these questions, you should have a comprehensive list of the system components, and are ready to begin modeling the system.

Modeling the System with Equations

The third step in modeling a system is to formulate the mathematical equations that describe the system.

For each subsystem, use the list of system components you identified to describe the system mathematically. Your model may include:

  • Algebraic equations
  • Logical equations
  • Differential equations, for continuous systems
  • Difference equations, for discrete systems

You use these equations to create the block diagram in Simulink.

Building the Simulink Block Diagram

After you have defined the mathematical equations that describe each subsystem, you can begin building a block diagram of your model in Simulink.

Build the block diagram for each of your subcomponents separately. After you have modeled each subcomponent, you can then integrate them into a complete model of the system.

[important]See Creating a Simple Model for more information on building the block diagram.[/important]

Running the Simulation

After you build the Simulink block diagram, you can simulate the model and analyze the results.

Simulink allows you to interactively define system inputs, simulate the model, and observe changes in behavior. This allows you to quickly evaluate your model.

[important]See Simulating the Model for more information on running a simulation.[/important]

Validating the Simulation Results

Finally, you must validate that the model accurately represents the physical characteristics of the system.

You can use the linearization and trimming tools available from the MATLAB command line, plus the many tools in MATLAB and its application toolboxes to analyze and validate your model.

Simulink Getting Started

Overview

Simulink® software models, simulates, and analyzes dynamic systems. It enables you to pose a question about a system, model the system, and see what happens.

With Simulink, you can easily build models from scratch, or modify existing models to meet your needs. Simulink supports linear and nonlinear systems, modeled in continuous time, sampled time, or a hybrid of the two. Systems can also be multirate — having different parts that are sampled or updated at different rates.

Thousands of scientists and engineers around the world use Simulink to model and solve real problems in a variety of industries, including:

  • Aerospace and Defense
  • Automotive
  • Communications
  • Electronics and Signal Processing
  • Medical Instrumentation
  • Tool for Model-Based Design

With Simulink, you can move beyond idealized linear models to explore more realistic nonlinear models, factoring in friction, air resistance, gear slippage, hard stops, and the other things that describe real-world phenomena. Simulink turns your computer into a laboratory for modeling and analyzing systems that would not be possible or practical otherwise.

Whether you are interested in the behavior of an automotive clutch system, the flutter of an airplane wing, or the effect of the monetary supply on the economy, Simulink provides you with the tools to model and simulate almost any real-world problem. Simulink also provides demos that model a wide variety of real-world phenomena (see Simulink Demo Models).

Simulink provides a graphical user interface (GUI) for building models as block diagrams, allowing you to draw models as you would with pencil and paper. Simulink also includes a comprehensive block library of sinks, sources, linear and nonlinear components, and connectors. If these blocks do not meet your needs, however, you can also create your own blocks. The interactive graphical environment simplifies the modeling process, eliminating the need to formulate differential and difference equations in a language or program.

Models are hierarchical, so you can build models using both top-down and bottom-up approaches. You can view the system at a high level, then double-click blocks to see increasing levels of model detail. This approach provides insight into how a model is organized and how its parts interact.

Tool for Simulation

After you define a model, you can simulate it, using a choice of mathematical integration methods, either from the Simulink menus or by entering commands in the MATLAB® Command Window. The menus are convenient for interactive work, while the command line is useful for running a batch of simulations (for example, if you are doing Monte Carlo simulations or want to apply a parameter across a range of values).

Using scopes and other display blocks, you can see the simulation results while the simulation runs. You can then change many parameters and see what happens for “what if” exploration. The simulation results can be put in the MATLAB workspace for postprocessing and visualization.

Tool for Analysis

Model analysis tools include linearization and trimming tools, which can be accessed from the MATLAB command line, plus the many tools in MATLAB and its application toolboxes. Because MATLAB and Simulink are integrated, you can simulate, analyze, and revise your models in either environment at any point.

How Simulink Software Interacts with the MATLAB Environment

Simulink software is tightly integrated with the MATLAB environment. It requires MATLAB to run, depending on it to define and evaluate model and block parameters. Simulink can also utilize many MATLAB features. For example, Simulink can use the MATLAB environment to:

  • Define model inputs.
  • Store model outputs for analysis and visualization.
  • Perform functions within a model, through integrated calls to MATLAB operators and functions.

Constructing Sparse Matrices

Creating Sparse Matrices

  • Converting Full to Sparse
  • Creating Sparse Matrices Directly
  • Creating Sparse Matrices from Their Diagonal Elements

MATLAB software never creates sparse matrices automatically. Instead, you must determine if a matrix contains a large enough percentage of zeros to benefit from sparse techniques.

The density of a matrix is the number of nonzero elements divided by the total number of matrix elements. For matrix M, this would be

nnz(M) / prod(size(M));

Matrices with very low density are often good candidates for use of the sparse format.

Converting Full to Sparse

You can convert a full matrix to sparse storage using the sparse function with a single argument.

S = sparse(A)

For example:

A = [ 0   0   0   5
      0   2   0   0
      1   3   0   0
      0   0   4   0];
S = sparse(A)

produces

 S =
     
   (3,1)        1
   (2,2)        2
   (3,2)        3
   (4,3)        4
   (1,4)        5

The printed output lists the nonzero elements of S, together with their row and column indices. The elements are sorted by columns, reflecting the internal data structure.

Creating Sparse Matrices Directly

You can convert a sparse matrix to full storage using the full function, provided the matrix order is not too large. For example A = full(S) reverses the example conversion.

Converting a full matrix to sparse storage is not the most frequent way of generating sparse matrices. If the order of a matrix is small enough that full storage is possible, then conversion to sparse storage rarely offers significant savings.

You can create a sparse matrix from a list of nonzero elements using the sparse function with five arguments.

S = sparse(i,j,s,m,n)

i and j are vectors of row and column indices, respectively, for the nonzero elements of the matrix. s is a vector of nonzero values whose indices are specified by the corresponding (i,j) pairs. m is the row dimension for the resulting matrix, and n is the column dimension.

The matrix S of the previous example can be generated directly with

S = sparse([3 2 3 4 1],[1 2 2 3 4],[1 2 3 4 5],4,4)

S =

   (3,1)        1
   (2,2)        2
   (3,2)        3
   (4,3)        4
   (1,4)        5

The sparse command has a number of alternate forms. The example above uses a form that sets the maximum number of nonzero elements in the matrix to length(s). If desired, you can append a sixth argument that specifies a larger maximum, allowing you to add nonzero elements later without reallocating the sparse matrix.

The matrix representation of the second difference operator is a good example of a sparse matrix. It is a tridiagonal matrix with -2s on the diagonal and 1s on the super- and subdiagonal. There are many ways to generate it—here’s one possibility.

D = sparse(1:n,1:n,-2*ones(1,n),n,n);
E = sparse(2:n,1:n-1,ones(1,n-1),n,n);
S = E+D+E'

For n = 5, MATLAB responds with

S =

   (1,1)       -2
   (2,1)        1
   (1,2)        1
   (2,2)       -2
   (3,2)        1
   (2,3)        1
   (3,3)       -2
   (4,3)        1
   (3,4)        1
   (4,4)       -2
   (5,4)        1
   (4,5)        1
   (5,5)       -2

Now F = full(S) displays the corresponding full matrix.

F = full(S)

F =

    -2     1     0     0     0
     1    -2     1     0     0
     0     1    -2     1     0
     0     0     1    -2     1
     0     0     0     1    -2

Creating Sparse Matrices from Their Diagonal Elements

Creating sparse matrices based on their diagonal elements is a common operation, so the function spdiags handles this task. Its syntax is

S = spdiags(B,d,m,n)

To create an output matrix S of size m-by-n with elements on p diagonals:

  • B is a matrix of size min(m,n)-by-p. The columns of B are the values to populate the diagonals of S.
  • d is a vector of length p whose integer elements specify which diagonals of S to populate.

That is, the elements in column j of B fill the diagonal specified by element j of d.

[warning]If a column of B is longer than the diagonal it’s replacing, super-diagonals are taken from the lower part of the column of B, and sub-diagonals are taken from the upper part of the column of B.[/warning]

As an example, consider the matrix B and the vector d.

B = [ 41    11     0
      52    22     0
      63    33    13
      74    44    24 ];

d = [-3
      0
      2];

Use these matrices to create a 7-by-4 sparse matrix A:

A = spdiags(B,d,7,4)

A =

   (1,1)       11
   (4,1)       41
   (2,2)       22
   (5,2)       52
   (1,3)       13
   (3,3)       33
   (6,3)       63
   (2,4)       24
   (4,4)       44
   (7,4)       74

In its full form, A looks like this:

full(A)

ans =

    11     0    13     0
     0    22     0    24
     0     0    33     0
    41     0     0    44
     0    52     0     0
     0     0    63     0
     0     0     0    74

spdiags can also extract diagonal elements from a sparse matrix, or replace matrix diagonal elements with new values. Type help spdiags for details.

Importing Sparse Matrices

You can import sparse matrices from computations outside the MATLAB environment. Use the spconvert function in conjunction with the load command to import text files containing lists of indices and nonzero elements. For example, consider a three-column text file T.dat whose first column is a list of row indices, second column is a list of column indices, and third column is a list of nonzero values. These statements load T.dat into MATLAB and convert it into a sparse matrix S:

load T.dat
S = spconvert(T)

The save and load commands can also process sparse matrices stored as binary data in MAT-files.

Computational Advantages

Memory Management

Using sparse matrices to store data that contains a large number of zero-valued elements can both save a significant amount of memory and speed up the processing of that data. sparse is an attribute that you can assign to any two-dimensional MATLAB matrix that is composed of double or logical elements.

The sparse attribute allows MATLAB to:

  • Store only the nonzero elements of the matrix, together with their indices.
  • Reduce computation time by eliminating operations on zero elements.

For full matrices, MATLAB stores every matrix element internally. Zero-valued elements require the same amount of storage space as any other matrix element. For sparse matrices, however, MATLAB stores only the nonzero elements and their indices. For large matrices with a high percentage of zero-valued elements, this scheme significantly reduces the amount of memory required for data storage.

The whos command provides high-level information about matrix storage, including size and storage class. For example, this whos listing shows information about sparse and full versions of the same matrix.

M_full = magic(1100);          % Create 1100-by-1100 matrix.
M_full(M_full > 50) = 0;       % Set elements >50 to zero.
M_sparse = sparse(M_full);     % Create sparse matrix of same.

whos
  Name           Size              Bytes  Class     Attributes

  M_full      1100x1100          9680000  double
  M_sparse    1100x1100             5004  double    sparse

[warning]
That the number of bytes used is fewer in the sparse case, because zero-valued elements are not stored.[/warning]

Computational Efficiency

Sparse matrices also have significant advantages in terms of computational efficiency. Unlike operations with full matrices, operations with sparse matrices do not perform unnecessary low-level arithmetic, such as zero-adds (x+0 is always x). The resulting efficiencies can lead to dramatic improvements in execution time for programs working with large amounts of sparse data.

[help]For more information, see Sparse Matrix Operations.[/help]

Importing MAT-Files

Viewing the Contents of a MAT-File

MAT-files are binary MATLAB format files that store workspace variables.

To see the variables in a MAT-file before loading the file into your workspace, click the file name in the Current Folder browser. Information about the variables appears in the Details Panel.

Alternatively, use the command whos -file filename. This function returns the name, dimensions, size, and class of all variables in the specified MAT-file.

For example, view the contents of the demo file durer.mat:

whos -file durer.mat

MATLAB returns:

 Name           Size               Bytes  Class     Attributes

  X            648x509            2638656  double              
  caption        2x28                 112  char                
  map          128x3                 3072  double              

The byte counts represent the number of bytes that the data occupies when loaded into the MATLAB workspace. Compressed data uses fewer bytes in a file than in the workspace. In Version 7 or higher MAT-files, MATLAB compresses data. For more information, see MAT-File Versions.

Loading a MAT-File

To import all variables from a MAT-file, use one of the following options:

  • In the Current Folder browser, double-click the name of the file, or right-click the name of the file and select Open or Load.

Call the load function. For example, the following command loads all variables from the demo file durer.mat:

load('durer.mat')

To load variables into a structure array, specify an output variable for the load function:

durerStruct = load('durer.mat')

[warning]When you import data into the MATLAB workspace, the new variables you create overwrite any existing variables in the workspace that have the same name.[/warning]

Loading Selected Variables

To select and load MAT-file variables interactively, use any of the following options:

  • Select File > Import Data.
  • Click the Import data button in the Workspace browser toolbar.
  • Drag variables from the Details Panel of the Current Folder browser to the Workspace browser.

Alternatively, use the load function. For example, load variables X and map from durer.mat:

load('durer.mat', 'X', 'map')

To load variables with names that match a specific pattern, use one of the following options:

Include the wildcard character (*). For example, load all variables that start with str from a file named strinfo.mat:

load('strinfo.mat', 'str*')

Apply the -regexp option, which matches variables to regular expressions. For example, load all variables that start with Mon, Tue, or Wed from a hypothetical file named myfile.mat:

load('myfile.mat', '-regexp', '^Mon|^Tue|^Wed')

[important]For more information, see Regular Expressions in the MATLAB Programming Fundamentals documentation.[/important]

Troubleshooting: Loading Variables within a Function

If you define a function that loads data from a MAT-file, and find that MATLAB does not return the expected results, check whether any variables in the MAT-file share the same name as a MATLAB function. Common variable names that conflict with function names include i, j, mode, char, size, or path. To determine whether a particular name is associated with a MATLAB function, use the which function.

[tip]For example, consider a MAT-file with variables height, width, and length. If you load these variables using a function such as findVolume,[/tip]

function vol = findVolume(myfile)
  load(myfile);
  vol = height * width * length;

MATLAB interprets the reference to length as a call to the length function, and returns an error:

??? Error using ==> length
Not enough input arguments.

To avoid confusion, when defining your function, choose one (or more) of the following approaches:

Load into a structure array. For example, define the findVolume function as follows:

function vol = findVolume(myfile)
  dims = load(myfile);
  vol = dims.height * dims.width * dims.length;
  • Explicitly include the names of variables in the call to load, as described in Loading Selected Variables.
  • Initialize variables within the function before calling load.

Any of these methods allow you to override the function name with the variable name within your function. For more information, see Potential Conflict with Function Names in the MATLAB Programming Fundamentals documentation.

Source Control Interface on Microsoft Windows

If you use source control systems to manage your files, you can interface with the systems to perform source control actions from within the MATLAB, Simulink, and Stateflow® products. Use menu items in the MATLAB, Simulink, or Stateflow products, or run functions in the MATLAB Command Window to interface with your source control systems.

The source control interface on Windows works with any source control system that conforms to the Microsoft Common Source Control standard, Version 1.1. If your source control system does not conform to the standard, use a Microsoft Source Code Control API wrapper product for your source control system so that you can interface with it from the MATLAB, Simulink, and Stateflow products.

This documentation uses the Microsoft® Visual SourceSafe® software as an example. Your source control system might use different terminology and not support the same options or might use them in a different way. Regardless, you should be able to perform similar actions with your source control system based on this documentation.

Perform most source control interface actions from the Current Folder browser. You can also perform many of these actions for a single file from the MATLAB Editor, a Simulink model window, or a Stateflow chart window—for more information, see Performing Source Control Actions from the Editor, Simulink, or Stateflow File Menu on Microsoft Windows. Another way to access many of the source control actions is with the verctrl function.

Formatting MATLAB Code for Publishing

Overview of Formatting MATLAB Code for Publishing

This section describes ways to control how output that the MATLAB software generates when it evaluates executable MATLAB code for a published document. For example, you can direct MATLAB to include the last, or all plots generated by a for loop. You can interweave comments, code, and output throughout your published document to draw your readers’ attention to certain areas of interest.

Formatting Code Output in a Published MATLAB Code File

The method you use to specify how output displays in the document is the same method you use to specify document titles and section headers; namely the cell break (%%). When you insert a cell break into a file, it directs MATLAB to publish the code and output contained in the cells created by the break. Because the entire file is a cell, inserting a cell break results in the file containing two cells. The first cells is the one above the cell break, and the second is the one below the cell break. The examples in the remaining topics demonstrate how you can use this behavior to control the output produced by MATLAB code.

Example of Formatting Code Output in a Published MATLAB File

This section provides an example to demonstrate how a MATLAB file appears when published. It demonstrates how the published example file appears before and after cell breaks are added to achieve the published results.

Suppose your file contains the following code:

%% Scale magic Data and Display as Image

for i=1:3
    imagesc(magic(i)) 
end

The following image illustrates how the code presented appears when you publish it to HTML. The plot in the figure is smaller than it appears if you publish the code using factory default settings. For information on setting publishing properties for images, see Producing Published Output from MATLAB Code Files.

[important]Notice that the published document displays the plot after the end of the for loop and that only the last plot generated by the code is included.[/important]

By placing cell breaks within a loop, you can display the output generated by MATLAB code when iterating a loop.

To include the plot generated by each iteration of the loop in the published document, insert a cell break after the opening for statement. Position the cursor at the end of the first line of the for loop, and then select Cell > Insert Cell Break.

The code now appears like this:

%% Scale magic Data and Display as Image

for i=1:3
    %%
    imagesc(magic(i)) 
end

Now when you publish the code to HTML, it appears as follows. The plots in the figure are smaller than they appear if you publish the code using factory default settings. For information on setting publishing properties for images, see Producing Published Output from MATLAB Code Files.

[important]Notice that the published document displays the plot within the for loop code. You can also use text markup for similar results with figures. See Formatting MATLAB Code for Publishing for details.[/important]

Notebook Feature Reference

Bring MATLAB to Front

This section provides reference information about each of the Notebook features, listed alphabetically. To use these features, select them from the Notebook menu in Microsoft Word. (In Word 2007, the Notebook menu is on the Add-Ins tab.)

Bring MATLAB to Front brings the MATLAB Command Window to the foreground.

Define Autoinit Cell

Define AutoInit Cell creates an autoinit cell by converting the current paragraph, selected text, or input cell. An autoinit cell is an input cell that is automatically evaluated whenever you open an M-book.

If you select this feature while the cursor is in a paragraph of text, Notebook converts the entire paragraph to an autoinit cell. If you select this feature while text is selected, Notebook converts the text to an autoinit cell. If you select this feature while the cursor is in an input cell, Notebook converts the input cell to an autoinit cell.

Notebook formats the autoinit cell using the AutoInit style, defined as bold, dark blue, 10-point Courier New.

[important]For more information about autoinit cells, see Defining Autoinit Input Cells for Notebook[/important].

Define Calc Zone

Define Calc Zone defines the selected text, input cells, and output cells as a calc zone. A calc zone is a contiguous block of related text, input cells, and output cells that describes a specific operation or problem.

Notebook defines a calc zone as a Word document section, placing section breaks before and after the calc zone. However, Word does not display section breaks at the beginning or end of a document.

[important]For information about evaluating calc zones, see Evaluating a Calc Zone with Notebook. For more information about document sections, see the Microsoft Word documentation.[/important]

Define Input Cell

Define Input Cell creates an input cell by converting the current paragraph, selected text, or autoinit cell. An input cell contains a MATLAB command.

If you select this feature while the cursor is in a paragraph of text, Notebook converts the entire paragraph to an input cell. If you select this feature while text is selected, Notebook converts the text to an input cell. If you select this feature while the cursor is in an autoinit cell, Notebook converts the autoinit cell to an input cell.

Notebook encloses the text in cell markers and formats the cell using the Input style, defined as bold, dark green, 10-point Courier New.

[important]For more information about creating input cells, see Defining MATLAB Commands as Input Cells for Notebook. For information about evaluating input cells, see Evaluating MATLAB Commands with Notebook.[/important]

Evaluate Calc Zone

Evaluate Calc Zone sends the input cells in the current calc zone to MATLAB to be evaluated. The current calc zone is the Word section that contains the cursor.

As Notebook evaluates each input cell, it generates an output cell. When you evaluate an input cell for which there is no output cell, Notebook places the output cell immediately after the input cell that generated it. If you evaluate an input cell for which there is an output cell, Notebook replaces the results in the output cell wherever it is in the M-book.
[important]
For more information, see Evaluating a Calc Zone with Notebook. [/important]

Evaluate Cell

Evaluate Cell sends the current input cell or cell group to MATLAB to be evaluated. An input cell contains a MATLAB command. A cell group is a single, multiline input cell that contains more than one MATLAB command. Notebook displays the output or an error message in an output cell.

If you evaluate an input cell for which there is no output cell, Notebook places the output cell immediately after the input cell that generated it. If you evaluate an input cell for which there is an output cell, Notebook replaces the results in the output cell wherever it is in the M-book. If you evaluate a cell group, all output for the cell appears in a single output cell.

An input cell or cell group is the current input cell or cell group if

  • The cursor is in the input cell or cell group.
  • The cursor is at the end of the line that contains the closing cell marker for the input cell or cell group.
  • The cursor is in the output cell for the input cell or cell group.
  • The input cell or cell group is selected.

[warning]Evaluating a cell that involves a lengthy operation may cause a time-out. If this happens, Word displays a time-out message and asks whether you want to continue waiting for a response or terminate the request. If you choose to continue, Word resets the time-out value and continues waiting for a response. Word sets the time-out value; you cannot change it.[/warning]

[important]For more information, see Evaluating MATLAB Commands with Notebook. For information about evaluating the entire M-book, see Evaluating an Entire M-Book. [/important]

Evaluate Loop

Evaluate Loop evaluates the selected input cells repeatedly.

[important]For more information, see Using a Loop to Evaluate Input Cells Repeatedly with Notebook.
[/important]

Evaluate M-Book

Evaluate M-book evaluates the entire M-book, sending all input cells to MATLAB to be evaluated. Notebook begins at the top of the M-book regardless of the cursor position.

As Notebook evaluates each input cell, it generates an output cell. When you evaluate an input cell for which there is no output cell, Notebook places the output cell immediately after the input cell that generated it. If you evaluate an input cell for which there is an output cell, Notebook replaces the results in the output cell wherever it is in the M-book.

[important]For more information, see Evaluating an Entire M-Book.[/important]

Group Cells

Group Cells converts the input cells in the selection into a single multiline input cell called a cell group. You evaluate a cell group using Evaluate Cell. When you evaluate a cell group, all of its output follows the group and appears in a single output cell.

If you include text in the selection, Notebook moves it after the cell group. However, if text precedes the first input cell in the group, the text will remain before the group.

If you include output cells in the selection, Notebook deletes them. If you select all or part of an output cell before selecting this feature, Notebook includes its input cell in the cell group.

If the first line in the cell group is an autoinit cell, the entire group acts as a sequence of autoinit cells. Otherwise, the group acts as a sequence of input cells. You can convert an entire cell group to an autoinit cell by using Define AutoInit Cell.

[important]For more information, see Defining Cell Groups for Notebook. For information about converting a cell group to individual input cells, see Ungroup Cells.[/important]

Hide Cell Markers

Hide Cell Markers hides cell markers in the M-book.

When you select this feature, it changes to Show Cell Markers.

[tip]Notebook does not print cell markers whether you choose to hide them or show them on the screen.[/tip]

Notebook Options

Notebook Options allows you to examine and modify display options for numeric and graphic output.

See Printing and Formatting an M-Book for more information.

Purge Selected Output Cells

Purge Selected Output Cells deletes all output cells from the current selection.

[important]For more information, see Deleting Output Cells with Notebook.[/important]

Toggle Graph Output for Cell

Toggle Graph Output for Cell suppresses or allows graphic output from an input cell.

If an input or autoinit cell generates figure output that you want to suppress, place the cursor in the input cell and choose this feature. The string (no graph) will be placed after the input cell to indicate that graph output for that cell will be suppressed.

To allow graphic output for that cell, place the cursor inside the input cell and choose Toggle Graph Output for Cell again. The (no graph) marker will be removed. This feature overrides the Embed Figures in M-book option, if that option is set in the Notebook Options dialog box.

[help]See Embedding Graphic Output in the M-Book and Suppressing Graphic Output for Individual Input Cells in Notebook for more information.[/help]

Undefine Cells

Undefine Cells converts the selected cells to text. If no cells are selected but the cursor is in a cell, Notebook undefines that cell. Notebook removes the cell markers and reformats the cell according to the Normal style.

If you undefine an input cell, Notebook automatically undefines its output cell. However, if you undefine an output cell, Notebook does not undefine its input cell. If you undefine an output cell containing an embedded graphic, the graphic remains in the M-book but is no longer associated with an input cell.

[important]For information about the Normal style, see Modifying Styles in the M-Book Template. For information about deleting output cells, see Purge Selected Output Cells. [/important]

Ungroup Cells

Ungroup Cells converts the current cell group into a sequence of individual input cells or autoinit cells. If the cell group is an input cell, Notebook converts the cell group to input cells. If the cell group is an autoinit cell, Notebook converts the cell group to autoinit cells. Notebook deletes the output cell for the cell group.

A cell group is the current cell group if

  • The cursor is in the cell group.
  • The cursor is at the end of a line that contains the closing cell marker for the cell group.
  • The cursor is in the output cell for the cell group.
  • The cell group is selected.

[important]For information about creating cell groups, see the description of Defining Cell Groups for Notebook.[/important]

Defining MATLAB Commands as Input Cells for Notebook

Defining Commands as Input Cells for Notebook

For information about evaluating the input cells you define, see Evaluating MATLAB Commands with Notebook.

To define a MATLAB command in a Word document as an input cell, follow these steps:

Type the command into the M-book as text. For example,

This is a sample M-book.

a = magic(3)

Position the cursor anywhere in the command and select Notebook > Define Input Cell or press Alt+D. If the command is embedded in a line of text, use the mouse to select it. Notebook defines the MATLAB command as an input cell:

This is a sample M-book.

[a = magic(3)]

Note how Notebook changes the character font of the text in the input cell to a bold, dark green color and encloses it within cell markers. Cell markers are bold, gray brackets. They differ from the brackets used to enclose matrices by their size and weight. For information about changing these default formats, see Modifying Styles in the M-Book Template.

Defining Cell Groups for Notebook

You can collect several input cells into a single input cell. This is called a cell group. Because all the output from a cell group appears in a single output cell that Notebook places immediately after the group, cell groups are useful when several MATLAB commands are needed, such as to fully define a graphic.

For example, if you define all the MATLAB commands that produce a graphic as a cell group and then evaluate that cell group, Notebook generates a single graphic that includes all the graphic components defined in the commands. If instead you define all the MATLAB commands that generate the graphic as separate input cells, evaluating the cells generates multiple graphic output cells.

See Evaluating Cell Groups with Notebook for information about evaluating a cell group. For information about ungrouping a cell group, see Ungroup Cells.

To create a cell group, follow these steps:

  • Use the mouse to select the input cells that are to make up the group.
  • Select Notebook > Group Cells or press Alt+G.

Notebook converts the selected cells into a cell group and replaces cell markers with a single pair that surrounds the group:

This is a sample cell group.

[date 
a = magic(3) ]

[tip]Note the following:[/tip]

  • A cell group cannot contain output cells. If the selection includes output cells, Notebook deletes them.
  • A cell group cannot contain text. If the selection includes text, Notebook places the text after the cell group. However, if the text precedes the first input cell in the selection, Notebook leaves it where it is.
  • If you select part or all of an output cell, but not its input cell, Notebook includes the input cell in the cell group.

When you create a cell group, Notebook defines it as an input cell unless its first line is an autoinit cell, in which case Notebook defines the group as an autoinit cell.

Defining Autoinit Input Cells for Notebook

You can use autoinit cells to specify MATLAB commands to be automatically evaluated each time an M-book is opened. This is a quick and easy way to initialize the workspace. Autoinit cells are input cells with the following additional characteristics:

  • Notebook evaluates the autoinit cells when it opens the M-book.
  • Notebook displays the commands in autoinit cells using dark blue characters.

Autoinit cells are otherwise identical to input cells.

You can create an autoinit cell in one of the following two ways:

  • Enter the MATLAB command as text, then convert the command to an autoinit cell by selecting Notebook > Define AutoInit Cell.
  • If you already entered the MATLAB command as an input cell, you can convert the input cell to an autoinit cell. Either select the input cell or position the cursor in the cell, then select Notebook > Define AutoInit Cell.

See Evaluating MATLAB Commands with Notebook for information about evaluating autoinit cells.

Defining Calc Zones for Notebook

You can partition an M-book into self-contained sections, called calc zones. A calc zone is a contiguous block of text, input cells, and output cells. Notebook inserts Microsoft Word section breaks before and after the section to define the calc zone. The section break indicators include bold, gray brackets to distinguish them from standard Word section breaks.

You can use calc zones to prepare problem sets, making each problem a separate calc zone that can be created and tested on its own. An M-book can contain any number of calc zones.

[help]Using calc zones does not affect the scope of the variables in an M-book. Variables used in one calc zone are accessible to all calc zones.[/help]

After you create the text and cells that you want to include in the calc zone, define the calc zone by following these steps:

  • Select the input cells and text to be included in the calc zone.
  • Select Notebook > Define Calc Zone.

[warning]You must select an input cell and its output cell in their entirety to include them in the calc zone.[/warning]

See Evaluating a Calc Zone with Notebook for information about evaluating a calc zone.

Converting an Input Cell to Text with Notebook

To convert an input cell (or an autoinit cell or a cell group) to text, follow these steps:

  • Select the input cell with the mouse or position the cursor in the input cell.
  • Select Notebook > Undefine Cells or press Alt+U.

When Notebook converts the cell to text, it reformats the cell contents according to the Microsoft Word Normal style. For more information about M-book styles, see Modifying Styles in the M-Book Template. When you convert an input cell to text, Notebook also converts the corresponding output cell to text.

Managing Desktop Layouts

Overview of Desktop Layouts

When you end a session, MATLAB saves the current desktop arrangement. The next time you start MATLAB, the desktop appears like the way you left it. However, tools such as the Help browser, Web browser, and Array Editor do not reopen automatically, even if they were open when you ended the last session. You can use startup options to specify tools that you want to open on startup. For example, to have the Help browser open each time you start MATLAB, add helpbrowser to a startup.m file. For more information, see Startup Options.

You can also use predefined layouts, and you can save your own layouts for later reuse.

Saving a Desktop Layout

To save your current desktop arrangement:

  • Select Desktop > Save > Layout.
  • Assign a name to the layout in the resulting dialog box, and then click OK.

MATLAB stores the arrangements you save as XML files in the preferences folder for MATLAB. Type prefdir in the Command Window to display the location of these XML files. The layout last used in a session is MATLABDesktop.xml. The MATLABDesktop.xml file loads when you start MATLAB and is overwritten when you close MATLAB.

Reusing a Saved or Predefined Desktop Layout

Select Desktop > Desktop Layout, and then select the name of the layout you want to use.

MATLAB includes the following predefined layouts:

  • Default — Contains the Current Folder, Command Window, Workspace Browser, and Command History windows.
  • Command Window Only — Contains the Command Window only.
  • History and Command Window — Contains the Command History window and Command Window.
  • All Tabbed — Contains all desktop tools, opened, maximized, and tabbed together.
  • All but Command Window Minimized — Contains all tools, opened and minimized in the desktop, except for the Command Window and sometimes the Editor. The Command Window and the Editor (if it contains a document) remain maximized.

When you select a saved or predefined layout, document tools already open in the desktop remain open.

Renaming a Saved Desktop Layout

Rename a desktop layout that you have previously created and saved as follows:

  • Select Desktop > Organize Layouts.
  • In the resulting dialog box, select a layout, click the Rename button.
  • Type the new name over the existing name.
  • Click Close.

You can rename desktop layouts that you created only.

Deleting a Saved Desktop Layout

Delete a desktop layout that you have previously created and saved as follows:

  • Select Desktop > Organize Layouts.
  • In the resulting dialog box, select a layout, click the Delete button, and then click Close.

You can delete desktop layouts that you created only.

Restoring the Default Desktop Layout

If you are dissatisfied with your current desktop arrangement, you can restore it to the default arrangement as follows:

The default arrangement is that which appeared when you first installed MATLAB.

Specifying a Data Source

Creating the Graph

First define two variables by issuing these statements in the command window.

t = 0:.01:20;
alpha =.055;

Next plot t versus the expression exp(-alpha*t).*sin(.5*t) using the plot function or the plot tools.

plot(t,exp(-alpha*t).*sin(.5*t))

Varying the Data Source

Plot objects have properties that enable you to specify the source of the data that defines the object. For example, you can specify a workspace variable name or a MATLAB expression as the value of the XDataSource, YDataSource, or ZDataSource property for a line in a plot (i.e., a lineseries object). You can then use the Property Editor to change the variable name or alter the expression, and the plot is updated to reflect the change.

After creating the graph, you can use the Property Editor to couple the plotted line to the MATLAB expression.

  • Double-click on the plotted line to display its property panel.
  • Enter the MATLAB expression exp(-alpha*t).*cos(.5*t) in the Y Data Source text field.


You can now modify the expression in the Y Data Source text field and observe how the graph changes. After changing the text, click the Refresh Data button to update the data.

In the following picture, alpha is no longer negated, so the function grows instead of decays. Also the period has been shortened by changing sin(.5*t) to sin(1.5*t).

Data Sources for Multiobject Graphs

Suppose you create a line graph from matrix data. For example,

z = peaks;
h = plot(z,'YDataSource','z');

Because there is one lineseries object for each column of z, the following is true.

The data source for h(1) is z(:,1).

The data source for h(2) is z(:,2).

...

The data source for h(n) is z(:,n).

Toolbox Path Caching in the MATLAB Program

About Toolbox Path Caching in the MATLAB Program

For performance reasons, the MATLAB program caches toolbox folder information across sessions. The caching features are mostly transparent to you. However, if MATLAB does not see the latest versions of your M-files or if you receive warnings about the toolbox path cache, you might need to update the cache.

Using the Cache File Upon Startup

Upon startup, MATLAB gets information from a cache file to build the toolbox folder cache. Because of the cache file, startup is faster, especially if you run MATLAB from a network server or if you have many toolbox folders. When you end a session, MATLAB updates the cache file.

MATLAB does not use the cache file at startup if you clear the Enable toolbox path cache check box in File > Preferences > General. Instead, it creates the cache by reading from the operating system folders, which is slower than using the cache file.

Updating the Cache and Cache File

How the Toolbox Path Cache Works

MATLAB caches (essentially, stores in a known files list) the names and locations of files in matlabroot/toolbox folders. These folders are for files provided with MathWorks products that should not change except for product installations and updates. Caching those folders provides better performance during a session because MATLAB does not actively monitor those folders.

We strongly recommend that you save any M-files you create and any files provided by The MathWorks that you edit in a folder that is not in the matlabroot/toolbox folder tree. If you keep your files in matlabroot/toolbox folders, they may be overwritten when you install a new version of MATLAB.

When to Update the Cache

When you add files to matlabroot/toolbox folders, the cache and the cache file need to be updated. MATLAB updates the cache and cache file automatically when you install toolboxes or toolbox updates using the installer for MATLAB. MATLAB also updates the cache and cache file automatically when you use MATLAB tools, such as when you save files from the MATLAB Editor to matlabroot/toolbox folders.

When you add or remove files in matlabroot/toolbox folders by some other means, MATLAB might not recognize those changes. For example, when you

  • Save new files in matlabroot/toolbox folders using an external editor
  • Use operating system features and commands to add or remove files in matlabroot/toolbox folders

MATLAB displays this message:

Undefined function or variable

You need to update the cache so MATLAB will recognize the changes you made in matlabroot/toolbox folders.

Steps to Update the Cache

To update the cache and the cache file,

Select File > Preferences > General.

The General Preferences pane is displayed.

  • Click Update Toolbox Path Cache and click OK.


To update the cache, use rehash toolbox. To also update the cache file, use rehash toolboxcache. For more information, see rehash.

Additional Diagnostics with Toolbox Path Caching

To display information about startup time when you start MATLAB, select the Enable toolbox path cache diagnostics check box in General Preferences.

Starting the MATLAB Program on Macintosh Platforms

Starting the MATLAB Program from the Macintosh Desktop

To start the MATLAB program on Apple Macintosh platforms, double-click the MATLAB icon in the Applications folder.

You can specify the current folder upon startup as well as other options—for more information, see Startup Folder for the MATLAB Program and Startup Options.

If MATLAB fails to start due to a problem with required system components such as X11 or Sun Microsystems™ Java™ software, diagnostics run automatically and advise you of the problem, along with suggestions to correct it.

After starting MATLAB, the desktop opens. Desktop components that were open when you last shut down MATLAB will be opened on startup. For more information, see Desktop. If the DISPLAY environment variable is not set or is invalid, the desktop will not display.

Limitation

On Macintosh platforms, if you run MATLAB remotely, for example using rlogin, you must run with nodisplay, noawt, and nojvm startup options—for more information, see Startup Options.

Starting the MATLAB Program from a Shell on Macintosh Platforms

You can start MATLAB on Macintosh platforms the way you would start it on other UNIX[1] platforms. For example, you would run

/Applications/MATLAB_R2010a.app/bin/matlab

For more information, see Starting the MATLAB Program on UNIX Platforms.

[1] UNIX is a registered trademark of The Open Group in the United States and other countries.

MATLAB Commands

Basic Command Syntax

A simple MATLAB command computes the result of the expression to the right of the equals sign and assigns the value of the result to the output variable at the left. Examples of simple MATLAB commands are

x = 5.71;
A = [1 2 3; 4 5 6; 7 8 9];
I = besseli(nu, Z);

Commands that do not terminate with a semicolon display the result at your terminal as well as assigning it to the output variable:

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

A =
     1     2     3
     4     5     6
     7     8     9

If you do not explicitly assign the output of a command to a variable, MATLAB assigns the result to the reserved word ans:

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

ans =
     1     2     3
     4     5     6
     7     8     9

The value of ans changes with every command that returns an output value that is not assigned to a variable. We recommend that you do not use ans in place of variables as this practice tends to lead to code that is difficult to maintain and also to programming errors. The following use of ans, for example, is not recommended:

rand(3,5);
A = ans > 0.5;

Entering More Than One Command on a Line

You can enter more than one command on the same line, provided that you terminate each command with a comma or semicolon. Commands terminated with a comma display their results when they are executed; commands terminated with a semicolon do not:

Assigning to Multiple Outputs

rand('state', 0);   
A = rand(3,5),   B = ones(3,5) * 4.7;   C = A./B

A =
    0.9501    0.4860    0.4565    0.4447    0.9218
    0.2311    0.8913    0.0185    0.6154    0.7382
    0.6068    0.7621    0.8214    0.7919    0.1763
C =
    0.2022    0.1034    0.0971    0.0946    0.1961
    0.0492    0.1896    0.0039    0.1309    0.1571
    0.1291    0.1621    0.1748    0.1685    0.0375

When a command generates more than one output, specify each output in square brackets to the left of the equals (=) sign. For example, the deal function distributes the values of each of its inputs to separate output variables:

[A, B, C] = deal([-12.3 4.89 -3.01], pi*1.46, diag(12:4:24))
A =
   -12.3000    4.8900   -3.0100
B =
    4.5867
C =
    12     0     0     0
     0    16     0     0
     0     0    20     0
     0     0     0    24

Other types of commands that can yield multiple outputs are assignments of structure and cell arrays, and calls to multiple-output functions. This example generates four outputs and assigns them to separate variables:

A(1).sym='H';  A(2).sym='He';  A(3).sym='Li';  A(4).sym='Be';
[hydrogen helium lithium beryllium] = A.sym

hydrogen =
   H
helium =
   He
lithium =
   Li
beryllium =
   Be

This example calls the fileparts function that returns several outputs, and assigns each output to a variable:

[path file exten] = ...
    fileparts('C:\matlab\work\strarray.mat')

path =
   C:\matlab\work
file =
   strarray
exten =
   .mat

For more information on assigning structure and cell arrays to multiple outputs, see Assigning Struct Values to Separate Variables and Assigning Cell Values to Separate Variables.

For information on assigning functions to multiple outputs, see Assigning Output Arguments.

Assigning Fewer Than the Full Number of Outputs

When assigning structure and cell arrays or when calling multiple-output functions, if you specify fewer output variables than there are return values, MATLAB assigns one return value to each output variable specified and discards the rest. Repeat the last two examples shown above, but specify fewer than the full number of outputs that are available:

[Symbol_1 Symbol_2] = A.symb
Symbol_1 =
   H
Symbol_2 =
   He


[path file] = fileparts('..\work\strarray.mat')
path =
   C:\matlab\work
file = 
   strarray

The deal function , however, does require that you specify the full number of output variables.

Commands that Call MATLAB Functions

When entering commands that call functions in MATLAB, you can use either of two syntaxes: command or function syntax. This is explained in the section Command vs. Function Syntax in the MATLAB Programming Fundamentals documentation.

Plotting Tools — Interactive Plotting

What Are Plotting Tools?

The modular, interactive plotting environment called plotting tools enables you to

  • Create various type of graphs
  • Select variables to plot directly from a workspace browser
  • Easily create and manipulate subplots in the figure
  • Add annotations such as arrows, lines, and text
  • Set properties on graphics objects

You can open and configure plotting tools in many ways. To create a figure with the plotting tools attached, use the plottools command. You can also start the plotting tools from the figure toolbar by clicking the Show Plot Tools icon .

Remove the plotting tools from a figure using the Hide Plot Tools icon .

You can display the three basic plotting tools from the View menu by selecting Figure Palette, Plot Browser, or Property Editor .

The next section describes the individual components making up the plotting tools.

Plotting Tools Interface Overview

The Plotting Tools interface includes three panels that are associated with a figure.

  • Figure Palette — Use to create and arrange subplot axes, view and plot workspace variables, and add annotations. Display the Figure Palette using the figurepalette command.
  • Plot Browser — Use to select and control the visibility of the axes or graphic objects plotted in the figure. You can also add data to any selected axes by clicking the Add Data button. Display the Plot Browser using the plotbrowser command.
  • Property Editor — Use to set common properties of the selected object. You can also open the Property Editor using the propertyeditor command. In the Property Editor you can click the More Properties button to display the Property Inspector, a GUI that displays most object properties and allows you to change any property’s value (unless it is read-only). See Accessing Object Properties with the Property Inspector for details.

The example illustrated below shows the plotting tools attached to a figure containing two subplots of lineseries data. The code to produce the graphs is

x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = sin(x+.25);
y3 = sin(x+.5);
subplot(2,1,1);
plot(x,y1,x,y2,x,y3);
axis tight;
w1 = cos(x);
w2 = cos(x+.25);
w3 = cos(x+.5);
subplot(2,1,2);
plot(x,w1,x,w2,x,w3);
axis tight;

You summon the plotting tools, either by selecting Figure Palette, Plot Browser, and Property Editor from the figure’s View menu, or by typing

plottools

in the Command Window. Typing plottools or plottools on restores the configuration of tools the last time you were using them; use the View menu to show the ones you need and hide the ones you do not, and the mouse to dock and undock them. The default configuration of plotting tools is shown below. MATLAB preferences remember the current arrangement of plot tools — whether they are visible or not — each time you exit; if you want to revert to the default configuration you need to restore the arrangement shown below manually.

Each of the plotting tools shown above can be docked or undocked from its figure, or dismissed by clicking the x at the right end of its titlebar. If you dismiss a tool and want it back again, you can raise it from the View menu or by typing one of several commands. For instance, if you had undocked, and then dismissed the figure palette, you could type either

plottools( ‘on’, ‘figurepalette’) or

figurepalette

Your desktop configuration might then look like this:

Figures Groups. When you activate any plot tool for a figure (or dock the figure in the desktop), the figure becomes part of a Figures group. Figures groups are desktop containers that you can dock in your desktop. Individual figures are not dockable except within the Figures group container. If you create subsequent figures, they will also dock in the Figures group, where they can be panelled or overlapped for viewing. A row of tabs appears along the bottom, one for each figure in the group.

When you dock a plot tool in a figure group and then dock the figure group in the desktop, the tool is included in that section of the desktop as well, as the following illustration shows:

Working with Multiple Figures. When you create a new figure and plot into it, It is created without plotting tools enabled, even if another figure already has them open:

figure
plot(y1,w1)

This generates a freestanding plot, like this:

If you then open the plotting tools for the figure by clicking the Open Plotting Tools icon , the figure docks in the figure window:

The new figure might seem to disappear if the Figures window is hidden, but it will overlay the existing plot within that window (it does not replace it). You can switch between the two figures by clicking the tabs at the bottom of the figure area. Be aware that clicking the x on the right side of a figure’s tab deletes that figure entirely, without asking for confirmation.

If you want to see both figures at once, use the Tiling Palette at the upper right corner of the Figures window to arrange the figures. For example, clicking the Left/Right tiling tool lays out the two figures side by side:

As the above illustrations shows, plot objects can be selected in both figures, but only one figure has focus at a time.

The Figure Palette

The Figure Palette contains three panels. Select the panel you want to view by clicking the respective button, which twists down the panel and exposes its contents.

The Figure Palette enables you to perform the following tasks with these panels:

  • New Subplots — Add 2-D or 3-D axes to the figure.
  • Variables — Browse and plot workspace variables.
  • Annotations — Add annotations to graphs.

Adding Subplot Axes

The New Subplots panel enables you to create a grid of either 2-D or 3-D axes. To display the selector, click the grid icon next to the axes type. A subplot selector grid appears.

As you move the cursor, squares darken to indicate the layout of axes that will be created if you release the mouse button. Click Cancel at the bottom of the grid to leave the figure unchanged.

The picture above shows the New Subplots panel selected to display four equally sized axes in the figure. Existing axes resize as required to accommodate the new layout.

The Variables panel displays current workspace variables. Double-clicking a variable in this panel opens that variable in the Variable Editor. If you select a variable and right-click to display the context menu, you can select a graphics function to plot the variable.

For example, the following picture illustrates how to plot the columns of variable Z. This is equivalent to passing a matrix to the plot function.

The context menu contains a list of possible plot types based on the variable you select and also enables you to perform certain operation on the variable, such as opening it in the Variable Editor, saving, copying, and so on.

The context menu items may change when you select different variables because a particular variable might be incompatible some of the plot types.

You can also drag the variable directly into an axes, in which case MATLAB selects the first appropriate plot type for that variable. If there are multiple axes, you must first select the one you want to plot in and then drag the variable to that axes.

In the previous example, the variable Z would be plotted using the plot function if you were to drag it into an axes.

If the desired plotting function is not available from the context menu, you can select More Plots to display the Plot Catalog tool.

The Plot Catalog tool provides access to most of the MATLAB plotting functions. You can type any workspace variables or MATLAB expressions in the Plotted Variables field, which are then passed to the selected plotting function as arguments. Separate variables with a comma.

You can also enter function handles to pass to one of the “ez…” family of plotting functions from the Analytic Plots category.

[warning]The Plot Catalog does not prevent you from passing inappropriate or insufficient data to a plotting function; if the plot appears to be incorrect or if a plot fails to draw after you press Plot or Plot in New Figure, you should check the Command Window for warning and error messages.[/warning]

The following picture shows the Plot Catalog tool and describes its components.

The Annotations panel enables you to insert annotation objects into a plot. To add an object, first select the object you want to add, and then click and drag the mouse to position and size the object.

See How to Annotate Graphs for more information about the various types of annotation objects.

The Plot Browser

The Plot Browser provides a legend of all the graphs in the figure. It lists each axes and the objects (lines, surfaces, etc.) used to create the graph.

For example, suppose you plot an 11-by-11 matrix z. The plot function creates one line for each column in z.

plot(z,'DisplayName','z')

When you set the DisplayName property, the Plot Browser indicates which line corresponds to which column.

If you want to set the properties of an individual line, double-click on the line in the Plot Browser. Its properties are displayed in the Property Editor, which opens on the bottom of the figure.

You can select a line in the graph, and the corresponding entry in the Plot Browser is highlighted, enabling you to see which column in the variable produced the line.

The check box next to each item in the Plot Browser controls the object’s visibility. For example, suppose you want to plot only certain columns of data in z, perhaps the positive values. You can deselect the columns you do not want to display. The graph updates as you deselect each box and rescales the axes as required.

You can delete any selected item in the Plot Browser by selecting Delete from the right-click context menu.

The Plot Browser provides the mechanism by which you add data to axes. The procedure is as follows:

  • Select a 2-D or 3-D axes from the New Subplots subpanel.
  • After creating the axes, select it in the Plot Browser panel to enable the Add Data button at the bottom of the panel.
  • Click the Add Data button to display the Add Data to Axes dialog.

The Add Data to Axes dialog enables you to select a plot type and specify the workspace variables to pass to the plotting function. You can also specify a MATLAB expression, which is evaluated to produce the data to plot.

Selecting Workspace Variables to Create a Graph. Suppose you want to create a surface graph from three workspace variables defining the XData, YData, and ZData (see the surf function for more information on this type of graph).

In the workspace you have defined three variables, x, y, and z. To create the graph, configure the Add Data to Axes dialog as shown in the following picture.

Using a MATLAB Expression to Create a Graph. The following picture shows the Add Data to Axes dialog specifying a workspace variable x for the plot’s x data and a MATLAB expression (x.^2 + 3*x + 5) for the y data.

You can use the default X Data value of index if you do not want to specify x data. In this case, the y data versus the index of the y data values are plotted, which is equivalent to calling the plot command with only one argument.

The Property Editor

The Property Editor enables you to access a subset of the selected object’s properties. When no object is selected, the Property Editor displays the figure’s properties.

Ways to Display the Property Editor

There are a variety of ways to display the Property Editor:

  • Double-click an object when plot edit mode is enabled.
  • Select an object and right-click to display its context menu, then select Properties.
  • Select Property Editor from the View menu.
  • Use the propertyeditor command.

Changing Plot Types

You can use the property editor to change the type of plot used to display data. For example, you can change the following line graph to a stem, stairs, area, or bar graph by changing the Plot Type field.

Accessing Object Properties with the Property Inspector

The Property Editor enables you to change the most commonly used object properties. To access more object properties, use the Property Inspector. Open the Property Inspector by clicking the More Properties button on the Property Editor or by typing inspect in the Command Window. The following picture shows the Property Inspector displaying the properties of the same lineseries object as that in the previous picture.

The default view of properties is an alphabetic list; you can change to a tree view by clicking the icon in the upper left corner containing plus marks. Click the “AZ” icon to its right to return to an alphabetized list view. Properties that contain fields, such as RGB color components, have a plus mark to their left you can click to expose the individual values. You can change properties that have enumerated values, such as Marker, via drop-down lists (downward-pointing triangles on the right edge of the inspector window). The following figure shows the Marker property being set to diamond using the Property Inspector (note the tree view in which other groups of properties have been collapsed):

There are a few properties of objects that the Property Inspector does not show, for example Parent and Children. For complete descriptions of the properties of graphics objects, use the Handle Graphics Property Browser.

Getting Help for Object Properties

If you are not sure what a property does or what values it can take on, you can get a description of it from the Property Inspector. To do so, right-click on the name or values of a property and select What’s This from the popup menu; a Help window opens displaying the property reference page for the current object, scrolled to the property you clicked. The following picture shows how this works:

If you want to access the properties of light or uicontextmenus objects, you need to get the handle using MATLAB commands, because you cannot click on these objects.

For example, to get the handles of all light objects in the current axes, use findobj.

h = findobj(gca,'Type','light');

Then use the inspect command to display the Property Inspector.

inspect(h)    % Inspect all light objects
inspect(h(1)) % Inspect the first light object in list

Marking Up Graphs with Data Brushing

What Is Data Brushing?

When you brush data, you manually select observations on an interactive data display in the course of assessing validity, testing hypotheses, or segregating observations for further processing. You can brush data on 2-D graphs, 3-D graphs, and surfaces. Most of the MATLAB high-level plotting functions allow you to brush on their displays. For a list of restrictions, see Plot Types You Cannot Brush in the brush function reference page, which also illustrates the types of graphs you can brush.

[warning]Data brushing is a MATLAB figure interactive mode like zooming, panning or plot editing. Unlike plot edit mode, in which you can affect a graph’s appearance and compose annotations but cannot manipulate its data, in data brushing mode you can select, remove, and replace individual data values.
Data brushing mode applies to an entire figure and all axes within it that contain brushable data.[/warning]

Activate data brushing in any of these ways:

  • Click the Data Brushing tool button on the figure toolbar.
  • Click the Data Brushing tool button in the Variable Editor toolbar.
  • Select Brush from the figure Tools menu.
  • Call the brush function.

By default, data brushing is off. The Data Brushing tool button contains two parts and has a dual role:

  • When you click the tool icon on its left side, it toggles data brushing mode on and off.
  • When you click the down arrow on its right side, it displays a drop-down menu for choosing a color for brushing data.

You can set the color with the brush function as well; it accepts colorspec names and RGB triplets. For example:

brush magenta
brush([.1 .3 .5])

The figures below show a scatter plot before and after brushing some outlying observations; the left-hand plot displays the Data Brushing tool palette for choosing a brush color. The information bar informs you that data brushing and linking are available for figures and contains hyperlinks to this page and other documentation. Once you dismiss this information bar by clicking the X on its right-hand side, it only reappears on subsequent plots if you select Show linking and brushing message bar in the MATLAB Preferences Confirmation Dialogs pane.

How to Brush Data

To brush observations on graphs and surface plots,

  • To enter brushing mode, select the Data Brushing tool; click the icon on the left side to activate the mode, and optionally select a brushing color by clicking the arrow on its right side.
  • Drag a selection rectangle to highlight observations on a graph in the current brushing color.
    Instead of dragging out a rectangle, you can click any observation to select it. Double-clicking selects all the observations in a series.
  • To add other observations to the highlighted set, hold down the Shift key and brush them.
  • Shift+clicking or Shift+dragging highlighted observations eliminates their highlighting and removes them from the selection set; this lets you select any set of observations.

Brushed observations remain brushed even in other modes (pan, zoom, edit) until you deselect them by brushing an empty area or by selecting Clear all brushing from the context menu. You can add and remove data tips to a brushed plot without disturbing its brushing.

Once you have brushed observations from one or more graphed variables, you can perform several tasks with the brushing set, either from the Tools menu or by right-clicking any brushed observation:

  • Remove all brushed observations from the plot.
  • Remove all unbrushed observations from the plot.
  • Replace the brushed observations with NaN or constant values.
  • Copy the brushed data values to the clipboard.
  • Paste the brushed data values to the command window
  • Create a variable to hold the brushed data values
  • Clear brushing marks from the plot (context menu only)

The two following figures show a lineseries plot of a variable, along with constant lines showing its mean and two standard deviations. On the left, the user is brushing observations that lie beyond two standard deviations from the mean. On the right, the user has eliminated these extreme values by selecting Brushing > Remove brushed from the Tools (or context) menu. The plot immediately redisplays with two fewer x- and y-values. The original workspace variable, however, remains unchanged.

Before removing the extreme values, you can save them as a new workspace variable with Tools > Brushing > Create new variable. Doing this opens a dialog box for you to declare a variable name.

Typing extremevals to name the variable and pressing OK to dismiss the dialog produces

extremevals =
   48.0000   25.7000
   50.0000   19.5000

The new variable contains one row per observation selected. The first column contains the x-values and the second column contains the y-values, copied from the lineseries’ XData and YData. In graphs where multiple series are brushed, the Create New Variable dialog box helps you identify what series the new variable should represent, allowing you to select and name one at a time.

Effects of Brushing on Data

Brushing simply highlights data points in a graph, without affecting data on which the plot is based. If you remove brushed or unbrushed observations or replace them with NaN values, the change applies to the XData, YData, and possibly ZData properties of the plot itself, but not to variables in the workspace. You can undo such changes. However, if you replot a brushed graph using the same workspace variables, not only do its brushing marks go away, all removed or replaced values are restored and you cannot undo it. If you want brushing to affect the underlying workspace data, you must link the plot to the variables it displays. See Making Graphs Responsive with Data Linking for more information.

Brushed 3-D Plots

When an axes displays three-dimensional graphics, brushing defines a region of interest (ROI) as an unbounded rectangular prism. The central axis of the prism is a line perpendicular to the plane of the screen. Opposite corners of the prism pass through points defined by the CurrentPoint associated with the initial mouse click and the value of CurrentPoint during the drag. All vertices lying within the rectangular prism ROI highlight as you brush them, even those that are hidden from view.

The next figure contains two views of a brushed ROI on a peaks surfaceplot. On the left plot, only the cross-section of the rectangular prism is visible (the brown rectangle) because the central axis of the prism is perpendicular to the viewing plane. When the viewplsoint rotates by about 90 degrees clockwise (right-hand plot), you see that the prism extends along the initial axis of view and that the brushed region conforms to the surface.

When the same x-, y- or z-variable appears in several plots, brushing observations in one plot highlights the related ones in the others whenever the plots are linked. If the brushed variables are open in the Variable Editor, rows of data containing the brushed observations are highlighted in the brushing color there as well. For more information, see Data Brushing with the Variable Editor.

[warning]You can see brushed observations highlighted in the Variable Editor if you activate the Data Brushing tool on its toolbar. In data brushing mode, you can directly brush data values in the Variable Editor to highlight them on plots. In addition, if you change any values in the Variable Editor, all linked graphs on which they appear reflect those changes.[/warning]

Organizing Plots for Brushing. Data brushing usually involves creating multiple views of related variables on graphs and in tables. Just as computer users organize their virtual desktops in many different ways, you can use various strategies for viewing sets of plots:

  • Multiple overlapping figure windows
  • Tiled figure windows
  • Tabbed figure windows
  • Subplots presenting multiple views

When MATLAB figures are created, by default, they appear as separate windows. Many users keep them as such, arranging, overlapping, hiding and showing them as their work requires. Any figure, however, can dock inside a figure group, which itself can float or dock in the MATLAB desktop. Once docked in a figure group, you can float and overlap the individual plots, tile them in various arrangements, or use tabs to show and hide them.

[warning]For more in formation on managing figure windows, see Floating (Cascaded) Figures in Desktop Example in the MATLAB Desktop documentation. Managing Plotting Tools in the MATLAB Graphics documentation provides related details.[/warning]

Another way of organizing plots is to arrange them as subplots within a single figure window, as illustrated in the example for Linking vs. Refreshing Plots. You create and organize subplots with the subplot function, for which there is no GUI as there is for figure groups. Subplots are useful when you have an idea of how many graphs you want to work with simultaneously and how you want to arrange them (they do not need to be all the same size).

[warning]You can easily set up MATLAB code files to create subplots; see Setting Up Figures in the Graphics documentation.[/warning]

Other Data Brushing Aspects

Not all types of graphs can be brushed, and each type that you can brush is marked up in a particular way. To be brushable, a graphic object must have XDataSource, YDataSource, and where applicable, ZDataSource properties. The one exception is the patch objects produced by the hist function, which are brushable due to the special handling they receive. In order to brush a histogram, you must put the figure containing it into a linked state. For related information, see Plot Objects in the MATLAB Graphics documentation.

The brush function reference page explains how to apply brushing to different graph types, describes how to use different mouse gestures for brushing, and lists graph types that you can and cannot brush. See the following sections:

  • Types of Plots You Can Brush
  • Plot Types You Cannot Brush
  • Mouse Gestures for Data Brushing

Keep in mind that data brushing is a mode that operates on entire figures, like zoom, pan, or other modes. This means that some figures can be in data brushing mode at the same time other figures are in other modes. When you dock multiple figures into a figure group, there is only one toolbar, which reflects the state or mode of whatever figure docked in the group you happen to select. Thus, even when docked, some graphs may be in data brushing mode while others are not.

If an axes contains a plot type that cannot be brushed, you can select the figure’s Data Brushing tool and trace out a rectangle by dragging it, but no brush marks appear. The following figure group contains a histogram and a scatter plot that describe intensity statistics for the image displayed in the middle. Although the graphs are brushable, the image itself is not. Here the graphs are shown brushed, after having linked to their data sources.

When you lay out graphs in subplots within a single figure and enter data brushing mode, all the subplot axes become brushable as long as the graphic objects they contain are brushable. If the figure is also in a linked state, brushing one subplot marks any other in the figure that shares a data source with it. Although this also happens when separate figures are linked and brushed, you can prevent individual figures from being brushed by unlinking them from data sources.

MATLAB GUI (Graphical User Interface) Tutorial for Beginners

[help]Why use a GUI in MATLAB?[/help] The main reason GUIs are used is because it makes things simple for the end-users of the program. If GUIs were not used, people would have to work from the command line interface, which can be extremely difficult and fustrating. Imagine if you had to input text commands to operate your web browser (yes, your web browser is a GUI too!).
It wouldn?t be very practical would it? In this tutorial, we will create a simple GUI that will add together two numbers, displaying the answer in a designated text field.

This tutorial is written for those with little or no experience creating a MATLAB GUI (Graphical User Interface). Basic knowledge of MATLAB is not required, but recommended. MATLAB version 2007a is used in writing this tutorial. Both earlier versions and new versions should be compatible as well (as long as it isn’t too outdated). Lets get started!

Initializing GUIDE (GUI Creator)

First, open up MATLAB. Go to the command window and type in guide.


You should see the following screen appear. Choose the first option Blank GUI (Default).

You should now see the following screen (or something similar depending on what version of MATLAB you are using and what the predesignated settings are):

Before adding components blindly, it is good to have a rough idea about how you want the graphical part of the GUI to look like so that it’ll be easier to lay it out. Below is a sample of what the finished GUI might look like.

Creating m-files in Matlab

Open an edit window where we can write the command lines. Click on the white sheet in the menu under File or simply write edit in the command window. Alternatively File->New ->M-file. The following is written in the edit window:

% M-file created by MatlabTutorials.com
t=0:0.01:10; % t goes from 0 to 10 in steps of 0.01.
y1=sin(t); % everything to the left of the equality sign is an
% assignment, y1 is % variable.
plot(t,y1), grid % plots y1 versus t and puts a grid on the plot.
hold % holds the figure window and allows several plots to be
made in the
% same figure.
y2=sin(2*t); % variable y2 is introduced and calculated.
plot(t,y2) % plots y2 versus t in the same figure window as above.
title('Exercise matlabtutorials.com') % puts a title in our plot.
xlabel('time') % gives a label to the x-axis.
ylabel('y')
legend('sin(t)','sin(2*t)') % puts a box with text for different plots.

Everything that follows the %-character on the same line is regarded a comment and ignored. Also note the semicolon. It prevents output from a command to be printed out in the command window. If the command is a calculation, it is still executed. Save the m-file as exercise.m in directory work. Run the m-file by writing exercise in the command window followed by . The result should be the same that as in the figure below.

Finding maximum and minimum values in arrays

Let’s write a function file range.m that calculates the difference between the maximum and minimum value in a vector. The file should return a reply. Open an edit window. Create a function file like the one below.

% the m-file is created by MatlabCorner.COM
% The m-file calculates the difference between the largest
% and smallest element in vector q.
function r=range(q) % defines a function file range.m
qmax=max(q); % finds the maximum value in the vector q.
qmin=min(q); % finds the minimum -value in the vector q.
r=qmax-qmin; % gives the value that should be returned.

Save the m-file as range.m. Now please enter a vector q=[ 1 3 5 7 9] in the command window. Run the m-file by simply writing range(q) after the prompt in the command window.

range(q) % do not forget to press enter.

Saving your Matlab sessions

Often one wants to save the data or variables to another occasion. Maybe one wants to save the whole Matlab session. This can be done. Commands are put in a m-file but data or variables are stored in a mat-file (binary file) which can be opened with Workspace Browser. First have a look in the workspace to find out how your varables look like. Then save these in a mat-file.

save execution1 % variables will now saved in a mat-file execution1.mat
clear % clears all variables from the present Workspace.
load execution1 % restores all variables stored in the execution1.mat

We can also store everything that is displayed in the command window. Like the whole session both the command lines and the output from Matlab, id est the calculations. This can be done by:

diary exercise % stores the whole session in file exercise(ascii-file)

Everything that follows from now on in the command window will be stored in the ascii-file exercise. Write just anything to get some response from Matlab into the command window. diary off % turns of the storage of the session to the file exercise9. Find the file exercise and see if the content in the file is the same that were displayed in the command window!

Analysis of Functions, Interpolation, Curve Fitting, Integrals and Differential Equations 2

Localize minima and maxima of functions

Let us try to find the local minima and maxima for the function func(x). The interval of interest is [-6 0]. The algorithms are iterative. There are 2 methods to use. The first one decides x in a given interval, and the second one looks for x around an initial guess. To decide the maxima we are looking for an x that minimizes the negative function: -func(x).

fminbnd(func,x1,x2): Gives the x-value for a local minima.

[x,y,flag,info]=fminbnd(func,x1,x2)

As above, but we also get the y-value. Flag gives a positive number, if minima is localized and a negative number otherwise. We store the information about the iterations in the variable info.
fminsearch(func, x0,): Gives the x-value for a local minima somewhere close to the initial guess x0.
Decide the global minima and maxima that exist on the interval -8 to 0 for the function func(x). This gives:

x =
-1.7326
y =
-5.9511
flag =
1

This seems to be true for our function. If we want to find the maxima values, the same command can be used. The only difference will be a minus sign in front of the function. Whenever we call the function fzero. The command looks for a minima but will in fact localize the maxima due to the minus sign. See below!

function f=func(x)
f=-(3*sin(x)-2+cos(x.^2)); % Note the minus sign in front of parenthesis.
>> fminbnd(@func,-8,0)

Look below for the answer. Note that the y-value is negated. Compare the plot func(x to our result below.

x = y =
-1.8691 -5.0046

Our maxima occurs at x=-1.8691, and the value of y becomes y=5.0046. Is this an accurate result according to your opinion?

Interpolation of data sets

Assume that we have made a number of measurements and thereby guessed a function relating the input and output. Then we also have some knowledge of the values between the measured points. This is very common in sampled applications. Think of a sampled continuous sine wave function with a very low sampling frequency. This can be done very simply, if we use a vector x with low resolution. Let us create one. Use the x vector values and calculate the corresponding sine function values and plot it in bellow Figure.

x=0:20;
y=sin(x), plot(x,y),grid



Low resolution sine plot

We could think of it as a rather badly shaped sine wave curve probably due to a too long sampling period. By interpolation one decides on a function P(x) that passes through certain known data points. The interpolated function can be used to calculate the function value approximately for any x. Normally one uses polynomials or functions combined from polynomials (spline functions) to make interpolations, but also sine and cosine waves can be useful.
Now, let us see what happens when we try to make a curve fit 10 random numbers.

y=rand(1,10) % 10 random numbers in a row vector
plot(y,'*')

See the figure below. Investigate whether it is possible to find a polynomial that can be adjusted to the random data.
Enter the figure window under Tools-> Basic Fitting. Mark the ninth-degree polynomial. This gives a polynomial that passes through all random data points. The basic fitting uses the least square method. Even if we use a lower degree it is still the best solution according to the least square method.

Mark the small box show equation. We can then explicitly see the polynomial in the figure window. Remove the ninth-degree polynomial and choose a linear equation instead. Matlab will now try to find the best linear equation. Mark the small box plot residuals. The error residual between each data point and the linear equation is calculated and shown. Despite large discrepancies this is the best first-order polynomial.

The error residual between each data point and the linear equation

We will now try to accomplish the same thing with Matlab commands that we did with the interactive basic fitting in the figure window.

y=rand(1,10), x=1:10;
plot(x,y,'*') ,hold on
p1=polyfit(x,y,1) % Best coefficients for a first order polynomial
% according to the least square method. Stored in
% a ector p1.
p9=polyfit(x,y,9) % Ninth-order coefficients.
xx=1:0.01:10; % Improves the resolution in the x-vector.
p1_func=polyval(p1,xx);% Calculates polynomial values for x-values.
p9_func=polyval(p9,xx);% As above.
plot(xx,p1_func,xx,'',p9_func,'-.')
legend('y=randn(1,10)','linear','9th degree')

The result of the commands can be seen in the figure below. The higher the order of the polynomial, the higher the oscillation between the data points. Notice the huge peaks between values 1 and 2 and 9 and 10. You should have been alarmed if this had been real data and your mission was to find an interpolation function that nicely fits the measurements. It is definitely not common sense to look for a ninth-order polynomial for a data set of 10 points.

The higher the order of the polynomial, the higher the oscillation between the data points

Integrals

Matlab can solve integrals and differential equations with numerical methods. Later on in this course we will show how integrals and differential equations can be solved in Symbolic Math toolbox. Numerical integration in Matlab is performed by the command quad. This stands for numerical quadrature. We can solve integrals only with defined limits. This can be done for single, double and triple integrals. To solve generalized integrals or integrals expressed with symbols, we must use the Symbolic Math toolbox. Let us exemplify with some numerical examples.

Example 1: Single integrals

Decide the integral below.

First we put the integrand in a function file: integrand.m.

function y=integrand(x)
y=sqrt(exp(x));

Write!

I1=quad('integrand',0,10)

Matlab gives:

I1 = 294.8263

It seems reasonable enough, if we plot the function. We can also use quad with a fourth argument, namely the tolerance for the calculation. This decides when the numerical integration will stop. The two following examples can be hard to understand, if one lacks the background of multivariable calculus.

Example 2: Double integrals

Calculate the double integral below.

Make as in the previous example a functionwhere we put the primitive function. We name the m-file as integrand2.m

function z=integrand2(x,y)
z=sqrt(exp(x)).*sqrt(exp(y));

Let us now call the function dblquad instead of it.

I2=dblquad('Integrand2',0,1,0,1)

and the answer is:

I2=1.6834

We will now take a look of the integrated area.

[X,Y]=meshgrid(0:0.1:1,0:0.1:1); % Makes a grid of calculation points.
Z=Integrand2(X,Y); % Calculates the integral.
mesh(X,Y,Z) ; % Makes a plot that connects these points.
% punkter.

The last three lines achieves Figure below.

Double integral

Matlab can also perform triple integrals. This example can be found by help triplequad.

Example 3: Triple integrals

A function f = y*sin(x)+z*cos(x) is integrated for the intervals 0 < x < pi, 0 < y < 1 and -1 < z < 1. This is achieved by:
First we create a function file integrnd.m.

function f = integrnd(x,y,z) % 3 input arguments and 1 output argument.
f = y*sin(x)+z*cos(x);

We refer to this m-file by using its handle. In the matlab command window we simply write:

triplequad(@integrnd,0,pi,0,1,-1,1);

Analysis of Functions, Interpolation, Curve Fitting, Integrals and Differential Equations

In this tutorial we will deal with analysis of functions, interpolation, curve fitting, integrals and differential equations. Firstly, we will need to use polynomials and therefore we have to be familiar with the representation of these. A general polynomial looks like: p(x)=anxn + an-1xn-1 +……….+ a1x + a0 and is represented by a vector in Matlab:
p=[ an an-1 ……. a1 a0 ]

Here we have a list of basic commands dealing with polynomials.

polyval(p,x): Calculates the value of polynomial p for different x. If x is a vector then the polynomial is evaluated for each element in the vector x.
poly(A): Gives a vector that represents the characteristic polynomial for the matrix A.
roots(p): Gives a vector with the zeros for the polynomial p(x)=0.
polyder(p): Gives a vector that represents the time-derivative of the polynomial p(x). The coefficients are sored in the vector p.
conv(p,q): Multiplies the polynomials p and q with each other. Returns a coefficient vector.
polyint(p): Integrates the polynomial p analytically and uses the constant of the integration c. The constant c is assigned to 0, if it is not explicitly given.
residue(p,q): Makes a partial fraction expansion of p(x)/q(x).

Example 1: Zeros of a polynomial

Represent the polynomial p(x)=3x3 + 2x2 -2x + 4 in Matlab and find its zeros. Let’s plot the function and check the zeros. This gives a quick idea of what the function looks like. See the resulting figure below.

 x=-10:0.1:10;
 plot(x,3*x.^3+2*x.^2-2*x+4), title('p(x)=3*x^3+2*x^2-2*x+4')
xlabel('x'), grid

Define the polynomial. The coefficients in the polynomial are arranged in descending order in the vector p. The orders that are nonzero in the polynomial will be represented by zeros in the vector p.

p=[3 2 -2 4] % Represents the coefficients in p(x)

With polyval we can easily calculate the value of the polynomial in different x-values.

polyval(p,6), polyval(p,7), polyval(p, -5)
ans= 712 , ans = 1117 , ans = -311

[help]What do you think? Are these values correct, if we use the plot below? Make some thinking and check your result.[/help]

Plot of a polynomial

Let us try some of the other functions that can be applied to polynomials, like polyder and polyint. They perform the time-derivative and integrate the polynomials p(x)=3x3 + 2x2 -2x + 4. The time-derivative becomes: p’(x)= 9x2 + 4x -2 and integration gives: P(x)= (3/4)x4 + (2/3)x3 – x2 + 4x+C

Now compare what Matlab gives us:

C=1 % C is a integration constant.
Pder=polyder(p), Pint=polyint(p,C)
Pder =
9 4 -2
Pint =
0.7500 0.6667 -1.0000 4.0000 1.0000

[warning]That we only obtain the coefficients in the new polynomials. Introduce another polynomial q(x)=x.[/warning]

q=[1 0]

Multiply the polynomial q(x) with p(x), it becomes: pq(x)= 3x4 + 2x3 – 2x2 + 4x and Matlab gives:

conv(p,q) % Performs a polynomial multiplication of p and q.

ans= 3 2 -2 4 0

Let us continue with other functions. Now, check the zeros in the polynomials. This is done with the Matlab command root.

roots(p) % Gives a vector with zeros to the polynomial p(x).
ans =
-1.6022
0.4678 + 0.7832i
0.4678 - 0.7832i

Above we can see something quite obvious. There are 3 zeros to a third order polynomial. It is nothing to be astounded by, but only one of these zeros is real. Can we foretell this by looking at the plot in first figure in the tutorial. I would say yes, because if we zoom the curve, we can find the zero-crossing. This gives us a real-valued zero. In our example there is only one, but what happens to the other two zeros? Since they are complex-conjugated, they are not visible.

Finally we will also take a look at the residue command. It makes a partial fraction expansion of the polynomials p(x) and q(x). Look at the ratio q(x)/p(x)!

[ t,n,the_rest]=residue(q,p) % There are 3 output arguments from residue.
t =
-0.1090
0.0545 - 0.0687i
0.0545 + 0.0687i
n =
-1.6022
0.4678 + 0.7832i
0.4678 - 0.7832i
the_rest =
[]

A partial fraction expansion looks like: R(x)= t1/ ( x-n1) ) + t2/ ( x-n2) + t3/ ( x-n3) + the_rest

Now let us define a function in Matlab. As you hopefully remember this is nothing more than a m-file. We will call it func.m and it should be used together with an input argument x. X is a real-valued argument.

% The function func.m created by MatlabCorner.Com
function f=func(x)
f=3*sin(x)-2+cos(x.^2);

We will now take a look at a plot of the function, but first we must decide what region we are interested in. See the plot below.

x=-10:0.1:10;
plot(x,func(x)), grid on % Note that: fplot(@func,[-10,10])
title( 'func(x)') % works equally well.

The command fplot accepts a string as an input argument, but also a handle, @func. We will also use handles later when dealing with figure windows for more advanced plotting purposes, as well as when we work with GUI.

Regional Polynomial Plot

In the previous example the zeros for a polynomial were decided with the command roots. Here on the other hand we have no polynomial, but only a function, and we can instead use the command fzero. The fzero command uses a repetetive algorithm. We must always add an initial guess and then the fzero tries to localize a zero closest to the guess.

Assume we would like to find the zero in the interval 0-1 in the example above. The function has an infinite number of zeros outside this interval 0-1. Our guess becomes:

fzero(@funk, 0.5), fzero(@funk, 0.9), fzero(@funk, -1.5)

They all produce the same zero!

ans= 0.3423

Our three guesses seems to use the fact that all of them have the same sign of the time-derivative, which and is why the algorithm converges toward 0.3423. If we change the initial guess to be on the other side of the peak, fzero will give us a new answer (zero).

fzero(@funk, 1.5 )
ans = 1.7053

Controlling Command Window Input and Output

The format Function

The format function controls the numeric format of the values displayed. The function affects only how numbers are displayed, not how MATLAB software computes or saves them. Here are the different formats, together with the resulting output produced from a vector x with components of different magnitudes.

x = [4/3 1.2345e-6]

format short

   1.3333    0.0000

format short e

   1.3333e+000  1.2345e-006

format short g

   1.3333  1.2345e-006

format long

   1.33333333333333   0.00000123450000

format long e

   1.333333333333333e+000    1.234500000000000e-006

format long g

   1.33333333333333               1.2345e-006

format bank

   1.33          0.00

format rat

   4/3          1/810045

format hex

   3ff5555555555555   3eb4b6231abfd271

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.
In addition to the format functions shown above

format compact

suppresses many of the blank lines that appear in the output. This lets you view more information on a screen or window. If you want more control over the output format, use the sprintf and fprintf functions.

Suppressing Output

If you simply type a statement and press Return or Enter, MATLAB automatically displays the results on screen. However, if you end the line with a semicolon, MATLAB performs the computation but does not display any output. This is particularly useful when you generate large matrices. For example,

A = magic(100);

Entering Long Statements

If a statement does not fit on one line, use an ellipsis (three periods), …, followed by Return or Enter to indicate that the statement continues on the next line. For example,

s = 1 -1/2 + 1/3 -1/4 + 1/5 – 1/6 + 1/7 …
– 1/8 + 1/9 – 1/10 + 1/11 – 1/12;
Blank spaces around the =, +, and – signs are optional, but they improve readability.

Command Line Editing

Various arrow and control keys on your keyboard allow you to recall, edit, and reuse statements you have typed earlier. For example, suppose you mistakenly enter

rho = (1 + sqt(5))/2

You have misspelled sqrt. MATLAB responds with
Undefined function or variable ‘sqt’.
Instead of retyping the entire line, simply press the up key. The statement you typed is redisplayed. Use the left key to move the cursor over and insert the missing r. Repeated use of the up key recalls earlier lines. Typing a few characters and then the up key finds a previous line that begins with those characters. You can also copy previously executed statements from the Command History. For more information, see Command History

bsxfun

bsxfun – Apply element-by-element binary operation to two arrays with singleton expansion enabled
Syntax

C = bsxfun(fun,A,B)

Description

C = bsxfun(fun,A,B) applies an element-by-element binary operation to arrays A and B, with singleton expansion enabled. fun is a function handle, and can either be an M-file function or one of the following built-in functions:

@plus Plus

@minus Minus

@times Array multiply

@rdivide Right array divide

@ldivide Left array divide

@power Array power

@max Binary maximum

@min Binary minimum

@rem Remainder after division

@mod Modulus after division

@atan2 Four quadrant inverse tangent

@hypot Square root of sum of squares

@eq Equal

@ne Not equal

@lt Less than

@le Less than or equal to

@gt Greater than

@ge Greater than or equal to

@and Element-wise logical AND

@or Element-wise logical OR

@xor Logical exclusive OR

If an M-file function is specified, it must be able to accept either two column vectors of the same size, or one column vector and one scalar, and return as output a column vector of the size as the input values.

Each dimension of A and B must either be equal to each other, or equal to 1. Whenever a dimension of A or B is singleton (equal to 1), the array is virtually replicated along the dimension to match the other array. The array may be diminished if the corresponding dimension of the other array is 0.

The size of the output array C is equal to:

max(size(A),size(B)).*(size(A)>0 & size(B)>0).

Examples

In this example, bsxfun is used to subtract the column means from the corresponding columns of matrix A.

A = magic(5);
A = bsxfun(@minus, A, mean(A))
A =

     4    11   -12    -5     2
    10    -8    -6     1     3
    -9    -7     0     7     9
    -3    -1     6     8   -10
    -2     5    12   -11    -4

arrayfun

arrayfun – Apply function to each element of array

Syntax

A = arrayfun(fun, S)
A = arrayfun(fun, S, T, ...)
[A, B, ...] = arrayfun(fun, S, ...)
[A, ...] = arrayfun(fun, S, ..., 'param1', value1, ...)

Description

A = arrayfun(fun, S) applies the function specified by fun to each element of array S, and returns the results in array A. The value A returned by arrayfun is the same size as S, and the (I,J,…)th element of A is equal to fun(S(I,J,…)). The first input argument fun is a function handle to a function that takes one input argument and returns a scalar value. fun must return values of the same class each time it is called.

If fun is bound to more than one built-in or M-file (that is, if it represents a set of overloaded functions), then the class of the values that arrayfun actually provides as input arguments to fun determines which functions are executed.

The order in which arrayfun computes elements of A is not specified and should not be relied upon.

A = arrayfun(fun, S, T, …) evaluates fun using elements of the arrays S, T, … as input arguments. The (I,J,…)th element of A is equal to fun(S(I,J,…), T(I,J,…), …). All input arguments must be of the same size.

[A, B, …] = arrayfun(fun, S, …) evaluates fun, which is a function handle to a function that returns multiple outputs, and returns arrays A, B, …, each corresponding to one of the output arguments of fun. arrayfun calls fun each time with as many outputs as there are in the call to arrayfun. fun can return output arguments having different classes, but the class of each output must be the same each time fun is called.

[A, …] = arrayfun(fun, S, …, ‘param1’, value1, …) enables you to specify optional parameter name and value pairs. Parameters recognized by arrayfun are shown below. Enclose each parameter name with single quotes.

UniformOutput

A logical 1 (true) or 0 (false), indicating whether or not the outputs of fun can be returned without encapsulation in a cell array.

If true (the default), fun must return scalar values that can be concatenated into an array. These values can also be a cell array. If false, arrayfun returns a cell array (or multiple cell arrays), where the (I,J,…)th cell contains the value fun(S(I,J,…), …).

ErrorHandler

A function handle, specifying the function that arrayfun is to call if the call to fun fails. If an error handler is not specified, arrayfun rethrows the error from the call to fun.

Remarks

The MATLAB software provides two functions that are similar to arrayfun; these are structfun and cellfun. With structfun, you can apply a given function to all fields of one or more structures. With cellfun, you apply the function to all cells of one or more cell arrays.

Examples

Example 1 — Operating on a Single Input.

Create a 1-by-15 structure array with fields f1 and f2, each field containing an array of a different size. Make each f1 field be unequal to the f2 field at that same array index:

for k=1:15
   s(k).f1 = rand(k+3,k+7) * 10;
   s(k).f2 = rand(k+3,k+7) * 10;
end

Set three f1 fields to be equal to the f2 field at that array index:

s(3).f2 = s(3).f1;
s(9).f2 = s(9).f1;
s(12).f2 = s(12).f1;

Use arrayfun to compare the fields at each array index. This compares the array of s(1).f1 with that of s(1).f2, the array of s(2).f1 with that of s(2).f2, and so on through the entire structure array.

The first argument in the call to arrayfun is an anonymous function. Anonymous functions return a function handle, which is the required first input to arrayfun:

z = arrayfun(@(x)isequal(x.f1, x.f2), s)
z =
   0  0  1  0  0  0  0  0  1  0  0  1  0  0  0

Example 2 — Operating on Multiple Inputs.

This example performs the same array comparison as in the previous example, except that it compares the same field of more than one structure array rather than different fields of the same structure array. This shows how you can use more than one array input with arrayfun.

Make copies of array s, created in the last example, to arrays t and u.

t = s;   u = s;

Make one element of structure array t unequal to the same element of s. Do the same with structure array u:

t(4).f1(12)=0;
u(14).f1(6)=0;

Compare field f1 of the three arrays s, t, and u:

z = arrayfun(@(a,b,c)isequal(a.f1, b.f1, c.f1), s, t, u)
z =
   1  1  1  0  1  1  1  1  1  1  1  1  1  0  1

Example 3 — Generating Nonuniform Output.

Generate a 1-by-3 structure array s having random matrices in field f1:

rand('state', 0);
s(1).f1 = rand(7,4) * 10;
s(2).f1 = rand(3,7) * 10;
s(3).f1 = rand(5,5) * 10;

Find the maximum for each f1 vector. Because the output is nonscalar, specify the UniformOutput option as false:

sMax = arrayfun(@(x) max(x.f1), s, 'UniformOutput', false)
sMax = 
    [1x4 double]    [1x7 double]    [1x5 double]

sMax{:}
ans =
  9.5013  9.2181  9.3547  8.1317
ans =
  2.7219  9.3181  8.4622  6.7214  8.3812   8.318  7.0947
ans =
  6.8222  8.6001  8.9977  8.1797  8.385

Find the mean for each f1 vector:

sMean = arrayfun(@(x) mean(x.f1), s, ...
                'UniformOutput', false)
sMean = 
    [1x4 double]    [1x7 double]    [1x5 double]

sMean{:}
ans =
  6.2628  6.2171  5.4231  3.3144
ans =
  1.6209   7.079  5.7696  4.6665  5.1301  5.7136  4.8099
ans =
  3.8195  5.8816  6.9128  4.9022  5.9541

Example 4 — Assigning to More Than One Output Variable.

The next example uses the lu function on the same structure array, returning three outputs from arrayfun:

[l u p] = arrayfun(@(x)lu(x.f1), s, 'UniformOutput', false)
l = 
    [7x4 double]    [3x3 double]    [5x5 double]
u = 
    [4x4 double]    [3x7 double]    [5x5 double]
p = 
    [7x7 double]    [3x3 double]    [5x5 double]

l{3}
ans =
       1          0         0         0         0
  0.44379         1         0         0         0
  0.79398   0.79936         1         0         0
  0.27799  0.066014  -0.77517         1         0
  0.28353   0.85338   0.29223   0.67036         1

u{3}
ans =
   6.8222    3.7837    8.9977    3.4197    3.0929
        0    6.9209    4.2232    1.3796    7.0124
        0         0   -4.0708  -0.40607   -2.3804
        0         0         0    6.8232    2.1729
        0         0         0         0  -0.35098

p{3}
ans =
     0     0     1     0     0
     0     0     0     1     0
     0     0     0     0     1
     1     0     0     0     0
     0     1     0     0     0

idivide

idivide – Integer division with rounding option
Syntax

C = idivide(A, B, opt)
C = idivide(A, B)
C = idivide(A, B, 'fix')
C = idivide(A, B, 'round')
C = idivide(A, B, 'floor')
C = idivide(A, B, 'ceil')

Description

C = idivide(A, B, opt) is the same as A./B for integer classes except that fractional quotients are rounded to integers using the optional rounding mode specified by opt. The default rounding mode is ‘fix’. Inputs A and B must be real and must have the same dimensions unless one is a scalar. At least one of the arguments A and B must belong to an integer class, and the other must belong to the same integer class or be a scalar double. The result C belongs to the integer class.

C = idivide(A, B) is the same as A./B except that fractional quotients are rounded toward zero to the nearest integers.

C = idivide(A, B, ‘fix’) is the same as the syntax shown immediately above.

C = idivide(A, B, ’round’) is the same as A./B for integer classes. Fractional quotients are rounded to the nearest integers.

C = idivide(A, B, ‘floor’) is the same as A./B except that fractional quotients are rounded toward negative infinity to the nearest integers.

C = idivide(A, B, ‘ceil’) is the same as A./B except that the fractional quotients are rounded toward infinity to the nearest integers.
Examples

a = int32([-2 2]);
b = int32(3);

idivide(a,b)             % Returns [0 0]
idivide(a,b,'floor')     % Returns [-1 0]
idivide(a,b,'ceil')      % Returns [0 1]
idivide(a,b,'round')     % Returns [-1 1]

floor

floor – Round toward negative 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 

fix

fix Round towards zero.
fix(X) rounds the elements of X to the nearest integers
towards zero.
Syntax

B = fix(A)

Description

B = fix(A) rounds the elements of A toward zero, resulting in an array of integers. 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

fix(a)

ans =
  Columns 1 through 4 
  -1.0000        0             3.0000        5.0000          

  Columns 5 through 6 
   7.0000        2.0000 + 3.0000i

round

round Round towards nearest integer.
round(X) rounds the elements of X to the nearest integers.

See also floor, ceil, fix.

Syntax

Y = round(X)
Description

Y = round(X) rounds the elements of X to the nearest integers. For complex X, 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

round(a)

ans =
  Columns 1 through 4 
  -2.0000                  0             3.0000             6.0000 
  Columns 5 through 6 
   7.0000             2.0000 + 4.0000i 

Introduction to Vectors in Matlab

Defining a Vector
vek
Matlab is a software package that makes it easier for you to enter matrices and vectors, and manipulate them. The interface follows a language that is designed to look a lot like the notation use in linear algebra. In the following tutorial, we will discuss some of the basics of working with vectors.

If you are running windows or Mac OSX, you can start matlab by choosing it from the menu. To start matlab on a unix system, open up a unix shell and type the command to start the software: matlab. This will start up the software, and it will wait for you to enter your commands. In the text that follows, any line that starts with two greater than signs (>>) is used to denote the matlab command line. This is where you enter your commands.

Almost all of Matlab’s basic commands revolve around the use of vectors. A vector is defined by placing a sequence of numbers within square braces:

>> v = [3 1]

v =

     3     1

This creates a row vector which has the label “v”. The first entry in the vector is a 3 and the second entry is a 1. Note that matlab printed out a copy of the vector after you hit the enter key. If you do not want to print out the result put a semi-colon at the end of the line:

>> v = [3 1];
>>

If you want to view the vector just type its label:

>> v 

v =

     3     1

You can define a vector of any size in this manner:

>> v = [3 1 7 -21 5 6]

v =

     3     1    7    -21    5    6

Notice, though, that this always creates a row vector. If you want to create a column vector you need to take the transpose of a row vector. The transpose is defined using an apostrophe (“‘”):

>> v = [3 1 7 -21 5 6]'

v =

     3
     1
     7
   -21
     5
     6

A common task is to create a large vector with numbers that fit a repetitive pattern. Matlab can define a set of numbers with a common increment using colons. For example, to define a vector whose first entry is 1, the second entry is 2, the third is three, up to 8 you enter the following:

>> v = = [1:8]

v =

     1     2     3     4     5     6     7     8

If you wish to use an increment other than one that you have to define the start number, the value of the increment, and the last number. For example, to define a vector that starts with 2 and ends in 4 with steps of .25 you enter the following:

>> v = [2:.25:4]

v =

  Columns 1 through 7

    2.0000    2.2500    2.5000    2.7500    3.0000    3.2500    3.5000

  Columns 8 through 9

    3.7500    4.0000

Accessing elements within a vector

You can view individual entries in this vector. For example to view the first entry just type in the following:

>> v(1)

ans =

     2

This command prints out entry 1 in the vector. Also notice that a new variable called ans has been created. Any time you perform an action that does not include an assignment matlab will put the label ans on the result.

To simplify the creation of large vectors, you can define a vector by specifying the first entry, an increment, and the last entry. Matlab will automatically figure out how many entries you need and their values. For example, to create a vector whose entries are 0, 2, 4, 6, and 8, you can type in the following line:

>> 0:2:8

ans =

     0     2     4     6     8

Matlab also keeps track of the last result. In the previous example, a variable “ans” is created. To look at the transpose of the previous result, enter the following:

>> ans'

ans =

     0
     2
     4
     6
     8

To be able to keep track of the vectors you create, you can give them names. For example, a row vector v can be created:

>> v = [0:2:8]

v =

     0     2     4     6     8

>> v

v =

     0     2     4     6     8

>> v;
>> v'

ans =

     0
     2
     4
     6
     8

Note that in the previous example, if you end the line with a semi-colon, the result is not displayed. This will come in handy later when you want to use Matlab to work with very large systems of equations.

Matlab will allow you to look at specific parts of the vector. If you want to only look at the first three entries in a vector you can use the same notation you used to create the vector:

>> v(1:3)

ans =

     0     2     4

>> v(1:2:4)

ans =

     0     4

>> v(1:2:4)'

ans =

     0
     4

Basic operations on vectors

Once you master the notation you are free to perform other operations:

>> v(1:3)-v(2:4)

ans =

    -2    -2    -2

For the most part Matlab follows the standard notation used in linear algebra. We will see later that there are some extensions to make some operations easier. For now, though, both addition subtraction are defined in the standard way. For example, to define a new vector with the numbers from 0 to -4 in steps of -1 we do the following:

>> u = [0:-1:4]
u = [0:-1:-4]

u =

     0    -1    -2    -3    -4

We can now add u and v together in the standard way:

>> u+v

ans =

     0     1     2     3     4

Additionally, scalar multiplication is defined in the standard way. Also note that scalar division is defined in a way that is consistent with scalar multiplication:

>> -2*u

ans =

     0     2     4     6     8

>> v/3

ans =

         0    0.6667    1.3333    2.0000    2.6667

With these definitions linear combinations of vectors can be easily defined and the basic operations combined:

>> -2*u+v/3

ans =

         0    2.6667    5.3333    8.0000   10.6667

You will need to be careful. These operations can only be carried out when the dimensions of the vectors allow it. You will likely get used to seeing the following error message which follows from adding two vectors whose dimensions are different:

>> u+v’
??? Error using ==> plus
Matrix dimensions must agree.

accumarray

Construct array with accumulation

Syntax

A = accumarray(subs,val)
A = accumarray(subs,val,sz)
A = accumarray(subs,val,sz,fun)
A = accumarray(subs,val,sz,fun,fillval)
A = accumarray(subs,val,sz,fun,fillval,issparse)
A = accumarray({subs1, subs2, …}, val, …)

Description

accumarray groups elements from a data set and applies a function to each group. A = accumarray(subs,val) creates an array A by accumulating elements of the vector val using the elements of subs as indices. The position of an element in subs determines which value of vals it selects for the accumulated vector; the value of an element in subs determines the position of the accumulated vector in the output.

A = accumarray(subs,val,sz) creates an array A with size sz, where sz is a vector of positive integers. If subs is nonempty with N>1 columns, then sz must have N elements, where all(sz >= max(subs,[],1)). If subs is a nonempty column vector, then sz must be [M 1], where M >= MAX(subs). Specify sz as [] for the default behavior.

A = accumarray(subs,val,sz,fun) applies function fun to each subset of elements of val. The default accumulating function is sum. To specify another function fun, use the @ symbol (e.g., @max). The function fun must accept a column vector and return a numeric, logical, or character scalar, or a scalar cell. Return value A has the same class as the values returned by fun. Specify fun as [] for the default behavior.

A = accumarray(subs,val,sz,fun,fillval) puts the scalar value fillval in elements of A that are not referred to by any row of subs. For example, if subs is empty, then A is repmat(fillval,sz). fillval and the values returned by fun must belong to the same class. The default value of fillval is 0.

A = accumarray(subs,val,sz,fun,fillval,issparse) creates an array A that is sparse if the scalar input issparse is equal to logical 1 (i.e., true), or full if issparse is equal to logical 0 (false). A is full by default. If issparse is true, then fillval must be zero or [], and val and the output of fun must be double.

A = accumarray({subs1, subs2, …}, val, …) passes multiple subs vectors in a cell array. You can use any of the four optional inputs (sz, fun, fillval, or issparse) with this syntax.

Note If the subscripts in subs are not sorted, fun should not depend on the order of the values in its input data.

The function processes the input as follows:

1.

Find out how many unique indices there are in subs. Each unique index defines a bin in the output array. The maximum index value in subs determines the size of the output array.
2.

Find out how many times each index is repeated.

This determines how many elements of vals are going to be accumulated at each bin in the output array.
3.

Create an output array. The output array is of size max(subs) or of size sz.
4.

Accumulate the entries in vals into bins using the values of the indices in subs and apply fun to the entries in each bin.
5.

Fill the values in the output for positions not referred to by subs. Default fill value is zero; use fillval to set a different value.

Note subs should contain positive integers. subs can also be a cell vector with one or more elements, each element a vector of positive integers. All the vectors must have the same length. In this case, subs is treated as if the vectors formed columns of an index matrix.val must be a numeric, logical, or character vector with the same length as the number of rows in subs. val can also be a scalar whose value is repeated for all the rows of subs.

Examples

Example 1

Create a 5-by-1 vector and sum values for repeated 1-D subscripts:

val = 101:105;
subs = [1; 2; 4; 2; 4]
subs =
     1 
     2 
     4 
     2 
     4 

A = accumarray(subs, val)
A =
   101       % A(1) = val(1) = 101
   206       % A(2) = val(2)+val(4) = 102+104 = 206
     0       % A(3) = 0
   208       % A(4) = val(3)+val(5) = 103+105 = 208

Example 2

Create a 4-by-4 matrix and subtract values for repeated 2-D subscripts:

val = 101:106;
subs=[1 2; 1 2; 3 1; 4 1; 4 4; 4 1];
B = accumarray(subs,val,[],@(x)sum(diff(x)))

B =

     0    -1     0     0
     0     0     0     0
     0     0     0     0
     2     0     0     0

The order of the subscripts matters:

val = 101:106;
subs=[1 2; 3 1; 1 2; 4 4; 4 1; 4 1];
B1 = accumarray(subs,val,[],@(x)sum(diff(x)))

B1 =

     0    -2     0     0
     0     0     0     0
     0     0     0     0
    -1     0     0     0

Example 3

Create a 2-by-3-by-2 array and sum values for repeated 3-D subscripts:

val = 101:105;
subs = [1 1 1; 2 1 2; 2 3 2; 2 1 2; 2 3 2];

A = accumarray(subs, val)
A(:,:,1) =
   101     0     0
     0     0     0
A(:,:,2) =
     0     0     0
   206     0   208

Example 4

Create a 2-by-3-by-2 array, and sum values natively:

val = 101:105;
subs = [1 1 1; 2 1 2; 2 3 2; 2 1 2; 2 3 2];

A = accumarray(subs, int8(val), [], @(x) sum(x,'native'))
A(:,:,1) =
  101    0    0
    0    0    0
A(:,:,2) =
    0    0    0
  127    0  127

class(A)
ans =
    int8

Example 5

Pass multiple subscript arguments in a cell array.

1.

Create a 12-element vector V:

V = 101:112;

2.

Create three 12-element vectors, one for each dimension of the resulting array A. Note how the indices of these vectors determine which elements of V are accumulated in A:

      %        index 1   index 6 => V(1)+V(6) => A(1,3,1)
      %          |         |
      rowsubs = [1 3 3 2 3 1 2 2 3 3 1 2];
      colsubs = [3 4 2 1 4 3 4 2 2 4 3 4];
      pagsubs = [1 1 2 2 1 1 2 1 1 1 2 2];
      %                |
      %              index 4 => V(4) => A(2,1,2)
      %
      % A(1,3,1) = V(1) + V(6) = 101 + 106 = 207
      % A(2,1,2) = V(4) = 104

3.

Call accumarray, passing the subscript vectors in a cell array:

      A = accumarray({rowsubs colsubs pagsubs}, V)
      A(:,:,1) =
           0     0   207     0        % A(1,3,1) is 207
           0   108     0     0
           0   109     0   317
      A(:,:,2) =
           0     0   111     0
         104     0     0   219        % A(2,1,2) is 104
           0   103     0     0

Example 6

Create an array with the max function, and fill all empty elements of that array with NaN:

val = 101:105;
subs = [1 1; 2 1; 2 3; 2 1; 2 3];

A = accumarray(subs, val, [2 4], @max, NaN)
A =
   101   NaN   NaN   NaN
   104   NaN   105   NaN

Example 7

Create a sparse matrix using the prod function:

val = 101:105;
subs = [1 1; 2 1; 2 3; 2 1; 2 3];

A = accumarray(subs, val, [2 4], @prod, 0, true)
A =
   (1,1)            101
   (2,1)          10608
   (2,3)          10815

Example 8

Count the number of entries accumulated in each bin:

val = 1;
subs = [1 1; 2 1; 2 3; 2 1; 2 3];

A = accumarray(subs, val, [2 4])
A =
     1     0     0     0
     2     0     2     0

Example 9

Create a logical array that shows which bins will accumulate two or more values:

val = 101:105;
subs = [1 1; 2 1; 2 3; 2 1; 2 3];

A = accumarray(subs, val, [2 4], @(x) length(x) > 1)
A =
     0     0     0     0
     1     0     1     0

Example 10

Group values in a cell array:

val = 101:105;
subs = [1 1; 2 1; 2 3; 2 1; 2 3];

A = accumarray(subs, val, [2 4], @(x) {x})
A = 
    [       101]     []              []     []
    [2x1 double]     []    [2x1 double]     []

A{2}
ans =
   104
   102

See Also

full, sparse, sum

abs

Absolute value and complex magnitude
Syntax

abs(X)

Description

abs(X) returns an array Y such that each element of Y is the absolute value of the corresponding element of X.

If X is complex, abs(X) returns the complex modulus (magnitude), which is the same as

sqrt(real(X).^2 + imag(X).^2)

Examples

abs(-5)
ans =
     5

abs(3+4i)
ans =
     5

See Also

angle, sign, unwrap

plot

plot Linear plot.
plot(X,Y) plots vector Y versus vector X. If X or Y is a matrix,
then the vector is plotted versus the rows or columns of the matrix,
whichever line up. If X is a scalar and Y is a vector, length(Y)
disconnected points are plotted.

plot(Y) plots the columns of Y versus their index.
If Y is complex, plot(Y) is equivalent to plot(real(Y),imag(Y)).
In all other uses of PLOT, the imaginary part is ignored.

Various line types, plot symbols and colors may be obtained with
plot(X,Y,S) where S is a character string made from one element
from any or all the following 3 columns:

y yellow . point – solid
m magenta o circle : dotted
c cyan x x-mark -. dashdot
r red + plus — dashed
g green * star
b blue s square
w white d diamond
k black v triangle (down)
^ triangle (up)
< triangle (left) > triangle (right)
p pentagram
h hexagram

For example, plot(X,Y,’c+:’) plots a cyan dotted line with a plus
at each data point; plot(X,Y,’bd’) plots blue diamond at each data
point but does not draw any line.

plot(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,…) combines the plots defined by
the (X,Y,S) triples, where the X’s and Y’s are vectors or matrices
and the S’s are strings.

For example, plot(X,Y,’y-‘,X,Y,’go’) plots the data twice, with a
solid yellow line interpolating green circles at the data points.

The plot command, if no color is specified, makes automatic use of
the colors specified by the axes ColorOrder property. The default
ColorOrder is listed in the table above for color systems where the
default is yellow for one line, and for multiple lines, to cycle
through the first six colors in the table. For monochrome systems,
plot cycles over the axes LineStyleOrder property.

plot returns a column vector of handles to LINE objects, one
handle per line.

The X,Y pairs, or X,Y,S triples, can be followed by
parameter/value pairs to specify additional properties
of the lines.

See also semilogx, semilogy, loglog, grid, clf, clc, title, xlabel,
ylabel, axis, axes, hold, colordef, legend, subplot, and stem.

ver

ver MATLAB, SIMULINK, and TOOLBOX version information.
ver displays the current MATLAB and toolbox version numbers.
ver(TOOLBOX_DIR) displays the current version information for the
toolbox specified by the string TOOLBOX_DIR.

For example,
ver control
returns the version info for the Control System Toolbox.

For tips on how to hook your toolboxes into ver ‘type ver.m’.

See also version, hostid, license, info, whatsnew.

type

type List M-file.
type foo.bar lists the ascii file called ‘foo.bar’.
type foo lists the ascii file called ‘foo.m’.

If files called foo and foo.m both exist, then
type foo lists the file ‘foo’, and
type foo.m list the file ‘foo.m’.

type FILENAME lists the contents of the file given a full pathname
or a MATLABPATH relative partial pathname (see PARTIALPATH).

See also dbtype, which, help, partialpath.

save

SAVE Save workspace variables to disk.
SAVE FILENAME saves all workspace variables to the binary “MAT-file”
named FILENAME.mat. The data may be retrieved with LOAD. If FILENAME
has no extension, .mat is assumed.

SAVE, by itself, creates the binary “MAT-file” named ‘matlab.mat’. It is
an error if ‘matlab.mat’ is not writable.

SAVE FILENAME X saves only X.
SAVE FILENAME X Y Z saves X, Y, and Z. The wildcard ‘*’ can be used to
save only those variables that match a pattern.

ASCII Options:
SAVE … -ASCII uses 8-digit ASCII form instead of binary regardless
of file extension.
SAVE … -ASCII -DOUBLE uses 16-digit ASCII form.
SAVE … -ASCII -TABS delimits with tabs.
SAVE … -ASCII -DOUBLE -TABS 16-digit, tab delimited.

MAT Options:
SAVE … -MAT saves in MAT format regardless of extension.
SAVE … -V4 saves a MAT-file that MATLAB 4 can LOAD.
SAVE … -APPEND adds the variables to an existing file (MAT-file only).

When using the -V4 option, variables that incompatible with MATLAB 4 are
not saved to the MAT-file. For example, ND arrays, structs, cells, etc.
cannot be saved to a MATLAB 4 MAT-file. Also, variables with names that
are longer than 19 characters cannot be saved to a MATLAB 4 MAT-file.

Use the functional form of SAVE, such as SAVE(‘filename’,’var1′,’var2′),
when the filename or variable names are stored in strings.

See also LOAD, DIARY, FWRITE, FPRINTF, UISAVE, FILEFORMATS.

Overloaded methods
help activex/save.m

rmpath

rmpath Remove directory from search path.
rmpath DIRNAME removes the specified directory from the
current matlabpath.

rmpath DIR1 DIR2 DIR3 removes all the specified directories
from the path.

Use the functional form of RMPATH, such as rmpath(‘dir1′,’dir2’,…),
when the directory specification is stored in a string.

Examples

        rmpath c:\matlab\work
        rmpath /home/user/matlab

See also addpath, path, rehash

quit

quit Quit MATLAB session.
quit terminates MATLAB after running the script FINISH.M,
if it exists. The workspace information will not be saved
unless FINISH.M calls SAVE. If an error occurs while
executing FINISH.M, quitting is cancelled.

quit FORCE can be used to bypass an errant FINISH.M that
will not let you quit.

quit CANCEL can be used in FINISH.M to cancel quitting.
It has no effect anywhere else.

Example
Put the following lines of code in your FINISH.M file to
display a dialog that allows you to cancel quitting.

          button = questdlg('Ready to quit?', ...
                            'Exit Dialog','Yes','No','No');
          switch button
            case 'Yes',
              disp('Exiting MATLAB');
              %Save variables to matlab.mat
              save 
            case 'No',
              quit cancel;
          end

Note: When using Handle Graphics in FINISH.M make sure to use UIWAIT, WAITFOR, or DRAWNOW so that figures are visible.

Path

path Get/set search path.
PATH, by itself, prettyprints MATLAB’s current search path. The
initial search path list is set by PATHDEF, and is perhaps
individualized by STARTUP.

P = path returns a string containing the path in P.
path(P) changes the path to P. path(PATH) refreshes MATLAB’s
view of the directories on the path, ensuring that any changes
to non-toolbox directories are visible.

path(P1,P2) changes the path to the concatenation of the two path
strings P1 and P2. Thus path(PATH,P) appends a new directory to
the current path and path(P,PATH) prepends a new path. If P1 or
P2 are already on the path, they are not added.

For example, the following statements add another directory
to MATLAB’s search path on various operating systems:

Unix:

path(path,'/home/myfriend/goodstuff')

Windows:

path(path,'c:\tools\goodstuff')

See also what, cd, dir, addpath, rmpath, genpath, rehash

Working with Matrices in Matlab

Generating Matrices

MATLAB software provides four functions that generate basic matrices.

zeros All zeros

ones All ones

rand Uniformly distributed random elements

randn Normally distributed random elements

Here are some examples:

Z = zeros(2,4)
Z =
0     0     0     0
0     0     0     0

F = 5*ones(3,3)
F =
5     5     5
5     5     5
5     5     5

N = fix(10*rand(1,10))
N =
9     2     6     4     8     7     4     0     8     4

R = randn(4,4)
R =
0.6353    0.0860   -0.3210   -1.2316
-0.6014   -2.0046    1.2366    1.0556
0.5512   -0.4931   -0.6313   -0.1132
-1.0998    0.4620   -2.3252    0.3792

The load Function

The load function reads binary files containing matrices generated by earlier MATLAB sessions, or reads text files containing numeric data. The text file should be organized as a rectangular table of numbers, separated by blanks, with one row per line, and an equal number of elements in each row. For example, outside of MATLAB, create a text file containing these four lines:

16.0     3.0     2.0    13.0
5.0    10.0    11.0     8.0
9.0     6.0     7.0    12.0
4.0    15.0    14.0     1.0

Save the file as magik.dat in the current directory. The statement

load magik.dat

reads the file and creates a variable, magik, containing the example matrix.

An easy way to read data into MATLAB from many text or binary formats is to use the Import Wizard.

M-Files

You can create your own matrices using M-files, which are text files containing MATLAB code. Use the MATLAB Editor or another text editor to create a file containing the same statements you would type at the MATLAB command line. Save the file under a name that ends in .m.

For example, create a file in the current directory named magik.m containing these five lines:

A = [16.0 3.0 2.0 13.0
5.0 10.0 11.0 8.0
9.0 6.0 7.0 12.0
4.0 15.0 14.0 1.0 ];

The statement

magik

reads the file and creates a variable, A, containing the example matrix.

Concatenation

Concatenation is the process of joining small matrices to make bigger ones. In fact, you made your first matrix by concatenating its individual elements. The pair of square brackets, [], is the concatenation operator. For an example, start with the 4-by-4 magic square, A, and form

B = [A  A+32; A+48  A+16]

The result is an 8-by-8 matrix, obtained by joining the four submatrices:

B =

16     3     2    13    48    35    34    45
5    10    11     8    37    42    43    40
9     6     7    12    41    38    39    44
4    15    14     1    36    47    46    33
64    51    50    61    32    19    18    29
53    58    59    56    21    26    27    24
57    54    55    60    25    22    23    28
52    63    62    49    20    31    30    17

This matrix is halfway to being another magic square. Its elements are a rearrangement of the integers 1:64. Its column sums are the correct value for an 8-by-8 magic square:

sum(B)

ans =
260   260   260   260   260   260   260   260

But its row sums, sum(B’)’, are not all the same. Further manipulation is necessary to make this a valid 8-by-8 magic square.

Deleting Rows and Columns

You can delete rows and columns from a matrix using just a pair of square brackets. Start with

X = A;

Then, to delete the second column of X, use

X(:,2) = []

This changes X to

X =
16     2    13
5    11     8
9     7    12
4    14     1

If you delete a single element from a matrix, the result is not a matrix anymore. So, expressions like

X(1,2) = []

result in an error. However, using a single subscript deletes a single element, or sequence of elements, and reshapes the remaining elements into a row vector. So

X(2:2:10) = []

results in

X =
16     9     2     7    13    12     1

Matlab Expressions

Variables

Like most other programming languages, the MATLAB language provides mathematical expressions, but unlike most programming languages, these expressions involve entire matrices.

MATLAB does not require any type declarations or dimension statements. When MATLAB encounters a new variable name, it automatically creates the variable and allocates the appropriate amount of storage. If the variable already exists, MATLAB changes its contents and, if necessary, allocates new storage. For example,

num_students = 25

creates a 1-by-1 matrix named num_students and stores the value 25 in its single element. To view the matrix assigned to any variable, simply enter the variable name.

Variable names consist of a letter, followed by any number of letters, digits, or underscores. MATLAB is case sensitive; it distinguishes between uppercase and lowercase letters. A and a are not the same variable.

Although variable names can be of any length, MATLAB uses only the first N characters of the name, (where N is the number returned by the function namelengthmax), and ignores the rest. Hence, it is important to make each variable name unique in the first N characters to enable MATLAB to distinguish variables.

N = namelengthmax
N =
63

The genvarname function can be useful in creating variable names that are both valid and unique.

Numbers

MATLAB uses conventional decimal notation, with an optional decimal point and leading plus or minus sign, for numbers. Scientific notation uses the letter e to specify a power-of-ten scale factor. Imaginary numbers use either i or j as a suffix. Some examples of legal numbers are

3              -99            0.0001
9.6397238      1.60210e-20    6.02252e23
1i             -3.14159j      3e5i

All numbers are stored internally using the long format specified by the IEEE® floating-point standard. Floating-point numbers have a finite precision of roughly 16 significant decimal digits and a finite range of roughly 10-308 to 10+308.

MATLAB software stores the real and imaginary parts of a complex number. It handles the magnitude of the parts in different ways depending on the context. For instance, the sort function sorts based on magnitude and resolves ties by phase angle.

sort([3+4i, 4+3i])
ans =
4.0000 + 3.0000i   3.0000 + 4.0000i

This is because of the phase angle:

angle(3+4i)
ans =
0.9273
angle(4+3i)
ans =
0.6435

The “equal to” relational operator == requires both the real and imaginary parts to be equal. The other binary relational operators > <, >=, and <= ignore the imaginary part of the number and consider the real part only.

Operators

Expressions use familiar arithmetic operators and precedence rules.

+

Addition

Subtraction

*

Multiplication

/

Division

\

Left division (described in Linear Algebra in the MATLAB documentation)

^

Power

Complex conjugate transpose

( )

Specify evaluation order

Functions

MATLAB provides a large number of standard elementary mathematical functions, including abs, sqrt, exp, and sin. Taking the square root or logarithm of a negative number is not an error; the appropriate complex result is produced automatically. MATLAB also provides many more advanced mathematical functions, including Bessel and gamma functions. Most of these functions accept complex arguments. For a list of the elementary mathematical functions, type

help elfun

For a list of more advanced mathematical and matrix functions, type

help specfun
help elmat

Some of the functions, like sqrt and sin, are built in. Built-in functions are part of the MATLAB core so they are very efficient, but the computational details are not readily accessible. Other functions, like gamma and sinh, are implemented in M-files.

There are some differences between built-in functions and other functions. For example, for built-in functions, you cannot see the code. For other functions, you can see the code and even modify it if you want.

Several special functions provide values of useful constants.

pi

3.14159265...

i

Imaginary unit,

j

Same as i

eps

Floating-point relative precision,

realmin

Smallest floating-point number,

realmax

Largest floating-point number,

Inf

Infinity

NaN

Not-a-number

Infinity is generated by dividing a nonzero value by zero, or by evaluating well defined mathematical expressions that overflow, i.e., exceed realmax. Not-a-number is generated by trying to evaluate expressions like 0/0 or Inf-Inf that do not have well defined mathematical values.

The function names are not reserved. It is possible to overwrite any of them with a new variable, such as

eps = 1.e-6

and then use that value in subsequent calculations. The original function can be restored with

clear eps

Examples of Expressions

You have already seen several examples of MATLAB expressions. Here are a few more examples, and the resulting values:

rho = (1+sqrt(5))/2
rho =
1.6180

a = abs(3+4i)
a =
5

z = sqrt(besselk(4/3,rho-i))
z =
0.3730+ 0.3214i

huge = exp(log(realmax))
huge =
1.7977e+308

toobig = pi*huge
toobig =
Inf

Manipulating Matrices

Matrices and Magic Squares

Matlab MatrisIn MATLAB, a matrix is a rectangular array of numbers. Special meaning is sometimes attached to 1-by-1 matrices, which are scalars, and to matrices with only one row or column, which are vectors. MATLAB has other ways of storing both numeric and nonnumeric data, but in the beginning, it is usually best to think of everything as a matrix. The operations in MATLAB are designed to be as natural as possible. Where other programming languages work with numbers one at a time, MATLAB allows you to work with entire matrices quickly and easily. A good example matrix, used throughout this book, appears in the Renaissance engraving Melancholia I by the German artist and amateur mathematician Albrecht Dürer.

Matrices and Magic Squares

This image is filled with mathematical symbolism, and if you look carefully, you will see a matrix in the upper right corner. This matrix is known as a magic square and was believed by many in Dürer’s time to have genuinely magical properties. It does turn out to have some fascinating characteristics worth exploring.

Entering Matrices

The best way for you to get started with MATLAB is to learn how to handle matrices. Start MATLAB and follow along with each example.You can enter matrices into MATLAB in several different ways:

  • Enter an explicit list of elements.
  • Load matrices from external data files.
  • Generate matrices using built-in functions.
  • Create matrices with your own functions in M-files.

Start by entering Dürer’s matrix as a list of its elements. You have only to follow a few basic conventions:

  • Separate the elements of a row with blanks or commas.
  • Use a semicolon, ; , to indicate the end of each row.
  • Surround the entire list of elements with square brackets, [ ].

To enter Dürer’s matrix, simply type in the Command Window

A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]

MATLAB displays the matrix you just entered.

A =
16  3  2  13
5  10  11  8
9  6  7  12
4  15  14  1

This exactly matches the numbers in the engraving. Once you have entered the matrix, it is automatically remembered in the MATLAB workspace. You can refer to it simply as A. Now that you have A in the workspace, take a look at what makes it so interesting. Why is it magic?

sum, transpose, and diag

You’re probably already aware that the special properties of a magic square have to do with the various ways of summing its elements. If you take the sum along any row or column, or along either of the two main diagonals, you will always get the same number. Let’s verify that using MATLAB. The first statement to try is

sum(A)

MATLAB replies with

ans =
34 34 34 34

When you don’t specify an output variable, MATLAB uses the variable ans, short for answer, to store the results of a calculation. You have computed a row vector containing the sums of the columns of A. Sure enough, each of the columns has the same sum, the magic sum, 34.

How about the row sums? MATLAB has a preference for working with the columns of a matrix, so the easiest way to get the row sums is to transpose the matrix, compute the column sums of the transpose, and then transpose the result. The transpose operation is denoted by an apostrophe or single quote, ‘.
It flips a matrix about its main diagonal and it turns a row vector into a column vector. So

A’

produces

ans =

A =
16  5  9  4
3  10  6  15
2  11  7  14
13  8  12  1

And

sum(A’)’

produces a column vector containing the row sums

ans =
34
34
34
34

The sum of the elements on the main diagonal is easily obtained with the help of the diag function, which picks off that diagonal.

diag(A)

produces

ans =
16
10
7
1

and

sum(diag(A))

produces

ans =
34

The other diagonal, the so-called antidiagonal, is not so important mathematically, so MATLAB does not have a ready-made function for it. But a function originally intended for use in graphics, fliplr, flips a matrix from left to right.

sum(diag(fliplr(A)))

ans =
34

You have verified that the matrix in Dürer’s engraving is indeed a magic square and, in the process, have sampled a few MATLAB matrix operations. The following sections continue to use this matrix to illustrate additional MATLAB capabilities.{mospagebreak}

Subscripts

The element in row i and column j of A is denoted by A(i,j). For example, A(4,2) is the number in the fourth row and second column. For our magic square, A(4,2) is 15. So it is possible to compute the sum of the elements in the fourth column of A by typing

A(1,4) + A(2,4) + A(3,4) + A(4,4)

This produces

ans =
34

but is not the most elegant way of summing a single column. It is also possible to refer to the elements of a matrix with a single subscript, A(k). This is the usual way of referencing row and column vectors. But it can also apply to a fully two-dimensional matrix, in which case the array is regarded as one long column vector formed from the columns of the original matrix. So, for our magic square, A(8) is another way of referring to the value

15 stored in A(4,2). If you try to use the value of an element outside of the matrix, it is an error.

t = A(4,5)

Index exceeds matrix dimensions. On the other hand, if you store a value in an element outside of the matrix, the size increases to accommodate the newcomer.

X = A;
X(4,5) = 17
X =
16  3  2  13  0
5  10  11  8  0
9  6  7  12  0
4  15  14  1  17

The Colon Operator

The colon, :, is one of MATLAB’s most important operators. It occurs in several different forms. The expression

1:10

is a row vector containing the integers from 1 to 10

1 2 3 4 5 6 7 8 9 10

To obtain nonunit spacing, specify an increment. For example,

100:-7:50

is

100 93 86 79 72 65 58 51

and

0:pi/4:pi

is

0 0.7854 1.5708 2.3562 3.1416

Subscript expressions involving colons refer to portions of a matrix.

A(1:k,j)

is the first k elements of the jth column of A. So

sum(A(1:4,4))

computes the sum of the fourth column. But there is a better way. The colon by itself refers to all the elements in a row or column of a matrix and the keyword end refers to the last row or column. So

sum(A(:,end))

computes the sum of the elements in the last column of A.

ans =
34

Why is the magic sum for a 4-by-4 square equal to 34? If the integers from 1 to 16 are sorted into four groups with equal sums, that sum must be

sum(1:16)/4

which, of course, is

ans = 34

The magic Function

MATLAB actually has a built-in function that creates magic squares of almost any size. Not surprisingly, this function is named magic.

B = magic(4)
B = 16  2  3  13
5  11  10  8
9  7  6  12
4  14  15  1

This matrix is almost the same as the one in the Dürer engraving and has all the same “magic” properties; the only difference is that the two middle columns are exchanged. To make this B into Dürer’s A, swap the two middle columns.   

 A = B(:,[1 3 2 4])

This says “for each of the rows of matrix B, reorder the elements in the order 1, 3, 2, 4.” It produces

A =  
16  3  2  13
5  10  11  8
9  6  7  12
4  15  14  1

Desktop Tools

This section provides an introduction to MATLAB’s desktop tools. You can also use MATLAB functions to perform most of the features found in the desktop tools. The tools are:

  • “Command Window”
  • “Command History”
  • “Launch Pad”
  • “Help Browser”
  • “Current Directory Browser”
  • “Workspace Browser”
  • “Array Editor”
  • “Editor/Debugger”

Command Window

MATLAB Command Window

Use the Command Window to enter variables and run functions and M-files.
For more information on controlling input and output, see “Controlling Command Window Input and Output” on next articles.

Command History

Matlab Command History

Lines you enter in the Command Window are logged in the Command History window. In the Command History, you can view previously used functions, and copy and execute selected lines.

To save the input and output from a MATLAB session to a file, use the diary function.

Running External Programs

You can run external programs from the MATLAB Command Window. The exclamation point character ! is a shell escape and indicates that the rest of the input line is a command to the operating system. This is useful for invoking utilities or running other programs without quitting MATLAB. On Linux, for example,
!emacs magik.m
invokes an editor called emacs for a file named magik.m. When you quit the external program, the operating system returns control to MATLAB.

Launch Pad

Launch Pad

MATLAB’s Launch Pad provides easy access to tools, demos, and documentation.

Help Browser

Use the Help browser to search and view documentation for all your MathWorks products. The Help browser is a Web browser integrated into the MATLAB desktop that displays HTML documents.

Help Browser

To open the Help browser, click the help button {mosimage} in the toolbar, or type helpbrowser in the Command Window.

The Help browser consists of two panes, the Help Navigator, which you use to find information, and the display pane, where you view the information.

Help Navigator

Use to Help Navigator to find information. It includes:

  • Product filterSet the filter to show documentation only for the products you specify.
  • Contents tabView the titles and tables of contents of documentation for your products.
  • Index tab Find specific index entries (selected keywords) in the MathWorks documentation for your products.
  • Search tabLook for a specific phrase in the documentation. To get help for a specific function, set the Search type to Function Name.
  • Favorites tab View a list of documents you previously designated as favorites.

Display Pane

After finding documentation using the Help Navigator, view it in the display pane. While viewing the documentation, you can:

  • Browse to other pages Use the arrows at the tops and bottoms of the pages, or use the back and forward buttons in the toolbar.
  • Bookmark pages – Click the Add to Favorites button in the toolbar.
  • Print pages – Click the print button in the toolbar.
  • Find a term in the page – Type a term in the Find in page field in the toolbar and click Go.

Other features available in the display pane are: copying information, evaluating a selection, and viewing Web pages.

For More Help

In addition to the Help browser, you can use help functions. To get help for a specific function, use doc. For example, doc format displays help for the format function in the Help browser. Other means for getting help include contacting Technical Support (http://www.mathworks.com/support) and participating in the newsgroup for MATLAB users, comp.soft-sys.matlab.{mospagebreak}

Current Directory Browser

MATLAB file operations use the current directory and the search path as reference points. Any file you want to run must either be in the current directory or on the search path.

Current Directory

A quick way to view or change the current directory is by using the Current Directory field in the desktop toolbar as shown below.

Matlab Current Directory

To search for, view, open, and make changes to MATLAB-related directories and files, use the MATLAB Current Directory browser. Alternatively, you can use the functions dir, cd, and delete.

Search Path

To determine how to execute functions you call, MATLAB uses a search path to find M-files and other MATLAB-related files, which are organized in directories on your file system. Any file you want to run in MATLAB must reside in the current directory or in a directory that is on the search path. By default, the files supplied with MATLAB and MathWorks toolboxes are included in the search path.

To see which directories are on the search path or to change the search path, select Set Path from the File menu in the desktop, and use the Set Path dialog box. Alternatively, you can use the path function to view the search path, addpath to add directories to the path, and rmpath to remove directories from
the path.

Workspace Browser

The MATLAB workspace consists of the set of variables (named arrays) built up during a MATLAB session and stored in memory. You add variables to the workspace by using functions, running M-files, and loading saved workspaces.
To view the workspace and information about each variable, use the Workspace browser, or use the functions who and whos.

Matlab Workspace

To delete variables from the workspace, select the variable and select Delete from the Edit menu. Alternatively, use the clear function.

The workspace is not maintained after you end the MATLAB session. To save the workspace to a file that can be read during a later MATLAB session, select Save Workspace As from the File menu, or use the save function. This saves the workspace to a binary file called a MAT-file, which has a .mat extension.There are options for saving to different formats. To read in a MAT-file, select Import Data from the File menu, or use the load function.

Array Editor

Double-click on a variable in the Workspace browser to see it in the Array Editor. Use the Array Editor to view and edit a visual representation of one- or two-dimensional numeric arrays, strings, and cell arrays of strings that are in the workspace.

Matlab Array Editor

Editor/Debugger

Use the Editor/Debugger to create and debug M-files, which are programs you write to run MATLAB functions. The Editor/Debugger provides a graphical user interface for basic text editing, as well as for M-file debugging.

Matlab Editör and matlab debugger

You can use any text editor to create M-files, such as Emacs, and can use references (accessible from the desktop File menu) to specify that editor as the default. If you use another editor, you can still use the MATLAB Editor/Debugger for debugging, or you can use debugging functions, such as dbstop, which sets a breakpoint.

If you just need to view the contents of an M-file, you can display it in the Command Window by using the type function.

while

while Repeat statements an indefinite number of times.
The general form of a while statement is:

while expression
statements
END

The statements are executed while the real part of the expression
has all non-zero elements. The expression is usually the result of
expr rop expr where rop is ==, <, >, <=, >=, or ~=.

The BREAK statement can be used to terminate the loop prematurely.

For example (assuming A already defined):

E = 0*A; F = E + eye(size(E)); N = 1;
while norm(E+F-E,1) > 0,
E = E + F;
F = A*F/N;
N = N + 1;
end

See also for, if, switch, break, end.

return

return Return to invoking function.
return causes a return to the invoking function or to the keyboard.
It also terminates the KEYBOARD mode.

Normally functions return when the end of the function is reached.
A return statement can be used to force an early return.

Example

function d = det(A)
if isempty(A)
d = 1;
return
else
...
end

See also function, keyboard.

elseif

elseif IF statement condition.
elseif is used with IF. The statements after the elseif are
executed if the expression is true and all the preceding IF and
elseif expressions are false. An expression is considered true if
the real part has all non-zero elements.

elseif does not need a matching END, while ELSE IF does.

The general form of the IF statement is
IF expression
statements
elseif expression
statements
ELSE
statements
END

See also if, else, end.

if

if if statement condition.
The general form of the if statement is

if expression
statements
ELSEIF expression
statements
ELSE
statements
END

The statements are executed if the real part of the expression
has all non-zero elements. The ELSE and ELSEIF parts are optional.
Zero or more ELSEIF parts can be used as well as nested IF’s.
The expression is usually of the form expr rop expr where
rop is ==, <, >, <=, >=, or ~=.

Example
if I == J
A(I,J) = 2;
elseif abs(I-J) == 1
A(I,J) = -1;
else
A(I,J) = 0;
end

See also relop, else, elseif, end, for, while, switch.

for

for Repeat statements a specific number of times.
The general form of a for statement is:

for variable = expr, statement, …, statement END

The columns of the expression are stored one at a time in
the variable and then the following statements, up to the
END, are executed. The expression is often of the form X:Y,
in which case its columns are simply scalars. Some examples
(assume N has already been assigned a value).

for I = 1:N,
for J = 1:N,
A(I,J) = 1/(I+J-1);
END
END

for S = 1.0: -0.1: 0.0, END steps S with increments of -0.1
for E = EYE(N), … END sets E to the unit N-vectors.

Long loops are more memory efficient when the colon expression appears
in the for statement since the index vector is never created.

The BREAK statement can be used to terminate the loop prematurely.

See also if, while, switch, break, end.

end

end Terminate scope of FOR, WHILE, SWITCH, TRY, and IF statements. Without END’s, FOR, WHILE, SWITCH, TRY, and IF wait for further input. Each end is paired with the closest previous unpaired FOR, WHILE, SWITCH, TRY or IF and serves to terminate its scope.

end can also serve as the last index in an indexing expression. In that context, end = SIZE(X,k) when used as part of the k-th index. Examples of this use are, X(3:end) and X(1,1:2:end-1). When using END to grow an array, as in X(end+1) = 5, make sure X exists first.

end(A,K,N) is called for indexing expressions involving the object A when end is part of the K-th index out of N indices. For example, the expression A(end-1,:) calls A’s end method with end(A,1,2).

See also for, while, switch, try, if.
Overloaded methods
help serial/end.m

else

else Used with IF.
else is used with IF. The statements after the else are executed
if all the preceding IF and ELSEIF expressions are false.

The general form of the IF statement is
IF expression
statements
ELSEIF expression
statements
ELSE
statements
END

See also if, elseif, end.

continue

continue Pass control to the next iteration of FOR or WHILE loop.
continue passes control to the next iteration of FOR or WHILE loop
in which it appears, skipping any remaining statements in the body
of the FOR or WHILE loop.

In nested loops, continue passes control to the next iteration of
FOR or WHILE loop enclosing it.

See also break, return.

case

case SWITCH statement case.
case is part of the SWITCH statement syntax, whose general form is:

SWITCH switch_expr
case case_expr,
statement, …, statement
case {case_expr1, case_expr2, case_expr3,…}
statement, …, statement

OTHERWISE,
statement, …, statement
END

See SWITCH for more details.

break

break Terminate execution of WHILE or FOR loop.
break terminates the execution of FOR and WHILE loops.
In nested loops, break exits from the innermost loop only.

If you use break outside of a FOR or WHILE loop in a MATLAB
script or function, it terminates the script or function at
that point. If break is executed in an IF, SWITCH-CASE, or
TRY-CATCH statement, it terminates the statement at that point.

Examples of Expressions

You have already seen several examples of MATLAB expressions. Here are a few more examples, and the resulting values.

rho = (1+sqrt(5))/2
rho =
1.6180
a = abs(3+4i)
a =
5
z = sqrt(besselk(4/3,rho-i))
z =
0.3730+ 0.3214i
huge = exp(log(realmax))
huge =
1.7977e+308
toobig = pi*huge
toobig =
Inf

pack

pack Consolidate workspace memory.
pack performs memory garbage collection. Extended MATLAB sessions may cause memory to become fragmented, preventing
large variables from being stored. pack is a command that saves all variables on disk, clears the memory, and then
reloads the variables.

If you run out of memory often, here are some additional system
specific tips:
Windows: Increase virtual memory using the control panel.
Unix: Ask your system manager to increase your Swap Space.

You should cd to a directory where you have “write” permission to execute this command successfully. The following lines of code will help you accomplish the consolidation of workspace memory.

cwd = pwd;
cd(tempdir);
pack
cd(cwd)

See also memory.

open

OPEN Open files by extension.
open NAME where NAME must contain a string, does different things
depending on the type of the object named by that string:

Type Action
—- ——
variable open named array in Array Editor
.mat file open MAT file; store variables in a structure in the workspace
.fig file open figure in Handle Graphics
.m file open M-file in M-file Editor
.mdl file open model in SIMULINK
.p file open the matching M-file if there is one
.html file open HTML document in Help Browser

open works similar to LOAD in the way it searches for files.

If NAME exists on MATLAB path, open file returned by WHICH.

If NAME exists on file system, open file named NAME.

Examples:

open(‘handel’) error if handel.mdl, handel.m, and handel
are not on the path.

open(‘handel.mat’) error if handle.mat is not on path.

open(‘d:\temp\data.mat’) error if data.mat is not in d:\temp.

open is user-extensible. To open a file with the extension “.XXX”,
open calls the helper function OPENXXX, that is, a function
named ‘OPEN’, with the file extension appended.

For example,
open(‘foo.m’) calls openm(‘foo.m’)
open foo.m calls openm(‘foo.m’)
open myfigure.fig calls openfig(‘myfigure.fig’)

You can create your own OPENXXX functions to change the way standard
file types are handled, or to set up handlers for new file types.
open will call whatever OPENXXX function it finds on the path.

Special cases:
for workspace variables, open calls OPENVAR
for image files, open calls OPENIM

If there is no matching helper function found, open calls OPENOTHER.

See also saveas, which, load, uiopen, uiload, path.

Overloaded methods
help scribehandle/open.m
help serial/open.m

more

more   Control paged output in command window.
more OFF disables paging of the output in the MATLAB command window.
more ON enables paging of the output in the MATLAB command window.
more(N) specifies the size of the page to be N lines.

When more is enabled and output is being paged, advance to the next
line of output by hitting the RETURN key;  get the next page of
output by hitting the spacebar. Press the “q” key to exit out
of displaying the current item.

format

format Set output format.
All computations in MATLAB are done in double precision.
format may be used to switch between different output display formats as follows:
format Default. Same as SHORT.
format SHORT Scaled fixed point format with 5 digits.
format LONG Scaled fixed point format with 15 digits.
format SHORT E Floating point format with 5 digits.
format LONG E Floating point format with 15 digits.
format SHORT G Best of fixed or floating point format with 5 digits.
format LONG G Best of fixed or floating point format with 15 digits.
format HEX Hexadecimal format.
format + The symbols +, – and blank are printed
for positive, negative and zero elements.
Imaginary parts are ignored.
format BANK Fixed format for dollars and cents.
format RAT Approximation by ratio of small integers.

Spacing:
format COMPACT Suppress extra line-feeds.
format LOOSE Puts the extra line-feeds back in.

edit

edit Edit M-file.
edit FUN opens the file FUN.M in a text editor.  FUN must be the
name of an m-file or a MATLABPATH relative partial pathname (see
PARTIALPATH).

edit FILE.EXT opens the specified text file.

edit FUN1 IN FUN2 opens function FUN1 in the context of m-file
FUN2.

edit FUN(A,B,C) opens file FUN.M that matches the
given input arguments.  For example, edit feval(g), when
g=inline(‘sin(x)’), opens inline/feval.m.

EDIT, by itself, opens up a new editor window.
Overloaded methods
help axischild/edit.m

echo

echo Echo commands in M-files.
echo ON turns on echoing of commands inside Script-files.
echo OFF turns off echoing.
echo file ON where ‘file’ is a function name causes the
named Function-file to be echoed when it is used.
echo file OFF turns it off.
echo file toggles it.
echo ON ALL turns on the echoing of commands inside any
Function-files that are currently in memory (i.e., the
functions returned by INMEM).
echo OFF ALL turns them all off.

See also function, script.

dir

dir List directory.
dir directory_name lists the files in a directory. Pathnames and
wildcards may be used.  For example, dir *.m lists all the M-files
in the current directory.

D = dir(‘directory_name’) returns the results in an M-by-1
structure with the fields:
name  — filename
date  — modification date
bytes — number of bytes allocated to the file
isdir — 1 if name is a directory and 0 if not

See also what, cd, type, delete.

diary

DIARY Save text of MATLAB session.
DIARY filename causes a copy of all subsequent command window input and most of the resulting command window output to be appended to the named file. If no file is specified, the file ‘diary’ is used.

DIARY OFF suspends it.
DIARY ON turns it back on.
DIARY, by itself, toggles the diary state.

Use the functional form of DIARY, such as DIARY(‘file’),
when the file name is stored in a string.

demo

demo Run demonstrations.

Type “demo” at the command line to browse available demos.

With the optional action argument demo
(‘matlab’|’toolbox’|’simulink’|’blockset’|’stateflow’),
demo opens the demo screen to the specified subtopic.

With the optional categoryArg argument,
demo opens to the specified toolbox or category, e.g.
demo toolbox signal
demo matlab language

delete

delete Delete file or graphics object.
delete file_name deletes the named file from disk. Wildcards
may be used. For example, delete *.p deletes all P-files from the
current directory.

Use the functional form of DELETE, such as delete(‘file’) when the
file name is stored in a string.

delete(H) deletes the graphics object with handle H. If the object
is a window, the window is closed and deleted without confirmation.
Overloaded methods
help char/delete.m
help scribehgobj/delete.m
help scribehandle/delete.m
help hgbin/delete.m
help editrect/delete.m
help arrowline/delete.m
help serial/delete.m
help activex/delete.m
help rptsp/delete.m
help rptgui/delete.m
help rptcp/delete.m

computer

computer Computer type.
computer returns a string containing the name of the computer
on which MATLAB is executing. Possibilities are:

ISPC ISUNIX
PCWIN – MS-Windows 1 0
SOL2 – Sun Sparc (Solaris 2) 0 1
HPUX – HP PA-RISC (HP-UX 11.00) 0 1
HP700 – HP PA-RISC (HP-UX 10.20) 0 1
ALPHA – Compaq Alpha (OSF1) 0 1
IBM_RS – IBM RS/6000 (AIX) 0 1
SGI – Silicon Graphics (IRIX/IRIX64) 0 1
GLNX86 – Linux on PC compatible (Linux) 0 1

[C,MAXSIZE] = computer returns also integer MAXSIZE which
contains the maximum number of elements allowed in a matrix
on this version of MATLAB.
Continue reading “computer”

clear

clear Clear variables and functions from memory.
clear removes all variables from the workspace.
clear VARIABLES does the same thing.
clear GLOBAL removes all global variables.
clear FUNCTIONS removes all compiled M- and MEX-functions.

clear ALL removes all variables, globals, functions and MEX links.
clear ALL at the command prompt also removes the Java packages
import list. Continue reading “clear”

beep

beep Produce beep sound.
beep produces a beep sound.
beep ON turns the beep on.
beep OFF turns the beep off.
S = beep returns the beep status: ‘on’ or ‘off’.

addpath

addpath Add directory to search path.
addpath DIRNAME prepends the specified directory to the current
matlabpath. Surround the DIRNAME in quotes if the name contains a
space.

addpath DIR1 DIR2 DIR3 … prepends all the specified directories to
the path.

addpath … -END appends the specified directories.
addpath … -BEGIN prepends the specified directories.
addpath … -FROZEN disables directory change detection for directories
being added and thereby conserves Windows change
notification resources (Windows only).

Use the functional form of ADDPATH, such as addpath(‘dir1′,’dir2’,…),
when the directory specification is stored in a string.

Examples

addpath c:\matlab\work
addpath /home/user/matlab

See also rmpath, path, genpath, rehash.

MATLAB Desktop

When you start MATLAB, the MATLAB desktop appears, containing tools (graphical user interfaces) for managing files, variables, and applications associated with MATLAB.
The first time MATLAB starts, the desktop appears as shown in the following illustration, although your Launch Pad may contain different entries.

MATLAB DesktopYou can change the way your desktop looks by opening, closing, moving, and resizing the tools in it. You can also move tools outside of the desktop or return them back inside the desktop (docking). All the desktop tools provide common features such as context menus and keyboard shortcuts.
You can specify certain characteristics for the desktop tools by selecting Preferences from the File menu. For example, you can specify the font characteristics for Command Window text. For more information, click the Help button in the Preferences dialog box.