Basic Matlab

About Matlab

Matlab stands for Matrix Laboratory. It started out as a scripting language developed by graduate student Cleve Moler so he could use LINPACK subroutines without having to write a Fortran program for each calculation.

Cleve Moler later founded MathWorks, which continues to expand and market Matlab. Matlab has by now absorbed most of the public domain scientific computation software, and has its own programming language and graphing system. There are interfaces to programming languages, to the Excel spreadsheet, scientific instruments, and much more. There is also an add-on called Simulab for circuit simulation.

ISU has a site license for Matlab, and it should be available in every lab on campus. You can probably get a cheap version for your own computer; details change frequently, so check the ISU Information Technology software page.

Data Types

Matlab has several different data types. The main data type is double, which consists of scalars, vectors and matrices of real or complex numbers.

Other data types you may come across are char (strings), sym (symbolic variables), inline (inline function), function_handle (function handles), cell (cell arrays) and struct (structures).

class(x)        % tells you which type it is

There are others, and you can also develop your own (object-oriented programming).

Constants and Variables

x = 1
x = 1.234
x = 1.23e5        
% 1.23*105
x = 'string'
x = [1,2;3,4]
A(3,4) = 3
                   % entry in matrix A

All matrices start with subscript 1. Commas separate numbers in the same row; semicolons separate rows.

Variable names can contain letters, numbers and underscores, for example x, x1 or x_1. The first character has to be a letter or underscore. There is some limit on length, but it is so large that it does not matter in practice.

All numbers are internally stored as double precision variables (about 15 decimals of accuracy).

Predetermined Variables

nargin, nargout, varargin, varargout
         (only in functions)

Basic Matrices

x = zeros(3,4)
x = ones(3,4)
x = eye(3)
x = diag([1,2,3])


Separated by comma, end of line, or semicolon. Comma or end of line cause the result to be displayed, semicolon suppresses the result. If you do not assign the result to any variable, it gets automatically assigned to variable ans.

y = x + ...                          % continuation statement
% comment

Important Commands

help <function>
lookfor <string>
format compact/loose
format short/long
diary <file name>
diary on/off

Basic Arithmetic Functions

c = a + b
c = a - b
c = a * b   
          % * cannot be omitted
c = a / b
c = a^b

Caution: they all work in matrix sense

A±B        % A, B must be matrices of same size, or scalars
A*B     % A, B must be matrices of compatible size, or scalars
A/B    % explained below
A'          % complex conjugate transpose

X=A/B is the least squares solution of X*B=A. If B is invertible, then A/B=A*B-1

X=A\B is the least squares solution of A*X=B. If A is invertible, then A\B=A-1*B.

Pointwise Arithmetic Functions on Matrices

C = A.*B
C = A./B
C = A.^B
    % real transpose

Standard functions all work element by element when applied to matrices:

C = sin(A), cos(A), exp(A), log(A), etc.

Use Vector/Matrix Notation

To write good Matlab programs, you have to learn to think in terms of entire vectors and matrices, not in terms of element-by-element computations. Your programs will be shorter and run faster.


for i = 0:100
    x(i+1) = i/10;
    y(i+1) = x(i+1)^2 - 2*x(i+1) + 1;


x = 0:0.1:10;
y = x.^2 - 2*x + 1;  
              % x.^2, not x^2

Matrix Concatenation

[A, B; C, D]

special case:  x = ['string',' and another string']

The Colon Operator and Matrix Subscripting

1:10 = [1,2,3,4,5,6,7,8,9,10];
1:0.2:2 = [1, 1.2, 1.4, 1.6, 1.8, 2]
5:-1:1 = [5,4,3,2,1]

Colon-generated lists are used often in subscripting and loops:

A(1:3,2:3) = the 3x2 submatrix taken from rows 1-3, columns 2 and 3
A([1,2,3],[2,3]) = same thing

In subscripting, a single colon means "from beginning to end". You can also use the string "end".

