I



I.1 What is MATLAB?

I.1.1 Introduction

MATLAB stands for matrix (MAT) laboratory (LAB). It is a high performance language for scientific computing. MATLAB integrates numerical computation, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notations. With its interactive capabilities, you can solve many

numerical problems in a fraction of the time it would take to write a program in a language such as BASIC, FORTRAN, or C. With MATLAB, you can develop new applications without writing a single line of low-level computer code.

I.1.2 Starting and Ending a MATLAB Session

To start MATLAB on a PC or Macintosh (Mac), double-click on the MATLAB icon. To start MATLAB on a UNIX system, type “matlab” at the operating system prompt.

To quit MATLAB at any time, type “quit” at the MATLAB prompt. On both the PC and the Mac, you have the option to exit or quit from the file menu.

Remember

MATLAB reacts to your command only after the return or enter key is pressed.

I.1.3 MATLAB Windows

The Command Window

When you start MATLAB, the Command Window opens by default. The name “MATLAB Command Window” appears at the top section of the MATLAB Window. In this window, you communicate with the MATLAB interpreter. The MATLAB interpreter displays a prompt ( >> ) indicating that it is ready to accept commands from you.

For example, to enter a 1 ( 5 vector, you can enter the following command:

>>x = [1 2 3 4 5]

MATLAB responds:

>> x =

1 2 3 4 5

>>

To find the dimension of x, you can use the size command. . .

>> size(x)

MATLAB responds:

ans =

1 5

>>

indicating that x is a vector with 1 row and 5 columns.

Remember

MATLAB is case sensitive. “X” and “x” are distinctly different variables.

The icons at the top of the Command Window can be used for managing files, workspace, editing, and getting online help.

Figure Windows

A figure window is used by MATLAB to display graphs. The number of figure windows allowed in MATLAB depends on the amount of available memory in your system. Whenever you ask MATLAB to plot a function for you, it automatically opens a figure window and plots the desired function in that window. If you are interested in opening several figure windows, you can do so by typing:

>>figure (x)

where x is the number assigned to the figure window. This number will appear in the title bar of the figure window.

For example, if you are interested in seeing two plots in two different windows, you can type

>> figure (1)

which opens Figure No. 1 and

>>figure (2)

which opens Figure No. 2. The size and location of these windows can be easily

modified. You can move a window by clicking on the title bar and dragging it to a desired location. You resize a figure window by moving the mouse pointer to the edge/corner of the window until the pointer becomes a “resize handle.” Then you drag in the desired direction and the window size adjusts accordingly.

We will discuss more windows in Chapters 4, 5, and 6.

I.1.4 What can MATLAB do for You ?

MATLAB provides the user with a set of high-level numerical and graphical routines.

The routines are written in C code and are optimized for high performance. Typical use of these routines include:

Mathematics and computations

Algorithm development

Modeling, simulation, and prototyping

Data analysis

Simulation

Visualization

Scientific and engineering graphics

Application development

The basic data element in MATLAB is an array that does not require dimensioning.

This feature of MATLAB allows you to solve problems that can be formulated with a matrix or a vector in a much faster time than it would take to write a program in C, FORTRAN, or BASIC. For example, you can solve for the roots of the following polynomial:

[pic]

in two simple steps. Step 1 is to tell MATLAB which polynomial you want to solve. This is done by typing the following statement at the prompt in the command window:

>> p = [1 2 5 12 5 -15]

With this expression, you have given MATLAB sufficient information about the polynomial that you want to solve. In step 2, you tell MATLAB to solve for the roots of the polynomial. This is done by issuing the following command:

>>r = root(p).

With this command, MATLAB solves for the roots, displays them, and stores the roots in a vector r. Here is the complete program used in MATLAB to solve for the roots of f(x).

» p = [1 2 5 12 5 -12]

p =

1 2 5 12 5 -12

» r = roots(p)

r =

0.2704+ 2.3713i

0.2704- 2.3713i

-1.6243+ 0.5818i

-1.6243- 0.5818i

0.7077

»

Plotting in MATLAB

MATLAB provides you with powerful 2-D and 3-D plot routines. For example, you can plot the function defined below in two easy steps.

[pic]

In step 1 you define three parameters: the starting point of the graph, the distance between two consecutive points on the graph, and the end of the graph. An example is given in the following expression:

>>x = 0:0.01:6

x = 0:0.01:6

Starting point of the graph End point of the graph

Distance between two consecutive points on the graph

In step 2, you plot the function f(x) by typing:

>>plot( (sin(x) + sin(3 * x))

After this command, MATLAB opens another window (Figure No.1 Window) and plots the function as shown below.

[pic]

There are many commands that allow you to control different aspects of a plot. We will discuss these in Chapters I.5 and I.6.

I.1.5 MATLAB Functions

MATLAB provides you with many functions that can be used to solve different problems.

These functions fall in different categories. In the following table, we list some of the most widely used operators and functions used in MATLAB.

In addition to the standard MATLAB functions, you can easily develop a customized function using an M-file. In Chapter 3 we will show you how you can build your own

M-files to perform specific tasks.

General Purpose Commands

Managing Commands and Functions

Command Description

demo Run demos

help Online documentation

info Information about MATLAB and MATHWorks

lookfor Keyword search through the help entries

path Control MATLAB’s search path

type List M-file

what Directory listing of M, MAT, and MEX-files

which Locate functions and files

Managing Variables and the Workspace

Command Description

clear Clear variables and functions from memory

disp Display matrix or text

length Length of vector

load Retrieve variables from disk

pack Consolidate workspace memory

save Save workspace variable to disk

size Size of matrix

who List current variables

whos List current variables, long form

Working with Files and the Operating System

Command Description

cd Change current working directory

delete Delete file

diary Save text of MATLAB session

dir Directory listing

getenv Get environment values

unix Execute operating systems command; return result.

! Execute operating system command.

Controlling the Command Window

Command Description

clc Clear Command Window

echo Echo commands inside script files

format Set output format

home Send cursor home

more Control paged output on Command Window

Starting and Quitting MATLAB

Command Description

matlabrc Master startup M-file

quit Terminate MATLAB

Startup M-file executed when MATLAB is invoked

Language Construct and Debugging

MATLAB as a Programming Language

Command Description

eval Execute string with MATLAB expression

feval Execute function specified by string

function Add new function

global Define global variable

nargchk Validate number of input arguments

Control Flow

Command Description

break Terminate execution of loop

else Used with if

elseif Used with if

end Terminate the scope of for, while, and if statement

error Display message and abort function

for Repeat statement for a specific number of times

if Conditionally execute statement

return Return to invoking function

while Repeat statements until a condition is met

Interactive Input

Command Description

input Prompt for user input

keyboard Invoke keyboard as if it were a script-file

menu Generate menu of choice for user input

pause Wait for user response

Debugging

Command Description

dbclear Remove breakpoint

dbcont Resume execution

dbdown Change local workspace context

dbquit Quit debugging mode

dbstack List who called whom

dbstatus List all breakpoints

dbstep Execute one or more line

dbstop Set breakpoint

dbtype List M-file with line numbers

dbup Change local workspace context

Elementary Matrices and Matrix Manipulation

Elementary Matrics

Command Description

eye Identity matrix

linspace Linearly spaced vector

logspace Logarithmically spaced vectors

meshgrid X and Y arrays for 3-D plots

ones Ones matrix

rand Uniformly distributed random numbers

randn Normally distributed random numbers

zeros Zeros matrix

: Regularly spaced vector

Matrix Manipulation

Command Description

diag Create or extract diagonals

fliprl Flip matrix in the left/right direction

flipud Flip matrix in the up/down direction

reshape Change size

rot90 Rotate matrix 90 degrees

tril Extract lower triangular part

triu Extract upper triangular part

Specialized Matrices

Command Description

compan Companion matrix

hadamard Hadamard matrix

hankel Hankel matrix

hilb Hilbert transform

invhilb Inverse Hilbert matrix

magic Magic square

pascal Pascal matrix

rosser Classic symmetric eigenvalue test problem

toeplitz Toeplitz matrix

vander Vandermonde matrix

wilkinson Wilkinson’e eigenvalue test matrix

Elementary Matrix Functions

Command Description

cond Matrix condition number

det Determinant

norm Matrix or vector norm

null Null space

orth Orthogonalization

rcond LINPAK reciprocal condition estimator

rank Number of linearly independent rows or columns

rref Reduced row echlon form

trace Sum of diagonal elements

Linear Equations

Command Description

chol Cholesky factorization

inv Matrix inverse

iscov Least square in the presence of known covariance

lu Factors from Gaussian elimination

nnls Non-negative least-squares

pinv Pseudoinverse

qr Orthogonal-triangular decomposition

\ and / Linear equation solution

Matrix Eigenvalues and Singular Values

Command Description

balance Diagonal scaling to improve eigenvalue accuracy

cdf2rdf Complex diagonal form to real block diagonal form

eig Eigenvalues and eigen vectors

hess Hessenberg form

poly Characteristic polynomial

qz Generalized eigenvalues

rsf2csf Real block diagonal form to complex diagonal form

schur Schur decomposition

svd Singular value decomposition

Advanced Matrix Functions

Command Description

expm Matrix exponential

exmp1 M-file implementation of exmp

exmp2 Matrix exponential via Taylor series

exmp3 Matrix exponential via eigenvalues and eigenvectors

funm Evaluate general matrix function

logm Matrix logarithm

sqrtm Matrix square root

Data Interpolation

Command Description

griddata Data gridding

interp1 1-D interpolation

interp2 2-D interpolation

interpft 1-D interpolation using FFT method

Data Analysis

Command Description

cumprod Cumulative product of elements

cumsum Cumulative sum of elements

max Largest component

mean Average or mean value

median Median value

min Smallest component

prod Product of elements

sort Sort of ascending order

std Standard deviation

sum Sum of elements

trapz Numerical integration using trapezoidal method

Special Variables and Constants

Command Description

ans Most recent answer

computer Computer type

eps Floating point relative accuracy

flops Count the floating point operations

i, j Imaginary units

inf Infinity

NaN Not-a-Number

nargin Number of function input arguments

nargout Number of function output arguments

pi 3.1415926535897…

realmax Largest floating point number

realmin Smallest floating point number

Time and Date

Command Description

clock Wall clock

cputime Elapsed CPU time

date Calendar

etime Elapsed time function

tic, toc Stopwatch timer functions

Operators and Special Characters

Command Description

+ Plus

( Minus

* Matrix multiplication

.* Array multiplication

^ Matrix power

.^ Array power

kron Kronecker tensor product

\ Left division

/ Right division

./ Array division

: Colon

( ) Parentheses

[ ] Brackets

. Decimal point

. . Parent directory

. . . Continuation

, Comma

; Semicolon

% Comment

! Exclamation point

‘ Transpose and quote

.’ Nonconjugated transpose

= Assignment

= = Equality

< > Relational operator

& Logical AND

| Logical OR

~ Logical NOT

xor Logical exclusive OR

Elementary Mathematical Functions

Command Description

abs Absolute value

acos Inverse cosine

acosh Inverse hyperbolic cosine

angle Phase angle

asin Inverse sine

asinh Inverse hyperbolic sine

atan Inverse tangent

atan2 Four quadrant inverse tangent

atanh Inverse hyperbolic tangent

ceil Round towards plus infinity

conj Complex conjugate

cos Cosine

cosh Hyperbolic cosine

exp Exponential

fix Round towards zero

floor Round towards minus infinity

imag Complex imaginary part

log Natural logarithm

log10 Base 10 (common ) logarithm

real Complex real part

rem Remainder after division

round Round towards nearest integer

sign Signum function

sin Sine

sinh Hyperbolic sine

sqrt Square root

tan Tangent

tanh Hyperbolic tangent

Finite Difference

Command Description

del2 Five-point discrete Laplacian

diff Difference function and approximate derivative

gradient Approximate gradient

Correlation

Command Description

corrcoef Correlation coefficients

cov Covariance matrix

Filtering and Convolution

Command Description

conv convolution and polynomial multiplication

conv2 Two-dimensional convolution

deconv Deconvolution and polynomial division

filter One-dimensional digital filter

filter2 Two-dimensional digital filter

Fourier Transform

Command Description

cplxpair Sort numbers into complex conjugate pairs

fft Discrete Fourier transform

fft2 Two-dimensional discrete Fourier transform

fftshift Move zeroth lag to center of spectrum

ifft Inverse discrete Fourier transform

ifft2 Inverse two-dimensional discrete Fourier transform

nextpow2 Next higher power of 2

unwrap Remove phase angle jumps across 360o boundaries

Polynomial and Interpolation Functions

Command Description

poly Construct polynomial with specified roots

polyder Differentiate polynomial

polyfit Fit polynomial to data

polyval Evaluate polynomial

polyvalm Evaluate polynomial with matrix argument

residue Partial-fraction expansion

roots Find polynomial roots

Function Functions

Command Description

fmin Minimize function of one variable

fmins Minimize function of several variables

fplot Plot function

fzero Find zero of function of one variable

ode23 Solve differential equations, low order method

ode45 Solve differential equations, high order method

quad Numerically evaluate integral, low order method

quad8 Numerically evaluate integral, high order method

Sparse Matrix Functions

Command Description

spdiags Sparse matrix formed from diagonals

speye Sparse identity matrix

sprands Sparse random matrix

sprandsym Sparse symmetric random matrix

Full to Sparse Conversion

Command Description

find Find indices of nonzero entries

full Convert sparse matrix to full matrix

sparse Create sparse matrix from nonzero and indices

spconvert Convert from sparse matrix external format

Working with Nonzero Entries of Sparse Matrices

Command Description

issparse True if matrix is sparse

nnz Number of nonzero entries

nonzeros Nonzero entries

nzmax Amount of storage allocated for nonzero entries

spalloc Allocate memory for nonzero entries

spones Replace nonzero entries with ones

Visualizing Sparse Matrices

Command Description

gplot Plot graph

spy Visualize sparsity structure

Reordering Algorithms

Command Description

colmmd Column minimum degree

colperm Order columns based on nozero count

dmperm Dulmage-Mendelsohn decomposition

randpers Random permutation vector

symmmd Symmetric minimum degree

symrcm Reverse Cuthill-Mckee ordering

Norm, Condition Number, and Rank

Command Description

condest Estimated 1-norm condition

normest Estimate 2-norm

sprank Structural rank

Miscellaneous

Command Description

spaugment Form least squares augmented system

spparms Set parameters for sparse matrix routines

symbfact Symbolic factorization analysis

Two Dimensional Graphics

Elementary X-Y Graphics

Command Description

fill Draw filled 2-D polygons

loglog Log-log scale plot

plot Linear plot

semilogx Semi-log scale plot

semilogy Semi-log scale plot

Specialized X-Y Graph

Command Description

bar Bar graph

compass Compass plot

errorbar Error bar plot

feather Feather plot

fplot Plot function

hist Histogram plot

polar Polar coordinate plot

rose Angle histogram plot

stairs Stairstep plot

Graph Annotation

Command Description

grid Grid lines

gtest Mouse placement of text

text Text annotation

title Graph title

xlabel X-axis label

yaxis Y-axis label

3-Dimensional Graphs

Command Description

fill3 Draw filled 3-D polygons in 3-D space

plot3 Plot lines and points in 3-D space

clabel Contour plot elevation labels

contour Contour plots

contour3 3-D contour plots

contourc Contour plot computation

image Display image

pcolor Pseudocolor plot

quiver Quiver plot

Surface and Mesh Plots

Command Description

mesh 3-D mesh surface

meshc Combination mesh/contour plot

meshz 3-D Mesh with zero plane

slice Volumetric visualization plot

surf 3-D shaded surface

surfc Combination surface/contour plot

surf1 3-D shaded surface with lighting

waterfall Waterfall plot

Graph Appearance

Command Description

axis Axis scaling and appearance

caxis Pseudocolor axis scaling

colormap Color lookup table

hidden Mesh hidden line removal mode

shading Color shading mode

view 3-D graph viewpoint specification

viewmtx View transformation matrices

zlabel Z-label for 3-D graph

3-D Objects

Command Description

cylinder Generate cylinder

sphere Generate sphere

General Purpose Graphics Functions

Command Description

clf Clear current figure

close Close figure

figure Create figure

gcf Get handle to current figure

Axis Creation and Control

Command Description

spaugment

axes Create axes in arbitrary position

axis Control axis scaling and appearance

cazis Control pseudocolor axis scaling

cla clear current axes

gca Get handle to current axes

hold Hold current graph

subplot Create axes in tiled position

Handling Graphics Objects

Command Description

line Create line

patch Create patch

surface Create surface

uicontrol Create user interface control

uimenu Create user interface menu

Handling Graphics Operations

Command Description

delete Delete object

drawnow Flash pending graphics event

get Get object properties

reset Reset object properties

set Set object properties

Hardcopy and Storage

Command Description

orient Set paper orientation

print Print graph or save graph to file

printopt Configure local printer default

Movies and Animation

Command Description

getframe Get movie frame

movie Play recorded movie frame

moviein Initialize movie frame memory

Miscellaneous

Command Description

ginput Graphical input from mouse

ishold Return hold state

Color Maps

Command Description

bone Gray-scale with a tingle of blue color map

cool Shaded of cyan and magenta color map

copper Linear copper-tone color map

flag Alternating red, white, blue, and black color

gray Linear gray-scale color map

hsv Hue-saturation-value color map

hot Black-red-yellow-white color map

pink Pastel shaded of pink color map

Color Map Related Functions

Command Description

brighten Brighten or darken color map

hsv2rgb Hue-saturation-value to red-green-blue conversion

rgb2hsv Red-green-blue to hue-saturation-value conversion

rgbplot Plot color map

spinmap Spin color map

Lighting Models

Command Description

diffuse Diffuse reflectance

specular Specular reflectance

surf1 3-D shaded surface with lighting

surfnorm Surface normals

Sound Processing Functions

Command Description

saxis Sound axis scaling

sound Convert vector into sound

Character String Functions

Command Description

abs Convert string to numerical values

eval Execute string with MATLAB expression

isstr True for string

setstr Convert numeric values to string

str2mat Form text matrix from individual string

string About character string in MATLAB

String Comparison

Command Description

lower Convert string to lowercase

strcmp Compare string

upper Convert string to uppercase

String-to-Number Conversion

Command Description

int2str Convert integer to string

num2str Convert number to string

sprintf Convert number to spring under format control

sscanf Convert string to number under format control

str2num Convert string to number

Hexadecimal-to-Number Conversion

Command Description

dec2hex Convert decimal integers to hex string

hex2dec Convert hex string to decimal integer

hex2num Convert hex string to IEEE floating point number

Low-level File I/O Functions

Command Description

fclose Close file

fopen Open file

Unformatted I/O

Command Description

fread Read binary data from file

fwrite Write binary data to file

Formatted I/O

Command Description

fgetl Read line from file, discard new line character

fgets Read line from file, keep new line character

fprintf Write formatted data to file

fscanf Read formatted data from file

File Positioning

Command Description

ferror Inquire file I/O error status

frewind Rewind file

fseek Set file position indicator

ftell Get file position indicator

String Conversion

Command Description

sprintf Write formatted data to string

sscanf Read string under format control

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download