Resources > Matlab > Getting Started with Matlab

Matlab is short for matrix laboratory. We use the terms matrix and array interchangeably in these notes, although they have different technical math definitions.^{1} For now, you can consider a matrix or array to consist of a list or table of numbers. Why a list or table of numbers? Because, for example, we may want to do calculations with many measurements on an experiment, or solve multiple coupled algebraic equations, or do calculations for multiple design cases at the same time.

Matlab is commercial software that is licensed by UCSD and free to use by UCSD students.

Free programs which are similar to Matlab include FreeMat (compatible but limited capability), Octave (compatible, not so easy to install), and Scilab (mostly compatible).

** Ways to use Matlab for UCSD Students**:

- Matlab is installed in many campus computer labs, find them here.
- You can install and use Matlab on your own computer, see matlab.ucsd.edu. The full installation is 11 GB to download and 31 GB on disk, so I suggest you start with only the Matlab application and the control systems and symbolic toolboxes, then add more toolboxes later, as needed.
- You can run Matlab directly in your web browser with Matlab Online. Create an account at matlab.mathworks.com using your UCSD email. Then sign in. You should be taken directly to the main window of Matlab in your web browser. I’ve only done a quick test. It has the symbolic toolbox, at least. It will Publish to HTML or PDF in new browser windows. You can save m-files to the Matlab Drive of your account.
- You can use Matlab and other UCSD computer lab software remotely over the Internet using the UCSD Virtual Lab on campus or off-campus through the UCSD VPN.
- You can use Matlab on your phone or tablet with the Matlab Mobile app. Get it at your mobile device’s app store.

** Textbook for UCSD students**: The textbook that we will use in our course is S. Attaway, “Matlab: A Practical Introduction To Programming And Problem Solving,” 4th Edition. I will be assigning homework problems from the book. The book is available online at no cost on campus or off-campus through the UCSD VPN. Click the link under “Get it Online” at http://roger.ucsd.edu/record=b9258406~S9. If you want a hardcopy, the bookstore should have them.

Matlab has extensive help available from within the program. There are videos, demos, and the usual help documentation.

The MathWorks, the makers of Matlab, have a lot of interesting material on the web. For example, see the Matlab Plot Gallery (link) to see examples of the types of plots you can make. See programming examples here (link). Also see the Discovery site (link).

__________

^{1}Matrices and vectors are types of arrays. A matrix is a 2D array of numbers, expressions, or symbols. A vector in linear algebra is a 1D array. A scalar is a single number.

**Introduction**

This introduction is meant to give you enough knowledge to start experimenting with Matlab. Matlab is an interactive programming tool. Using Matlab is much friendlier than programming in C. Here are some major differences:

* Matlab can be run interactively. Instructions typed in the Command window execute immediately, whereas in C, programs have to be compiled and linked before execution.

* Variable type definitions are not needed.

* Arrays are much easier to use in Matlab. They do not have to be dimensioned. Operations on arrays are easy to perform without using DO loops.

* Matlab includes an extensive library of procedures. Compared to the mathematical tools in Excel, Matlab’s procedures are more robust so they can handle tougher problems and, for example, “least squares” procedures are not as sensitive to initial guesses. Matlab also has many more procedures than does Excel. Matlab’s procedures including procedures for doing

- 2D and 3D graphics
- matrix manipulations and linear algebra, such as matrix division, inverse of a matrix (inv), getting eigenvalues and eigenvectors (eig)
- nonlinear single and multi-parameter “least squares minimization” (fminsearch),
- integration of multiple coupled ordinary differential equations (ode45),
- process control such as getting the step response of a system (step) and converting from the normal time-domain “state space” representation of a linear system to the system’s transfer functions (ss2tf) and the reverse.

* Matlab has an on-line help library. Issue the instruction “help help” in the Command window to get information on the help library. Type “help procedureName” to get help on the Matlab procedure “procedureName”, e.g., “help inv” to get help on matrix inversion. One tricky thing with help: in help function names are in all caps to make them stand out – however, since Matlab is case-sensitive – all function names have to be used in all lower case!

If you don’t know the Matlab procedure to use, use “lookfor keyword”, where “keyword” is a keyword for what you are looking for, e.g., “lookfor complex” to find information on procedures dealing with complex variables.

INTERACTIVE USE AND “M FILES”:

Matlab instructions (commands) can be issued by typing in the Command window. Below the prompt >> is seen after the previous operation has been completed and Matlab is ready for you to enter a new command.