A(:,2) = second column
A(2,:) = second row
A(:) = matrix A strung out into a vector
A(end-2:end) = last 3 entries

Formatting Output


The disp(whatever) command has precisely the same effect as just typing whatever, except it doesn't put up the labeling.

>> x
x =
    1   2   3
>> disp(x)
    1   2   3

Note that disp takes a single argument. To display several things, you have to group them together:

>> a = 1
a =
>> b = 2
b =
>> disp(a,b)
??? Error using ==> disp
Too many input arguments.
>> disp([a,b])
    1   2

To mix text and numbers, use num2str (number to string):

>> x
x =
    1  3  5
>> i = 2
i =
>> disp(['x(',num2str(i),') = ',num2str(x(i))])
x(2) = 3

Displaying a certain number of significant digits

Normally, you only have two choices: format short, which gives you 5 decimals of accuracy, and format long, which gives you 15 decimals. Internally, Matlab keeps full accuracy, this is just a matter of how the numbers are displayed.

For finer control, use sprintf (modelled on the sprintf function from the C programming language):

>> disp(sprintf('pi = %12.8f',pi))
pi =   3.14159265

The %12.8f means: display this as a floating point number of 12 characters, 8 of them after the decimal point. That leaves 1 character for the decimal point and 3 characters before the decimal point (in this case 1 digit and 2 leading blanks).

>> i = 1
>> disp(sprintf('x%d = 1',i))
x1 = 1
>> disp(sprintf('x%2d = 1',i))
x 1 = 1
>> disp(sprintf('x%2.2d = 1',i))
x01 = 1

Here %d means "display this as an integer, with however many digits that takes". %2d means "display this as an integer, using 2 characters". Since we only have one digit, we get a leading blank. %2.2d means "display this as an integer using the full 2 characters". That generates leading zeros.

Control Structures

for i = <list>

for i = 1:10
for i = [2,3,5,7,11]
for x = 0:0.1:10

if <condition>

if <condition>

if <condition>

if x > 2 ...
if x >= 2 ...
if x == 2 ...  
                          % equal
if x ~= 2 && y < 1 ...        % not equal, and
if x ~= 2 || y < 1 ...   % or

For string comparison, use strcmp

while <condition>

switch s
  case 'a': <statements>
  case 'b','c': <statements>
  otherwise: <statements>


plot(x,y)                      % connect the dots
plot(x,y,'*')            % use * at each data point, instead of line segments between points
plot(x,y,'r--')     % red dashed line

Multiple plots in one picture

method 1:    plot(x,y)         % x is vector, y is matrix
method 2:   plot(x1,y1,x2,y2,...)
method 3:    plot (x1,y1); hold on; plot(x2,y2); ...

        % interactive

Text is interpreted as in TeX (simple cases only, like greek letters, subscripts)

label('\alpha_0 = 0 ... \infty')

Some other relevant commands are listed below. Instead of print, you can also use the buttons on the figure.

grid on/off
a = axis
         % get current values

print -d<format> filename
print -deps                % encapsulated postscript
print -depsc              % color postscript
print -djpeg ...

figure(2)            % make figure 2 the current figure
clf                          % clear current figure
clf(1)                 % clear figure 1

All graphics commands can be executed in the form h = command. h is the handle and can then be manipulated.


The workspace is the set of all variables that you defined. Each function gets its own workspace.

Scripts and Functions

Matlab knows about scripts and functions. Both of them are sequences of commands that are kept in a separate file with ending .m. If the text in the file starts with the word "function", it is a function. Otherwise, it is a script.


  • behaves precisely as if you type the commands at the keyboard
  • no input or output arguments
  • uses main workspace


  • can have input/output arguments (but does not have to)
  • has its own workspace => recursive calls are possible


x = 5;


function y = f(t)
y = t.^2;
x = 10;
         % optional

Call them from main program:

x = 3;
          % x has now the value 5
y = f(x)          % x still has the value 5

General form:

function [out1,out2,...] = f(in1,in2,...)

