# Notes on matlab

• Use xwin or an unix workstation to work with graphics in matlab.
• On the PC log in by double click on the xwin icon. click on xwin in the task bar. Choose from the pop up window: session => scf. Type in your login name and password and a xterm window will pop up.
• Start matlab by typing matlab at the unix prompt. The matlab prompt >> will appear
• matlab commands can be typed from the promt directly or a file with name filename.m can be created. If the filename is typed in matlab all commands written in the file will be executed.

### Matlab basics:

• more on/ more off: toggles between showing screen output continuously and screen by screen.
• help: gives a list of matlab libraries available. help library gives all commands with some information for a specific library. helpcommand gives help to a specific command: e.g.: help sin.
• helpdesk: opens a web page with more information on matlab with lots of examples.
• ;       prevents screen output after a command: e.g.: a = sin(10); doesn't give an echo on the screen.
• []     delimiter for vectors and matrices. e.g:  a = [3, 4, 5]  creates the vector (3 4 5). Entries in a row are separated by space or , . Entries in a column are separated by typing enter or by ; . e.g.: a = [1,2,3                                    4,5,6]  is the same than     a = [1 2 3; 4 5 6].
• matlab understands algebraic operations such as * + - / ^ . However be careful those are matrix operations and the dimensions must agree. e.g. a = [1,2,3]. b = a^2 returns an error since dimensions are wrong.
• a'    transpose of an vector. e.g. a = [1,2,3] b = a' makes b a column vector.
• . operator    a dot in front of an operator means the operator is performed on each scalar in the matrix (no matrix operation). e.g.: a = [1,2,3]. b = a.^2 returns b = [1,4,9].
• ones(a,b) zeros(a,b) these commands create a matrix of size a * b with ones or zeros.
• all common mathematical functions such as sin( ), cos( ) exist also in matlab.
• size( ): size of a matrix in each dimension. e.g.: a = [1,2,3] => size(a) returns 3,1.
• plot(x,y): plots y over x.
• print -dps filename.ps: saves the currently open plot to a black and white ps file.
• a:b:c this is a quick way to create a vector with the first element a, steplength b and the last element <= c.

### Discussion session 3 (diary file and files created with the editor)

>> help

HELP topics:

matlab/general       -  General purpose commands.
matlab/ops           -  Operators and special characters.
matlab/lang          -  Programming language constructs.
matlab/elmat         -  Elementary matrices and matrix manipulation.
matlab/elfun         -  Elementary math functions.
matlab/specfun       -  Specialized math functions.
matlab/matfun        -  Matrix functions - numerical linear algebra.
matlab/datafun       -  Data analysis and Fourier transforms.
matlab/polyfun       -  Interpolation and polynomials.
matlab/funfun        -  Function functions and ODE solvers.
matlab/sparfun       -  Sparse matrices.
matlab/graph2d       -  Two dimensional graphs.
matlab/graph3d       -  Three dimensional graphs.
matlab/specgraph     -  Specialized graphs.
matlab/graphics      -  Handle Graphics.
matlab/uitools       -  Graphical user interface tools.
matlab/strfun        -  Character strings.
matlab/iofun         -  File input/output.
matlab/timefun       -  Time and dates.
matlab/datatypes     -  Data types and structures.
matlab/demos         -  Examples and demonstrations.
toolbox/control      -  Control System Toolbox.
control/ctrlguis     -  Control System Toolbox -- GUI support functions.
control/obsolete     -  Control System Toolbox -- obsolete commands.
fuzzy/fuzzy          -  Fuzzy Logic Toolbox.
fuzzy/fuzdemos       -  Fuzzy Logic Toolbox Demos.
toolbox/ident        -  System Identification Toolbox.
images/images        -  Image Processing Toolbox.
images/imdemos       -  Image Processing Toolbox --- demos and sample images
lmi/lmictrl          -  LMI Control Toolbox: Control Applications
lmi/lmilab           -  LMI Control Toolbox
toolbox/local        -  Preferences.
nnet/nnet            -  Neural Network Toolbox.
nnet/nndemos         -  Neural Network Demonstrations.
toolbox/optim        -  Optimization Toolbox.
toolbox/pde          -  Partial Differential Equation Toolbox.
toolbox/robust       -  Robust Control Toolbox.
toolbox/sb2sl        -  SystemBuild to Simulink Translator
signal/signal        -  Signal Processing Toolbox.
signal/siggui        -  Signal Processing Toolbox GUI
signal/sigdemos      -  Signal Processing Toolbox Demonstrations
stateflow/stateflow  -  Stateflow
stateflow/sfdemos    -  Stateflow demonstrations and samples.
toolbox/symbolic     -  Symbolic Math Toolbox.
toolbox/tour         -  MATLAB Tour
wavelet/wavelet      -  Wavelet Toolbox.
wavelet/wavedemo     -  Wavelet Toolbox Demos.