The best way to learn is to try things out in the Command window and see what happens. Matlab instructions can also be typed into a text file without executing each line as it is typed. This way, you can develop complex programs without seeing error messages, etc. You may also need to write text files that contain information needed by some of Matlab’s standard procedures such as “fminsearch”, which is used in “least-squares” fitting procedures and “ode45”, which is used for integrating ordinary differential equations.

A text file that contains Matlab instructions is called an “m-file” and should end with the .m file name extension. Let’s say you have a text file containing Matlab instruction named “myprogram.m” and located in the default Matlab work folder. To execute the set of instructions, type “myprogram” (no quotes) at the Command window prompt.

For m-files that are located somewhere other than the default Matlab work folder, such as files you download to the desktop, YOU HAVE TO SET THE PATH to which Matlab looks for files. To the right of the path location window is the browse button with three dots […]. Click that button, browse to where your file is, then select that location. See Matlab help for saving paths.

In m-files, use the % character to start comments. Anything following the % character is a comment and not executed. The % can be at the start of a line or after an instruction.

ASSIGNING VARIABLE VALUES:

The instructions demonstrated here are copied from an interactive session in the Command window. Any instruction entered in the Command window can also be typed in an m-file. Prompts such as >> shouldn’t be typed in your m-file, of course.

A variable that contains only a single value can be considered a scalar. If you type a = 5 at the prompt in the command window, the value 5 will be assigned to the variable a and the result of the instruction will be echoed to the screen.

>> a = 5

a =

5

>>

A semicolon at the end of an instruction suppresses the result echo.

>> a = 5;

>>

You will want to suppress most echoing when doing complex calculations. If you don’t, you will see lots of stuff on the screen that you don’t need to and the execution time will be increased dramatically. During DEBUGGING, selectively removing semicolons to echo results of intermediate calculations will be helpful.

The following loads information into the row vector b:

>> b = [1 2 3]

b =

1 2 3

The square brackets [] at the beginning and end of the array definition are required. Either spaces or commas can separate the different values in a row:

>> b = [1,2,3]

b =

1 2 3

The apostrophe at the end of an array assignment is the TRANSFORM operator. The following loads information into the column vector c:

>> c = [2 3 5]’

c =

2

3

5

The following loads values into a two dimensional array or matrix:

>> d = [1 2 3

4 5 6]

d =

1 2 3

4 5 6

This array can also be defined on one input line using a semicolon to specify the end of a row:

>> d = [1 2 3; 4 5 6]

d =

1 2 3

4 5 6

Note the two different uses of semicolons: (a) suppression of echoing a result to the screen when at the end of an instruction, (b) specification of the end of a row of values in a matrix.

USES OF ARRAYS FOR HOLDING INFO:

In most cases in this class we will use column vectors to hold a series of values of a single variable that were taken at different places or times. For example, cA might be a column vector that holds values of the concentration of species A at different times during a batch reaction, cB might hold the values of B at the same times, and t would be a column vector holding the corresponding time values.

We will sometimes combine the values from two or more column vectors to form one matrix. For example, during integration of the equations describing a batch reactor, column one of the matrix c would hold the column vector cA and column two of c would hold the column vector cB. We can combine cA and cB to form c the following way:

% define column vectors cA and cB

>> cA = [1;2];

>> cB = [2;3];

% combine the column vectors cA and cB to form the matrix c

>> c = [cA cB]

c =

1 2

2 3

At other times, we will want to extract column vectors from a matrix:

% pull individual columns out of a matrix

cA = c(:,1); % cA = c ( all rows of column 1 )

cB = c(:,2); % cB = c ( all rows of column 2 )

The colon is used to specify a range of locations,e.g., 1:3 would mean rows 1 to 3 (or columns 1 to 3 if it were specifying column locations). The bare colon means all rows.

In this case, all the values in the matrix are concentrations, so it is natural to name the matrix c or a similar name like concentrations. At other times we may want to keep the values of a concentration, temperature and pressure in the same matrix. This will occur in some integration problems and also when we want to write results of a calculation to a disk file. Since the matrix holds different things, we can use a generic name like y or x for the matrix.

SAVING AND LOADING ARRAYS TO/FROM DISK FILES:

If you want to save the value of an array to disk to be used later in MATLAB, either in the same session or in another session, use an instruction like:

>> save Asaved A

This saves the value of A in the file Asaved.mat. The file name can, of course, be one you pick. The extension .mat refers to Matlab’s binary file format. To retrieve the value of a later in a session or in a different session, enter:

>> load Asaved

Now, the original values of A will have been loaded into a variable named “Asaved”, or whatever else you named the file. To see what values were loaded, just enter the name of the variable and hit return and the variable name and the values contained will echo to the screen.