All input arguments go on the right. All output arguments go on the left. Input and output arguments can have the same name.

Functions can be called with more or fewer input or output arguments than defined. Nothing bad happens as long as you don't try to use an undefined value.


function [y1,y2] = f(x1,x2)

called as

y = f(1,2)                              % y2 is thrown away
[y1,y2,y3] = f(1,2)       % causes error; no value for y3
[y1,y2] = f(1)                     % OK as long as x2 is not used inside f
The following example shows a function norm(x,p) which calculates the p-norm of the vector x. If p is not given, use p=2. This is what the actual built-in norm command does.
function y = norm(x,p)
if nargin < 2
    p = 2
<compute p-norm>

Here is an example with a variable number of outputs. This is how the actual built-in command size works:

[m,n] = size(A)      % returns m, n as two numbers
s = size(A)               % returns [m,n] as 2-vector

function [m,n] = size(A)
<calculate m, n>
if nargout < 2
    m = [m,n];   
        % which is really s

Advanced example:    s = sum(a,b,c,...)      % unknown number of arguments

function s = sum(varargin)
s = 0;
for i = 1:length(varargin)
         % or i = 1:nargin
    s = s + varargin{i};                        % varargin is a cell array

Inline Functions

These can be used for simple, one-line functions, if you don't want to deal with creating a file for them. There are two ways to do this:

f = inline('x.^2 + y','x','y');
g = @(x,y) x.^2 + y;

In this example, f and g are the same function.

The 'x','y' at the end of the definition of f, and the (x,y) in the definition of g, means that the first input argument is x, the second is y. If I call f(2,3), then x=2 and y=3. It is not strictly necessary to specify the order, but it is recommended (unless there is only one argument). There is a default ordering of inputs, but the rules are quite complicated.

In the following example, f and g are different.

a = 5;
f = inline('x.^2 + a*y','x','y');
g = @(x,y) x.^2 + a*y;

The difference is the following.

The formula for f just gets stored when it is defined, and gets evaluated when you call it. When you call f(2,3), you get 2^2 + a*3, but a is undefined inside the workspace of f, and you get an error.

The formula for g gets evaluated when it is defined. However, the current value a=5 gets hardwired into g, so g(2,3)=2^2+5*3=19.

Function Handles

Function handles were developed to pass functions as arguments. Suppose you have a function f, stored in a file f.m, and you want to numerically integrate it from 1 to 3. The integration routine is called quad (for "quadrature").

area = quad(@f,1,3);

@f is a function handle. You can also do

fun = @f; area = quad(fun,1,3);

The syntax from above

g = @(x,y) x.^2 + y;

is a side effect of this. g is actually a handle for an inline function.

Paths and Shadowed Functions

What actually happens when you type x = a?

  1. Matlab looks whether there is a variable a in the workspace. If yes, it uses that.
  2. Matlab checks whether there is a builtin routine named a
  3. Matlab looks in the path for a function a.m. If there is one, it runs the function (with no arguments), and assigns the result to x

There could be several routines a.m in the path. The order of directories in the path determines which one gets executed. The routines after the first one are called shadowed.

When you type x = a(3), the same thing happens. This could be the third element in array a, or function a evaluated with argument 3.

Relevant commands are

path    % show the path
addpath <directory>  
    % add directory at the beginning
rmpath <directory>          % remove from path
clear a                                          % clear variable a in workspace
clear all
which a    % shows the first routine named a in the path
which a -all     % shows also the shadowed routines

Global Variables

Sometimes it is necessary for a function to access variables in the main workspace.

Main program:

global a b
a = 3;
b = 5;


function y = f(x)
global a b
y = x + a - b;

Working With Polynomials

Polynomials in Matlab are represented as vectors of coefficients, highest power first. There are a few commands for manipulating them, unfortunately no polyadd.

>> help polyfun