For more help on directory/topic, type "help topic".

>> more on
>> help

HELP topics:

matlab/general       -  General purpose commands.
matlab/ops           -  Operators and special characters.
matlab/lang          -  Programming language constructs.
matlab/elmat         -  Elementary matrices and matrix manipulation.
matlab/elfun         -  Elementary math functions.
matlab/specfun       -  Specialized math functions.
matlab/matfun        -  Matrix functions - numerical linear algebra.
matlab/datafun       -  Data analysis and Fourier transforms.
matlab/polyfun       -  Interpolation and polynomials.
matlab/funfun        -  Function functions and ODE solvers.
matlab/sparfun       -  Sparse matrices.
matlab/graph2d       -  Two dimensional graphs.
matlab/graph3d       -  Three dimensional graphs.
matlab/specgraph     -  Specialized graphs.
matlab/graphics      -  Handle Graphics.
matlab/uitools       -  Graphical user interface tools.
matlab/strfun        -  Character strings.
matlab/iofun         -  File input/output.
matlab/timefun       -  Time and dates.
matlab/datatypes     -  Data types and structures.
matlab/demos         -  Examples and demonstrations.
toolbox/control      -  Control System Toolbox.
control/ctrlguis     -  Control System Toolbox -- GUI support functions.
control/obsolete     -  Control System Toolbox -- obsolete commands.
fuzzy/fuzzy          -  Fuzzy Logic Toolbox.
fuzzy/fuzdemos       -  Fuzzy Logic Toolbox Demos.
toolbox/ident        -  System Identification Toolbox.
images/images        -  Image Processing Toolbox.
images/imdemos       -  Image Processing Toolbox --- demos and sample images
lmi/lmictrl          -  LMI Control Toolbox: Control Applications
lmi/lmilab           -  LMI Control Toolbox
toolbox/local        -  Preferences.
nnet/nnet            -  Neural Network Toolbox.
nnet/nndemos         -  Neural Network Demonstrations.
toolbox/optim        -  Optimization Toolbox.
toolbox/pde          -  Partial Differential Equation Toolbox.
toolbox/robust       -  Robust Control Toolbox.
toolbox/sb2sl        -  SystemBuild to Simulink Translator
signal/signal        -  Signal Processing Toolbox.
signal/siggui        -  Signal Processing Toolbox GUI
signal/sigdemos      -  Signal Processing Toolbox Demonstrations
stateflow/stateflow  -  Stateflow
stateflow/sfdemos    -  Stateflow demonstrations and samples.
toolbox/symbolic     -  Symbolic Math Toolbox.
toolbox/tour         -  MATLAB Tour
wavelet/wavelet      -  Wavelet Toolbox.
wavelet/wavedemo     -  Wavelet Toolbox Demos.

For more help on directory/topic, type "help topic".

>> diary off
>> help

HELP topics:

matlab/general       -  General purpose commands.
matlab/ops           -  Operators and special characters.
matlab/lang          -  Programming language constructs.
matlab/elmat         -  Elementary matrices and matrix manipulation.
matlab/elfun         -  Elementary math functions.
matlab/specfun       -  Specialized math functions.
matlab/matfun        -  Matrix functions - numerical linear algebra.
matlab/datafun       -  Data analysis and Fourier transforms.
matlab/polyfun       -  Interpolation and polynomials.
matlab/funfun        -  Function functions and ODE solvers.
matlab/sparfun       -  Sparse matrices.
matlab/graph2d       -  Two dimensional graphs.
matlab/graph3d       -  Three dimensional graphs.
matlab/specgraph     -  Specialized graphs.
matlab/graphics      -  Handle Graphics.
matlab/uitools       -  Graphical user interface tools.
matlab/strfun        -  Character strings.
matlab/iofun         -  File input/output.
matlab/timefun       -  Time and dates.
matlab/datatypes     -  Data types and structures.
matlab/demos         -  Examples and demonstrations.
toolbox/control      -  Control System Toolbox.
control/ctrlguis     -  Control System Toolbox -- GUI support functions.
control/obsolete     -  Control System Toolbox -- obsolete commands.
fuzzy/fuzzy          -  Fuzzy Logic Toolbox.
fuzzy/fuzdemos       -  Fuzzy Logic Toolbox Demos.
toolbox/ident        -  System Identification Toolbox.
images/images        -  Image Processing Toolbox.
images/imdemos       -  Image Processing Toolbox --- demos and sample images
lmi/lmictrl          -  LMI Control Toolbox: Control Applications
lmi/lmilab           -  LMI Control Toolbox
toolbox/local        -  Preferences.
nnet/nnet            -  Neural Network Toolbox.
nnet/nndemos         -  Neural Network Demonstrations.
toolbox/optim        -  Optimization Toolbox.
toolbox/pde          -  Partial Differential Equation Toolbox.
toolbox/robust       -  Robust Control Toolbox.
toolbox/sb2sl        -  SystemBuild to Simulink Translator
signal/signal        -  Signal Processing Toolbox.
signal/siggui        -  Signal Processing Toolbox GUI
signal/sigdemos      -  Signal Processing Toolbox Demonstrations
stateflow/stateflow  -  Stateflow
stateflow/sfdemos    -  Stateflow demonstrations and samples.
toolbox/symbolic     -  Symbolic Math Toolbox.
toolbox/tour         -  MATLAB Tour
wavelet/wavelet      -  Wavelet Toolbox.
wavelet/wavedemo     -  Wavelet Toolbox Demos.

For more help on directory/topic, type "help topic".

>> more on
>> help

HELP topics:

matlab/general       -  General purpose commands.
matlab/ops           -  Operators and special characters.
matlab/lang          -  Programming language constructs.
matlab/elmat         -  Elementary matrices and matrix manipulation.
matlab/elfun         -  Elementary math functions.
matlab/specfun       -  Specialized math functions.
matlab/matfun        -  Matrix functions - numerical linear algebra.
matlab/datafun       -  Data analysis and Fourier transforms.
matlab/polyfun       -  Interpolation and polynomials.
matlab/funfun        -  Function functions and ODE solvers.
matlab/sparfun       -  Sparse matrices.
matlab/graph2d       -  Two dimensional graphs.
matlab/graph3d       -  Three dimensional graphs.
matlab/specgraph     -  Specialized graphs.
matlab/graphics      -  Handle Graphics.
matlab/uitools       -  Graphical user interface tools.
matlab/strfun        -  Character strings.
matlab/iofun         -  File input/output.
matlab/timefun       -  Time and dates.
>> help elmat

Elementary matrices and matrix manipulation.

Elementary matrices.
zeros       - Zeros array.
ones        - Ones array.
eye         - Identity matrix.
repmat      - Replicate and tile array.
rand        - Uniformly distributed random numbers.
randn       - Normally distributed random numbers.
linspace    - Linearly spaced vector.
logspace    - Logarithmically spaced vector.
meshgrid    - X and Y arrays for 3-D plots.
:           - Regularly spaced vector and index into matrix.

Basic array information.
size        - Size of matrix.
length      - Length of vector.
ndims       - Number of dimensions.
disp        - Display matrix or text.
isempty     - True for empty matrix.
isequal     - True if arrays are identical.
isnumeric   - True for numeric arrays.
islogical   - True for logical array.
logical     - Convert numeric values to logical.