In many cases in this class, we will want to save data as ASCII text in order to load it into Excel or a scientific plotting program. The following instruction saves the matrix “u” to the disk file “data.txt” as ASCII text with tabs between the values in different columns.

>> save results.txt u -ascii -tabs

In some problems, you may want to enter input data first into a text file with a text editor, then load that text file into MATLAB’s memory for your computations.

>> load input.txt

This reads the ASCII file input.txt, which must contain a rectangular array of numeric data, arranged in m lines with n values in each line. The result is an m-by-n matrix variable named “input”. Other names input and extensions besides txt can be used (but don’t use .mat). If the name of the ASCII file doesn’t have an extension specify the option -ascii after the file name:

>> load input -ascii

Enter the instructions “help save” and “help load” to get more information.

MATHEMATICAL OPERATIONS:

This is one place that can be tricky in Matlab. There is a distinct difference between “matrix operators” and “array operators”:

matrix operators: * / ^ (raise to a power)

array operators: .* ./ .^ (raise to a power)

You have to be careful to notice the dots before the * / and ^ in these notes and in your programs because they are small. I also refer to the array operators as “dot operators”. There is only one + and – to use.

If you are doing linear algebra with vectors and matrices, use the matrix operators, i.e., * / and ^ without the dots. Let’s say that A and B are matrices. A * B performs matrix multiplication of the two matrices, as defined in linear algebra. The two matrices must be of the proper dimensions for matrix multiplication, i.e., the number of columns of A must match the number of rows of B.

You can also use the matrix * operator to multiply a constant times a matrix (e.g., B = 5*A), and can use the / operator to divide a constant into a matrix (e.g., B = A/5) but not divide a matrix into a constant. In addition to constants (e.g., 5) you can also use variables with only one element in the same way as a constant in the above examples. For example, if a = [2], which can be considered a scalar, and b = [1 2], then you can write c = a * b without a dot and get c = [2 4].

In most cases in this class, the arrays we will deal with are column vectors that hold a collection of values of variables, e.g., the values of one variable at each integration step.

For example let’s say that the column vector cA holds the concentration values of A at different batch reactor times, the column vector cB holds the concentration values of B, and the column vector t holds the time values. The first element in cA corresponds to the first element in cB and in t, and so forth. Let’s say that at each time, we want to calculate the reaction rate which is first order in A and first order in B (second order overall). We need to multiply the rate constant k (a scalar variable, i.e., an array with only one element) times the concentration of A at one time times the concentration of B. That is, we need to multiply individual elements of cA and cB times each other, “element by element”, and NOT do matrix multiplication of the matrix cA and cB. This is where the “array operators” or “dot operators” come in. They specify that the operation is performed on the corresponding individual elements of the matrixes and that matrix multiplication or division is not performed. In this example:

r = k * cA .* cB % note the dot immediately before the second *

In an INTEGRATION problem, in the m-file that defines the derivative equations, the individual elements of the dependent variables, e.g., y(1) and y(2), are scalars, so you don’t need dot operators anywhere in the m file that specifies the derivatives. Back in the main m-file, after the integration has been complete and you want to do computation with the results, note that the results you pull out of the y matrix, e.g., cA = y(:,1) and cB = y(:,2) are column vectors and dot operations will need to be peformed in order to multiply the concentrations cA and cB at each time t with each other.

THE EASY WAY OUT: In problems where you do not have any matrix operations, use dot operators ( .* ./ .^ ) everywhere.

In many cases, your dependent variables will have different names. For example, concentration of A and temperature. In such a case, pick a general name such as “y” for the matrix that holds the dependent variables. Then, the first column in y would hold the concentration values, and the second column of y would hold the temperature values. Write some comments defining the relationships and use these definitions in the main m-file and the m-file in which the derivatives are defined.

STRINGS AND PAUSING PROGRAMS:

When an m-file is running, you can print information to the user with strings. Text between two apostrophes is considered a string:

info = ‘this string will print on the screen if no ; at end’

You may want to pause a program. For example, you make a plot and want the user to be able to view the plot before it is redrawn. Print a string to the screen and use the PAUSE command:

info = ‘press any key to continue’

pause

Also see the fprintf command for printing variable values in the string.

GRAPHICS, PLOTTING:

This is a big subject. Start by issuing the instruction “help plot” in the Command window. For a quick example, let’s say that the column vector t contains time values, i.e., is the independent variable, and the column vector c contains concentrations. The following plots the values in c (y axis) vs. the values in t (x axis) and does some basic labeling:

plot(t,c) % plot(x axis vector, y axis vector)

title(‘concentration vs. time’) % note the required apostrophes

xlabel(‘time’)

ylabel(‘concentration’)