roots - Find polynomial roots.
poly - Convert roots to polynomial.
polyval - Evaluate polynomial.
polyvalm - Evaluate polynomial with matrix argument.
residue - Partial-fraction expansion (residues).
polyfit - Fit polynomial to data.
polyder - Differentiate polynomial.
polyint - Integrate polynomial analytically.
conv - Multiply polynomials.
deconv - Divide polynomial


>> p = poly([1,2,3])
p =
     1 -6 11 -6
>> roots(p)
ans =
>> p2 = conv(p,p)
p2 =
    1 -12 58 -144 193 -132 36
>> roots(p2)
ans =
    3.000000000000197 + 0.000000542678441i
    3.000000000000197 - 0.000000542678441i
    1.999999999999772 + 0.000000308732273i
    1.999999999999772 - 0.000000308732273i
>> deconv(p2,p)
ans =
    1 -6 11 -6
>> [n,d,pp] = residue([1,0,0,0,0],p)
n =
d =
pp =
     1 6
>> polyder(p)
ans =
     3 -12 11
>> y = polyval(p,0:0.1:4);
>> x = 0:0.1:4;
>> y = polyval(p,x);
>> plot(x,y)
>> roots(polyder(p))
ans =
>> P = polyint(p)
P =
     0.2500 -2.0000 5.5000 -6.0000 0

Optional Material

Structures and Cell Arrays

Standard arrays are written A(i,j). They consist of elements of the same type (usually array of double, or array of char).

A cell array is written A{i,j}. Its elements can have different types. A = {1,[2,3],'hello'} is a 1x3 cell array with elements that are a scalar, a vector, and a string. A{2} = [2,3], so A{2}[2] = 3, and so on.

A structure is a one-dimensional cell-array whose subscripts are text, not numbers. A standard example in programming courses is an employee record: = 'James Smith'; = '(515) 555-1234'
jim.salary = 60000;

This is basically the same as a cell array { 'James Smith', '(515) 555-1234', 60000}, except that the subscripts are 'name', 'phone' and 'salary' instead of 1,2,3.

Getting Input From the Keyboard

The input command does just that:

>> x = input('type a number: ')
type a number: 15
x =

Using the Debugger

The debugger lets you single-step through your routines. I usually invoke it in one of two ways:

  1. Put the command keyboard in the script or function. Execution will stop there and bring up the debugger.
  2. Type "dbstop in <routine_name>". Next time you execute that routine, it will bring up the debugger at the first statement.

To get out of it, use dbquit, followed by dbclear all.

Comments and Help Files

There are two commands for getting help on built-in commands. If you know what the command is called, use help. If you don't, use lookfor. Here is what they actually do:

Comment lines start with a percent sign. The lookfor command goes through every single *.m file in the path, reads the first comment line, and checks it for a string match with what you are looking for. The help command looks at the particular file you are asking for, and lists the first unbroken string of comment lines it finds.

Consider this:

function z = sum(x,y)

% SUM - add two numbers
% z = sum(x,y)
% This function adds the numbers x and y, and returns the sum

% Copyright 2014 by Fritz Keinert

If you follow Matlab's conventions, your own routines will fit right in with the Matlab help system:

  • The first comment line contains the name of the routine in uppercase, followed by a one-line description
  • The following comment lines give an example of how to call it, and what the input and output arguments mean. You can also add details on the algorithm, etc.
  • Any comments you don't want listed (like my copyright notice) are separated by a blank line from the rest.

There is one more kind of documentation you can do. Suppose we guessed (correctly) that the routine for doing a QR decomposition is called qr. We see that this routine is in a directory called matfun, and wonder what other things might be in there. Of course you could go there and look, but there is an easier way:

>> which qr
C:\Program Files\MATLAB704\toolbox\matlab\matfun\qr.m
>> help matfun
Matrix functions - numerical linear algebra.

Matrix analysis.
norm - Matrix or vector norm.
normest - Estimate the matrix 2-norm.
rank - Matrix rank.

This is done by placing a file called Contents.m in that directory. The file contains nothing but comments, which are listed when you type help matfun.

Last Updated: July 31, 2014