# Introduction to Matlab Course Notes Main Page

### Description:

This web site contains course notes for a basic introduction to Matlab

Initially this page is really just a list of the topics I want to / have talk(ed) about, without any real coverage here of any particular topic.

### Accreditation:

1. This version of these course notes was modified Summer 2011 by John Bell, for CS 109 at the University of Illinois Chicago.
2. The textbook being used for this coverage is "Introduction to Matlab", Second Edition, by Delores M. Etter.
3. A previous version of these notes was based on "Essential MATLAB for Engineers and Scientists", Fourth Edition ,by Hahn & Valentine. Some content on this site may be from that source.

### Course Notes, by Topic, in the order covered ( more or less ):

1. Introduction
• Basics of getting, installing, and running Matlab.
• How to get and install a Virtual Private Network
• Survey of the Matlab desktop and capabilities.
• How to save Matlab commands in a script file and run that file.
2. Getting Started with Matlab
• Valuable commands and pre-defined variables:
• help, helpwin - Provides help on specified topics
• lookfor - ( not in book ) Find functions based on keywords in description
• clear - clears variables. You can also clear specific variables.
• clc - clears command window
• who, whos - Lists variables, with and without size information
• which - Indicates whether an identifier is a variable, built-in Matlab function, user-defined function, or other
• what - Lists files in the current directory
• ans - The last value calculated
• i, j - square root of -1, UNLESS they have been re-defined
• pi - 3.14159 . . .
• Inf - Infinity
• NaN - Not a Number, for example zero divided by zero
• eps - Epsilon, the smallest number the computer can add to 1 and not get 1 as a result.
• Special Characters
• [ ] - Used for creating matrices
• ( ) - Used for accessing matrices, forcing precedence, and calling functions
• NOTE THAT ARRAY INDICES BEGIN AT 1 IN MATLAB,NOT 0
• ... ( ellipses ) - Continuation of a statement to a following line
• ' ( apostrophe ) - Takes the transpose of a matrix, or quote a string
• , ( comma ) - Separates values in a matrix or arguments in a function
• ; ( semicolon ) - Suppresses output. Also used to separate rows in a matrix
• : ( colon ) - Used to specify a range, with or without a provided increment
• Can be used to select a subset of an array or matrix, e.g. nums( 4:8 ), arr( 3:4, 2:5 )
• When used by itself as an array index, acts as a wild card representing all valid values. For example, array( 2:4, : ) would access every column for rows 2, 3, and 4, effectively extracting those rows.
• Can be used to extract the color components of a RGB Image:
• originalImage = imread( 'diver.jpg' );
• red = originalImage( :, :, 1 ); % Red is plane 1, Green plane 2, and Blue plane 3.
• As a single array index generates a single column from the matrix. m = magic( 5 ); linear = m( : );
• % ( percent ) - Comment, to the end of the line
• Defining Matrices
• Colon operator - Fill in using a given increment ( 1 by default)
• linspace, logspace - Fill in linearly or logarithmically using endpoints and number of points
• [ list ] - specify values. Comma to separate numbers, semicolon to separate rows. Can also concatenate matrices.
• Functions ( see below ) - eye, magic, peaks, rand, diag, etc.
• Mathematical Operators
• May be different for scalars versus arrays versus combinations of both
• +, -, *, /, ^, \
• Left division is only relevant to matrix operations:
• A x = b
• x = A \ b
• Elementwise - .*, ./, .^ - Acts on matrices element by element, as opposed to normal matrix operations.
• Modulus is the function "mod", not an operator.
• Formatting Output
• disp
• disp [ 'X = ', num2str( x ) ]; % Print an array of two strings as a sentence.
• format - long, short, bank, e, +
• fprintf( 'format string with % codes', variables )
• %f - Fixed decimal number
• %e - Exponential notation
• %g - E or F, whichever fits best
• %d - decimal integer
• width.precision - E.g. %5.2f prints a floating point number in a space of width 5, with two digits right of the decimal point.
• \n - newline
• \t - tab
• Note: When printing arrays with Matlab:
• Format specifiers are used repeatedly until all data values are printed
• Array data is accessed column-wise, not row-wise!
• fprintf example printing arrays
• Getting input from the user
• variable = input( 'Prompt string' );
• variable = input( 'Prompt string', 's' ); - To specify a text ( string ) input instead of numbers.
• Saving work
• save
• save filename - saves entire workspace ( i.e. all variables )
• save filename variables - save specific variables
• -ascii - flag to save in human-readable form
• If no extension is given, then ".mat" is the default. This is appropriate for binary files, but you probably want to specify .txt or something like it for ascii text files.
• load filename - puts all variables back, or single variable with name of file.
• If the data was saved from Matlab in binary format, particularly if there were multiple variables saved, then "load filename" will restore all the saved data into variables with the same names as originally saved.
• If the file contains only a single variable in plain text format ( as might be generated by some other program ), then "load filename.txt" will create a new variable with the same name as the data file.
• variable = load( filename ) - stores into named variable. Note: parenthesis are required.
• Right-click on data file in Matlab file directory listing, and select "import"
• Creating and running scripts
• Copy ( drag ) or write Matlab commands into any text file. ( Matlab has a built-in editor. )
• Save with a ".m" extension - Automatic when using Matlab's editor.
• Run the file by typing the name, or "run name", or run( 'name' ), or right-clicking, or from the Matlab editor
3. Matlab Functions
• Built-in functions
• See list in book, or below, or follow the link to the full online list of Matlab functions
• Check help ( or helpwin ) on elmat, elfun, specfun, randfun
• Use "lookfor" to search for functions
• Click on the "Fx" function icon on the left edge of the Matlab command window, if available.
• Matlab trig functions sin, cos, tan assume angles in radians, just like C++
• sind, cosd, tand assume angles in degrees
• Some functions return multiple results
• A = [ 1, 2, 3; 4, 5, 6 ]
• size( A ) % returns [ 2, 3 ]
• [ nrows, ncols ] = size( A ); % stores results in nrows and ncols
• Some functions' results vary with dimension of input:
• max( 1-D vector ) returns a single maximum value.
• [ value, position ] = max( 1-D vector ) returns the maximum and its position
• max( 2-D matrix ) returns a row vector containing the max of each column
• max( max( 2-D matrix ) ) returns the maximum value in the matrix.
• ( As does max( 2-D_matrix( : ) ) )
• A few functions worth noting:
• atan2( y, x ) - Arctangent of y / x, between -pi and pi.
• ceil - smallest integer that exceeds its argument. ceil( 3.1 ) is 4, ceil( -3.9 ) is -3.
• clock - time and date in a six-element vector.
• cumsum - cumulative sum, i.e. cumsum( [ 1 2 3 4 ] ) yields [ 1 3 6 10 ].
• date
• exp - exponential, base e.
• fix - nearest integer towards zero. fix( 3.9 ) is 3, fix( -3.9 ) is -3.
• floor - largest integer not exceeding its argument - floor( 3.9 ) is 3, floor( -3.1 ) is -4.
• length - number of elements in a vector, or number of columns in a matrix.
• log - natural logarithm
• log10 - base 10 logarithm.
• max - Maximum. When applied to a matrix, yields a vector with the maximums of each column.
• mean - Average. See max.
• min - Minimum. See max.
• mod( X, Y ) - returns X - n.*Y where n = floor(X./Y). Like mod in C, but works with all types of numbers.
• pow2 - Two raised to the power of the argument.
• prod - product of the elements of its argument. prod( [ 2 3 5 ] ) is 30.
• rand - generates pseudo-random numbers in the range of [ 0, 1 ).
• Initialize the random number generator ONCE with rand( 'state', sum( 100*clock))
• realmax - largest positive floating point number ( for this installation on this computer. )
• realmin - smallest positive floating point number ( same ).
• rem( x, y ) - remainder when x is divided by y.
• Strictly speaking, returns x - ( y * fix( x / y ) ), which defines actions for negative and non-integer operands.
• round - rounds off to nearest integer. round( 3.5 ) = 4, round( -3.5 ) = -4.
• size - Returns all dimensions of its argument, e.g. number of rows and number of columns for a 2-D matrix.
4. User Defined Functions
5. Plotting
• Sample script: plotExample.m
• Commands and Techniques Common to All Plot Types
• Generate data in Matlab or load in a data file generated externally
• Use the colon operator as needed to extract subsets of data, e.g. columns.
• Plotting from the Workspace
• Right-click on one or more data items and select a plot type from the pull-down menu
• When selecting multiple data items, the order of selection is important.
• The commands generated are displayed in the command window - Use help or doc to learn more about them, and copy them into scripts as necessary.
• Plotting using plotting commands
• Any of the plot commands can be issued in the command window or from a script.
• Porting plots to other documents, e.g. to include in a written report
• From plot window, select "File, Save As", and select a file type compatible with your other program, e.g. jpeg
• Annotating plots
• subplots
• subplot( m, n, p ) sets up to plot in position "p" of an "m" row by "n" column grid of plots.
• "p" increases row-wise, so 1 to n on the top row, n+1 to 2n on the second row, and so on.
• The position p may span multiple cells, e.g. subplot( 2, 3, 5:6 );
• For style purposes, indent plotting commands under a subplot command.
• colormaps
• Pre-defined - Gray, copper, pink, bone, hot, cool, jet, hsv, spring summer, autumn, winter, lines
• User-defined - Any matrix of 3 columns of RGB values, in the range 0 to 1.0 inclusive.
• Display with rgbplot
• Multiple plots on a common set of axes
• figure - Create a new figure, make a particular figure active, or bring up the current figure.
• e.g. figure( gcf );
• Line Specifications - line types, colors, markers, etc.
• 2-D Plots
• 3-D Plots
• Images
6. Control Structures
• Most of the basic concepts we learned in C/C++ apply in Matlab. Only some of the implementation details differ.
• Relational Operators - >,<,>=,<=,= =, ~ =
• Note that "not equals" uses a tilde, ~, in place of the ! in C++
• Applied to matrices produces matrices of zeros and ones
• These zeros and ones can then be used as indices to refer to positions within matrices.
• Example:
• m = magic( 5 ); % Five by five magic square, values 1 to 25
• big = ( m >= 20 ); % Ones indicate positions where m is >= 20
• m( big ) = 0; % Changes values of only those positoins to zero.
• m( 5 < m & m < 10 ) = 42.0; % Without intermediary array. Note single &, not double &&.
• twoTone = 255 * big; % Array of all 255 or zero, based on whether m >= 20 ( originally ).
• Logical Operators - &, |, ~ for AND, OR, NOT
• Single &, | does elementwise comparison, continuing for all elements.
• Double &&, || does short-circuiting, similar to C++, only works on scalars.
• if - elseif - else - end
• No curly braces, but the "end" command is required.
• elseif and else are optional.
• No parentheses required, but they don't hurt either.
• while loops
• Condition controlled loops, just as in C/C++
• No curly braces, but a closing "end" is required.
• No parentheses required, but they don't hurt either.
• demonstrated in epsilonExample.m
• Matlab does not have a do-while loop.
• for loops
• NOT a counter-controled loop as in C, though that behaviour can be mimiced.
• The for loop in Matlab is a list-controlled loop
• Syntax:

for index = list

statements

end

• index takes on one value from the list for each iteration.
• If the "list" is a 2-D matrix,then index is a column vector inside the loop.
• for loops and while loops support break and continue
• Matlab does not have the conditional operator, ?: . ( Also no ++, --, +=, etc. )
• find - Generates indices of non-zero elements.
• Example: find( x > 0 ) returns indices for which x is positive.
• Normally treats 2-D matrices as one long column
• [ rows, columns ] = find( ... ) returns separate row and column information.
• ( However results of relational operators can be used directly, as shown above. )
• Matlab has a switch construct, not covered in our current book.
• Syntax:
```                  switch switch_expression
case case_expression
statements
case case_expression
statements
:
otherwise
statements
end```
• Automatically breaks at the end of each case.
• Cases can be combined by using a list for the case expression
• No braces, but a closing "end" is required
• No colon after the case expression
• Parentheses not required around the switch expression, but they don't hurt either
• Matlab uses "otherwise" instead of "default"
• menus also not covered in our current book - combined with an infinite loop and switch in menuExample.m
7. Matrix Computations
• Matrix multiplication, inverse, determinant, solution of equations, Gaussian elimination, etc.
8. Using Matlab to Plot Data from ASCII Files ( Appendix from C++ book )
• Use load to load in the data, : to extract columns ( or other subsets ), and the plotting tools to plot.
9. Beyond the Scope of These Notes:

Notes below this point are left over from previous semesters, and correspond to the other book. Material covered above is being deleted here.

1. 4.1 - Common Matlab Functions. Note that many of the aggregating functions ( e.g. max, min, mean ) return a row vector of the operation applied on each column separately when applied to a matrix.
• ( See the Function Browser in Matlab help for a more complete list, or read the help documentation on a particular subject such as linear algebra. )
• abs
• acos
• acosh
• asin
• asinh
• atan
• atan2( y, x ) - Arctangent of y / x, between -pi and pi.
• atanh
• ceil - smallest integer that exceeds its argument. ceil( 3.1 ) is 4, ceil( -3.9 ) is -3.
• clock - time and date in a six-element vector.
• cos
• cosh
• cot
• csc
• cumsum - cumulative sum, i.e. cumsum( [ 1 2 3 4 ] ) yields [ 1 3 6 10 ].
• date
• exp - exponential, base e.
• fix - nearest integer towards zero. fix( 3.9 ) is 3, fix( -3.9 ) is -3.
• floor - largest integer not exceeding its argument - floor( 3.9 ) is 3, floor( -3.1 ) is -4.
• length - number of elements in a vector, or number of columns in a matrix.
• log - natural logarithm
• log10 - base 10 logarithm.
• max - Maximum. When applied to a matrix, yields a vector with the maximums of each column.
• mean - Average. See max.
• min - Minimum. See max.
• pow2 - Two raised to the power of the argument.
• prod - product of the elements of its argument. prod( [ 2 3 5 ] ) is 30.
• rand - generates pseudo-random numbers in the range of [ 0, 1 ).
• Initialize the random number generator ONCE with rand( 'state', sum( 100*clock))
• realmax - largest positive floating point number ( for this installation on this computer. )
• realmin - smallest positive floating point number ( same ).
• rem( x, y ) - remainder when x is divided by y.
• Strictly speaking, returns x - ( y * fix( x / y ) ), which defines actions for negative and non-integer operands.
• round - rounds off to nearest integer. round( 3.5 ) = 4, round( -3.5 ) = -4.
• size - Returns all dimensions of its argument, e.g. number of rows and number of columns for a 2-D matrix.
2. Not covered in this course:
• Matlab has low-level file I/O operations fopen, fwrite, fread, feof, fseek,and fclose.
3. Chapter 6 - Any details regarding matrices not already covered. ( Sections up to 6.1.13 only. )
• Trying to READ an element of an array that is out of bounds will generate an error, but WRITING to one will simply expand the array to accommodate the new data ( so long as the indices are positive. ) For example:
```        data = ones( 2, 2 ); % Creates a 2 x 2 array of value 1
whos
x = data( 3, 3 ); % Error - element doesn't exist.
whos
data( 3, 3 ) = 42	% Sets the value and expands the array, filling with zeros.
whos```
• Matrices may be "tiled" using "repmat( array, nRows, nCols )"
• A matrix referenced with a single subscript is treated as if it were "unwound" column by column into a vector form. E.g. "data( 4 ) = 7" continuing from the above example.
• Rows or columns of a matrix can be deleted by replacing them with the null vector:
• data( 2, : ) = [ ];
• data( :, 3 ) = [ ];
• Individual elements can only be deleted if the matrix is unwound first: data( 5 ) = [ ];
• Elementary Matrix operations:
• See "help elmat" for a full list
• zeros
• ones
• eye
• linspace
• logspace
• repmat
• Basic array information
• size - rows & columns for a matrix
• length - columns only for a matrix
• ndims - numberof dimensions.
• numel - number of elements
• all - generates 1 if all elements are non-zero, 0 otherwise.
• any - genrates 1 if any element is non-zero, 0 otherwise.
• Matrix Manipulation
• cat - Concatenate
• reshape
• diag - Extracts the diagonal of a matrix into a vector, or creates a matrix having the vector as its diagonal.
• fliplr - Flips a matrix left to right.
• flipud - Flips a matrix up and down.
• rot90 - counterclockwise
• tril - Extracts lower triangular part
• triu - Extracts upper triangular part
• ( NOT the same as LU factorization - See "lu" if you are interested in that. )
4. Chapter 7 - Plotting
• Above and beyond right-clicking on the variable and selecting a plot from the menu
• May not include complete coverage of the entire chapter.
• Useful annotations:
• title( 'text' );
• xlabel ( 'label' ); - also ylabel, zlabel
• text( x, y, 'text' ) - places text at the coordinates specified
• gtext( 'text' ) - places the text interactively using a mouse and cross hairs.
• colorbar - shows the mapping of numbers to colors
• Colormap - controls mapping of data values to colors for many plot types
• A "color" is a set of 3 numbers, indicating the relative amount of red, green, and blue light.
• A colormap is any array of 3 columns and any number of rows, representing an array of colors.
• "help graph3d" for list of pre-defined colormaps and other useful 3D graphing commands.
• Most plotting commands will use row and column numbers to label the axes if no alternative data is provided.
• There is generally a variation that allows you to provide your own data for labeling the axes.
• Example: pcolor( x, y, data ) instead of pcolor( data ), where "data" is a 2-D matrix and "x" and "y" are vectors equal in length to the number of columns and rows respectively in the data matrix.
• The "axis" command can be used to adjust the scaling ( but not the values ) of the axes.
• Survey of Matlab plot types
• Line plots
• Stem and stair plots
• Bar plots
• Scatter plots
• Pie charts
• Histograms
• Polar plots
• Contour plots
• Images
• 3D Surfaces
• Volumetrics
• Vector fields
• Analytic plots
• Subplot( m, n, p ) - Breaks the figure into m x n sub plots, and selects the pth plot for drawing.
• hold - Toggles whether the current plot is held for future plotting commands. ( Used for plotting multiple plots of different types on a single set of axes, such as a line plot and a bar chart for example. ) Can also be used as "hold on" and "hold off".
• "plot" can also plot multiple lines on the same set of axes.
• See also plotyy for a plot with two lines plotted on separate y axes.