Matrix manipulation.
reshape     - Change size.
diag        - Diagonal matrices and diagonals of matrix.
blkdiag     - Block diagonal concatenation.
tril        - Extract lower triangular part.
triu        - Extract upper triangular part.
fliplr      - Flip matrix in left/right direction.
flipud      - Flip matrix in up/down direction.
flipdim     - Flip matrix along specified dimension.
rot90       - Rotate matrix 90 degrees.
:           - Regularly spaced vector and index into matrix.
find        - Find indices of nonzero elements.
end         - Last index.
sub2ind     - Linear index from multiple subscripts.
ind2sub     - Multiple subscripts from linear index.
Special variables and constants.
eps         - Floating point relative accuracy.
realmax     - Largest positive floating point number.
realmin     - Smallest positive floating point number.
pi          - 3.1415926535897....
i, j        - Imaginary unit.
inf         - Infinity.
NaN         - Not-a-Number.
isnan       - True for Not-a-Number.
isinf       - True for infinite elements.
isfinite    - True for finite elements.
flops       - Floating point operation count.

Specialized matrices.
compan      - Companion matrix.
gallery     - Higham test matrices.
hankel      - Hankel matrix.
hilb        - Hilbert matrix.
invhilb     - Inverse Hilbert matrix.
magic       - Magic square.
pascal      - Pascal matrix.
rosser      - Classic symmetric eigenvalue test
toeplitz    - Toeplitz matrix.
vander      - Vandermonde matrix.
wilkinson   - Wilkinson's eigenvalue test matrix.

>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>> help ones

ONES   Ones array.
ONES(N) is an N-by-N matrix of ones.
ONES(M,N) or ONES([M,N]) is an M-by-N matrix of ones.
ONES(M,N,P,...) or ONES([M N P ...]) is an M-by-N-by-P-by-...
array of ones.
ONES(SIZE(A)) is the same size as A and all ones.

>> a = 1

a =

1

>> a = 1;
>> who

a

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

B =

1     2     3
4     5     6

>> B2 = [ 1,2,3
4 5 6]

B2 =

1     2     3
4     5     6

>> c = [1,2,3,4,5]

c =

1     2     3     4     5

>> d = 0:0.5:100;
>> B

B =

1     2     3
4     5     6

>> B2

B2 =

1     2     3
4     5     6

>> E = B*B2
Error using ==> *
Inner matrix dimensions must agree.

>> B3 = B2'

B3 =

1     4
2     5
3     6

>> E = B*B3

E =

14    32
32    77

>> F = B.*B2

F =

1     4     9
16    25    36

>> help arith

Arithmetic operators.
+   Plus.
X + Y adds matrices X and Y.  X and Y must have the same
dimensions unless one is a scalar (a 1-by-1 matrix).
A scalar can be added to anything.

-   Minus.
X - Y subtracts matrix X from Y.  X and Y must have the same
dimensions unless one is a scalar.  A scalar can be subtracted
from anything.

*   Matrix multiplication.
X*Y is the matrix product of X and Y.  Any scalar (a 1-by-1 matrix)
may multiply anything.  Otherwise, the number of columns of X must
equal the number of rows of Y.

.*  Array multiplication
X.*Y denotes element-by-element multiplication.  X and Y
must have the same dimensions unless one is a scalar.
A scalar can be multiplied into anything.

^   Matrix power.
Z = X^y is X to the y power if y is a scalar and X is square. If y is an
integer greater than one, the power is computed by repeated
multiplication. For other values of y the calculation
involves eigenvalues and eigenvectors.
Z = x^Y is x to the Y power, if Y is a square matrix and x is a scalar,
computed using eigenvalues and eigenvectors.
Z = X^Y, where both X and Y are matrices, is an error.

.^  Array power.
Z = X.^Y denotes element-by-element powers.  X and Y
must have the same dimensions unless one is a scalar.
A scalar can operate into anything.

>>
>>
>> help arith

Arithmetic operators.
+   Plus.
X + Y adds matrices X and Y.  X and Y must have the same
dimensions unless one is a scalar (a 1-by-1 matrix).
A scalar can be added to anything.

-   Minus.
X - Y subtracts matrix X from Y.  X and Y must have the same
dimensions unless one is a scalar.  A scalar can be subtracted
from anything.

*   Matrix multiplication.
X*Y is the matrix product of X and Y.  Any scalar (a 1-by-1 matrix)
may multiply anything.  Otherwise, the number of columns of X must
equal the number of rows of Y.

.*  Array multiplication
X.*Y denotes element-by-element multiplication.  X and Y
must have the same dimensions unless one is a scalar.
A scalar can be multiplied into anything.

^   Matrix power.
>> help *

Operators and special characters.

