Matlab Demo 1

Matlab Overview

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 language, the Excel spreadsheet, scientific instruments, and much more. There is also an add-on called Simulab for circuit simulation.

Data Types

The data types we are likely to encounter in this class are double (numbers), char (strings), sym (symbolic variables), inline (inline function), function_handle (function handles), and many others we don't need.

class(x)        % tells you which type it is

There are others, and you can also develop your own (object-oriented programming). Type double includes complex numbers.

Structures and Cell Arrays (optional)

Standard arrays are written A(i,j). They consist of elements of the same type (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:

jim.name = 'James Smith';
jim.phone = '(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.

Constants and Variables

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

All matrices start with subscript 1.

Matlab is case sensitive, but don't rely on that. Certainly not with script or function files on Windows systems (file names are not case sensitive in Windows).

Predetermined Variables

i
j
eps
pi
inf
ans
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])

Statements

Separated by comma, end of line, or semicolon.

Continuation statements:

y = x + ...
5;
% 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

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

Standard functions all work element by element:

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.

Bad:

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

Good:

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
A([3,2,1],[2,4])

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

Control Structures

for i = <list>
    <statements>
end

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

if <condition>
    <statements>
end

if <condition>
    <statements>
else
    <statements>
end

if <condition>
    <statements>
elseif
    <statements>
elseif
    <statements>
...
else
    <statements>
end

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 strings, use strcmp

while <condition>
  <statements>
end

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

Plotting

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); ... title('text')

xlabel('text')
ylabel('text')
text(x,y,'string')
gtext('string')
        % interactive

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

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

grid on/off
axis([xmin,xmax,ymin,ymax])
a = axis
         % get current values

print -d<format> filename
print -deps graph.ps                % encapsulated postscript
print -depsc graph.ps              % 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.

Workspace

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

Scripts, Functions and Subroutines

I learned programming in Fortran. Fortran has functions and subroutines. The difference is that a function returns a value, and a subroutine does not.

Matlab makes no distinction between functions and subroutines. I think the Matlab documentation does not even use the word subroutine, but it you ever run across it, it means the same as function.

Matlab instead makes a distinction between scripts and functions.

Script:

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

Function:

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

Both scripts and functions are stored as files with .m extension on the computer. If the file starts with the word "function", it is a function. Otherwise, it is a script.

script.m:

x = 5;

f.m

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

Call them from main program:

x = 3;
script;
          % 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.

Examples:

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
end
<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
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
end

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
end

Inline Functions

These can be used for simple, one-line functions, if you don't want to deal with making up a file for them.

f = inline('x.^2 - 2*x+1')

If you have more than one variable, list the variables at the end in the correct order, just to make sure. Note that an inline function operates in its own workspace. In the following example, the variable a is undefined inside the inline function:

>> a = 2
a =
2
>> f = inline('x+a*y','x','y')
f =
Inline function:
f(x,y) = x+a*y
>> class(f)
ans =
inline
>> f(2,3)
??? Error using ==> inlineeval
Error in inline expression ==> x+a*y
??? Error using ==> eval
Undefined function or variable 'a'.

Error in ==> inline.subsref at 25

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").

Old style:      area = quad('f',1,3);

The function name is passed as a string. the problem with that is that if the quad routine internally uses a variable called x1, and your function happens to be called x1, this bombs.

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

fun is now a function handle. This is now the recommended way, but the old way still works.

As a side effect, you can define function handles that point to functions that are defined inline, instead of in an external file.

Notice that this time a has a value, but it is not dynamic. Inside g, a is replaced by its value at the time when g was defined.

>> g = @(x,y) x+a*y
g =
@(x,y) x+a*y
>> g(2,3)
ans =
8
>> a = 4
a =
4
>> g(2,3)
ans =
8
>> class(f)
ans =
inline
>> class(g)
ans =
function_handle

Most of the time, inline functions and function handles behave identically.

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 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.

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.

path
addpath <directory>  
    % add at the beginning
rmpath <directory>          % remove from path
clear a                                          % clear variable a
clear all
which a
which a -all

Passing Functions as Arguments

Old method:

minimum = fmin('f',[a,b],x0)      % find minimum of f on interval [a,b] with initial guess x0

The problem is that if function fmin contains a variable called f, you get weird errors.

New method:

fhandle = @f;                       % function handle
minimum = fmin(@f,[a,b],x0);

Alternative:

f = inline(...)
minimum = fmin(f,[a,b],x0)

Another Alternative:

f = @(x) ...
minimum = fmin(f,[a,b],x0)

The following used to work. Maybe it still does. I still wouldn't recommend it.

minimum = fmin('x.^2-2*x+1',[a,b],x0);

Fun and Games

All versions of Matlab contain some "easter eggs", that means, hidden jokes. Unfortunately, most of them have disappeared over the years.

Still present in version 7:

why

image
axis ij
axis equal
colormap gray

spy

Jokes that I observed myself in the past:

Unfortunately, they have been removed from recent versions.

puzzle

lala
Quit singing and get back to work

lalala

The lalala command can be simulated with these commands:

load handel.mat
wavplay(y)

f***
OK. Your place or mine?

viper

Puts up a picture of a sports car.

>> sqrt(inf)

There was a young Don from Trinity,
Who tried the square root of infinity.
But the number of digits,
Gave him such fidgets,
That he gave up Math for Divinity.

>> log cabin

integral from 1 to 'cabin' of (1/t) dt

>> reshape(1, [-1 -1])
??? Error using ==> reshape
Don't do this again!.
>> reshape(1, [-1 -2])
??? Error using ==> reshape
Cleve says you should be doing something more useful.
>> reshape(1, [-1 -3])
??? Error using ==> reshape
Seriously, size argument cannot be negative..

Jokes that other people have reported that I have not observed:

toilet

shower

Supposedly these commands just make appropriate noises.


Last Updated: January 15, 2009