Arithmetic operators.
plus       - Plus   +
uplus      - Unary plus                         +
minus      - Minus  -
uminus     - Unary minus                        -
mtimes     - Matrix multiply                    *
times      - Array multiply                    .*
mpower     - Matrix power                       ^
power      - Array power                       .^
mldivide   - Backslash or left matrix divide    \
mrdivide   - Slash or right matrix divide       /
ldivide    - Left array divide                 .\
rdivide    - Right array divide                ./
kron       - Kronecker tensor product         kron

Relational operators.
eq         - Equal ==
ne         - Not equal                         ~=
lt         - Less than                          <
gt         - Greater than                       >
le         - Less than or equal                <=
ge         - Greater than or equal             >=

Logical operators.
and        - Logical AND                        &
or         - Logical OR                         |
not        - Logical NOT                        ~
xor        - Logical EXCLUSIVE OR
any        - True if any element of vector is nonzero
all        - True if all elements of vector are nonzero

Special characters.
colon      - Colon  :
paren      - Parentheses and subscripting      ( )
paren      - Brackets                          [ ]
paren      - Braces and subscripting           { }
punct      - Decimal point                      .
punct      - Structure field access             .
punct      - Parent directory                   ..
punct      - Continuation                       ...
punct      - Separator                          ,
punct      - Semicolon                          ;
punct      - Comment%
punct      - Invoke operating system command    !
punct      - Assignment                         =
punct      - Quote  '
transpose  - Transpose                         .'
ctranspose - Complex conjugate transpose        '
horzcat    - Horizontal concatenation          [,]
vertcat    - Vertical concatenation            [;]
subsasgn   - Subscripted assignment          ( ),{
subsref    - Subscripted reference           ( ),{
subsindex  - Subscript index

Bitwise operators.
bitand     - Bit-wise AND.
bitcmp     - Complement bits.
bitor      - Bit-wise OR.
bitmax     - Maximum floating point integer.
bitxor     - Bit-wise XOR.
bitset     - Set bit.
bitget     - Get bit.
bitshift   - Bit-wise shift.

Set operators.
union      - Set union.
unique     - Set unique.
intersect  - Set intersection.
setdiff    - Set difference.
setxor     - Set exclusive-or.
ismember   - True for set member.

>> % Hello World
>> ones(1,2)

ans =

1     1

>> zeros(3,4)

ans =

0     0     0     0
0     0     0     0
0     0     0     0

>> eye(3,3)

ans =

1     0     0
0     1     0
0     0     1

>> who

B         B3        F         ans       d
B2        E         a         c

>> size(B2)

ans =

2     3

>> B = [1,2,3
2,3,5
2,4,6]

B =

1     2     3
2     3     5
2     4     6

>> size(B)

ans =

3     3

>> rank(B)

ans =

2

>> % Polynome ax^2+bx+c
>> a = 3

a =

3

>> b = 4

b =

4

>> c = 5

c =

5

>> x = 0:.01:10;
>> y = a*x.^2+b*x+c*ones(size(x));
>> plot(x,y)
>> xlabel('x')
>> ylabel('y')
>> title('poly2')
>> Poly
>> x = 0:.1:3

x =

Columns 1 through 7

0    0.1000    0.2000    0.3000    0.4000    0.5000    0.6000

Columns 8 through 14

0.7000    0.8000    0.9000    1.0000    1.1000    1.2000    1.3000

Columns 15 through 21

1.4000    1.5000    1.6000    1.7000    1.8000    1.9000    2.0000

Columns 22 through 28

2.1000    2.2000    2.3000    2.4000    2.5000    2.6000    2.7000

Columns 29 through 31

2.8000    2.9000    3.0000

>> y = sin(x)

y =

Columns 1 through 7

0    0.0998    0.1987    0.2955    0.3894    0.4794    0.5646

Columns 8 through 14

0.6442    0.7174    0.7833    0.8415    0.8912    0.9320    0.9636

Columns 15 through 21

0.9854    0.9975    0.9996    0.9917    0.9738    0.9463    0.9093

Columns 22 through 28

0.8632    0.8085    0.7457    0.6755    0.5985    0.5155    0.4274

Columns 29 through 31

0.3350    0.2392    0.1411

>> Integ = trapz(y)

Integ =

19.8833

>> Integ = trapz(y)*0.1

Integ =

1.9883

>> z = Square(3)

y =

9

z =

9

>> t = [ 0 1 2
3 4 5]

t =

0     1     2
3     4     5

>> z = Square(t)

y =

0     1     4
9    16    25

z =

0     1     4
9    16    25

>> % c' = -c  IC c0 = 1 for t = 0
>> help ode45

ODE45  Solve non-stiff differential equations, medium order method.
[T,Y] = ODE45('F',TSPAN,Y0) with TSPAN = [T0 TFINAL] integrates the
system of differential equations y' = F(t,y) from time T0 to TFINAL with
initial conditions Y0.  'F' is a string containing the name of an ODE
file.  Function F(T,Y) must return a column vector.  Each row in
solution array Y corresponds to a time returned in column vector T.  To
obtain solutions at specific times T0, T1, ..., TFINAL (all increasing
or all decreasing), use TSPAN = [T0 T1 ... TFINAL].

[T,Y] = ODE45('F',TSPAN,Y0,OPTIONS) solves as above with default
integration parameters replaced by values in OPTIONS, an argument
created with the ODESET function.  See ODESET for details.  Commonly
used options are scalar relative error tolerance 'RelTol' (1e-3 by
default) and vector of absolute error tolerances 'AbsTol' (all
components 1e-6 by default).

[T,Y] = ODE45('F',TSPAN,Y0,OPTIONS,P1,P2,...) passes the additional
parameters P1,P2,... to the ODE file as F(T,Y,FLAG,P1,P2,...) (see
ODEFILE).  Use OPTIONS = [] as a place holder if no options are set.

It is possible to specify TSPAN, Y0 and OPTIONS in the ODE file (see
ODEFILE).  If TSPAN or Y0 is empty, then ODE45 calls the ODE file
>> t = [ 0 10]

t =

0    10

>> c0 = 1

c0 =

1

>> [t,y] = ode45('F',t,c0)

t =

0
0.0502
0.1005
0.1507
0.2010
0.4063
0.6117
0.8171
1.0225
1.2186
1.4147
1.6108
1.8069
2.0036
2.2002
2.3968
2.5934
2.7900
2.9866
3.1832
3.3798
3.5764
3.7730
3.9696
4.1662
4.3628
4.5594
4.7560
4.9526
5.1492
5.3457
5.5423
5.7389
5.9355
6.1321
6.3287
6.5253
6.7219
6.9185
7.1151
7.3117
7.5083
7.7049
7.9015
8.0981
8.3111
8.5242
8.7372
8.9503
9.2127
9.4751
9.7376
10.0000

y =

1.0000
0.9510
0.9044
0.8601
0.8180
0.6659
0.5421
0.4416
0.3598
0.2957
0.2430
0.1997
0.1642
0.1349
0.1108
0.0910
0.0748
0.0615
0.0505
0.0415
0.0341
0.0280
0.0230
0.0189
0.0155
0.0128
0.0105
0.0086
0.0071
0.0058
0.0048
0.0039
0.0032
0.0026
0.0022
0.0018
0.0015
0.0012
0.0010
0.0008
0.0007
0.0005
0.0005
0.0004
0.0003
0.0002
0.0002
0.0002
0.0001
0.0001
0.0001
0.0001
0.0000

>>  plot(t,y)
>> exit

### Matlab files created with the editors in the discussion session

::::::::::::::
F.m
::::::::::::::
function cprime = F(t,c)
k = 1.0;
cprime = -k*c;
::::::::::::::
Poly.m
::::::::::::::
x = 0:.01:10;
y = sin(x);
plot(x,y)
xlabel('x')
ylabel('y')
title('sin')
::::::::::::::
Poly2.m
::::::::::::::
echo on;
% Polynomial ax^2+bx+c
a = 1;
b = 2;
c = 3;
x = 0:.01:1;
y = a*x.^2+b*x+c*ones(size(x));
plot(x,y,'.');
echo off;
::::::::::::::
Square.m
::::::::::::::
function y = Square(x)
y=x.^2
::::::::::::::
Statistic.m
::::::::::::::
function [m,s,v,sze] = Statistic(x);
m = mean(x)
s = std(x)
v = sqrt(s)
sze = size(x)