Matlab commands and variables


Matlab commands and variables

Contents






Introduction



Matlab, MATrix LABoratory, is a powerful, high level language and a technical computing environment which provides core mathematics and advanced graphical tools for data analysis, visualisation, and algorithm and application development. It is intuitive and easy to use. Many common functions have already been programmed in the main program or on one of the many toolboxes. In MATLAB everything is a matrix, (this is the mantra: everything is a matrix) and therefore it is a bit different from other programming languages, such as C or JAVA. Matrix operations are programmed so that element-wise operations or linear combinations are more efficient than loops over the array elements. The for instruction is recommended only as last resource.



Matrices and operations



A matrix should be understood in the mathematical sense:

% "A rectangular array of symbols or mathematical expressions arranged in rows and columns, 
treated as a single entity, and now usually written within round brackets"

and not as (other definitions from the Oxford dictionary) an uterus of a mammal or the amorphous or fibrillar material that surrounds cells. The simplest matrix is a 1 x 1 array with one scalar value, or a single number. This value can be assigned to a variable which will store the value and can later be used in conjunction with other variables. For example to store the value 5 in a matrix with the name "a", the following code is typed in the coomand window after the prompt (>>):


a=5
a =

     5

After pressing enter the value is stored, the workspace will show the an entry for "a" and Matlab will "echo" the answer to the command entered. In this case, the echo just repeats what was typed before, but it can be used with more complex data. For instance:

b = 45 + 123 +  a
b =

   173

In this way, Matlab can be used as a calculator and no variables are required if the resulting value is not to be stored, Matlab will store it in a temporary variable called 'ans'. The order of precedence in which the operations are carried out is exponentiation, then multiplication/division and then addition and subtraction, but this can be modified by using parenthesis. For instance:

1 + 2 * 3 ^ 4
ans =

   163

is equivalent to:

1 + (2 * (3 ^ 4))
ans =

   163

and is different from

(((1 + 2) * 3) ^ 4)
ans =

        6561

Matrix operations are programmed in Matlab so that element-wise operations or linear combinations are more efficient than loops over the array elements and therefore Matlab is a bit different from other programming languages, such as C or JAVA. The for instruction is not as widely used as in C. Once you are in MATLAB, many UNIX commands can be used: pwd, cd, ls, ....

To create a matrix you can type its values directly:

x = [ 1 2 3 4 5 6 7 8 9 10 ];

Which is equivalent to:

x = 1:10;

where only initial and final values are specified. It is possible to define the initial and final value and increment (lower limit: increment: upper limit) using the colon operator in the following way:

z = 0 : 0.1 :20;

Both are 1 x 10 matrices. Note that this would be different from:

y = [1;2;3;4;5;6;7;8;9;10];

or

y=[1:10]';

Both are 10 x 1 matrices. The product x*y would yield the inner product of the vectors, a single value, y*x would yield the outer product, a 10 x 10 matrix, while the products x*x and y*y are not valid because the matrix dimensions do not agree. If element-to-element operations are desired then a dot "." before the operator can be used, e. g. x.*x would multiply the elements of the vectors:

x*y
ans =

   385

y*x
ans =

     1     2     3     4     5     6     7     8     9    10
     2     4     6     8    10    12    14    16    18    20
     3     6     9    12    15    18    21    24    27    30
     4     8    12    16    20    24    28    32    36    40
     5    10    15    20    25    30    35    40    45    50
     6    12    18    24    30    36    42    48    54    60
     7    14    21    28    35    42    49    56    63    70
     8    16    24    32    40    48    56    64    72    80
     9    18    27    36    45    54    63    72    81    90
    10    20    30    40    50    60    70    80    90   100

x.*x
ans =

     1     4     9    16    25    36    49    64    81   100

The Matrix obtained by typing:

mat = [1 2 3 4;2 3 4 5;3 4 5 6;4 5 6 7]
mat =

     1     2     3     4
     2     3     4     5
     3     4     5     6
     4     5     6     7

The final semicolon (;) inhibits the echo to the screen. Any individual value of the matrix can be read by typing (without the semicolon):

mat (2,2)
ans =

     3

Mathematical functions can be used over the defined matrices, for example:

s1 = sin (z);

A column or line of a matrix can be obtained from another one:

s2(1,:) = -s1/2;
s2(2,:) = s1;
s2(3,:) = s1 * 4;


Simple Plots



To display a 1D matrix you can use plot, and for 2D you can use mesh, Figure 1 shows the result of typing:

plot(s1);
mesh(s2);

More plotting options will be introduced in the following sections.



Advanced Matrix manipulation



The matrices in Matlab can be manipulated in ways that can simplify your life considerably, so you can try to work as much as possible in Matlab before considering exporting your data to other packages like spreadsheets. But to be able to do this, you need to be able to address the matrix, that is designate or recall only some elements of a matris. Take the following matricies for example:

a = [1 2 3 1 2 3 1 2 3 1 2 3];
b = [3 3 3 3 2 2 2 2 2 1 1 1];
c = [1 2 3 4 5 6 7 8 9 1 2 3];

say you want the elements of a that are larger than 1, you address a with that logical condition (a>1):

>> a>1
ans =

     0     1     1     0     1     1     0     1     1     0     1     1

this is the array which indicates which elements of a that are larger than 1 (1) or not (0). We will take this addressing one step forward by not just comparing a matrix but by extracting some elements from it:

>> a(a>1)
ans =

     2     3     2     3     2     3     2     3

Notice that the output only contains a subset of the elements of the matrix "a". This concept of "addressing" does not need to be restricted to a single matrix, for instance, if we want to recall the elements of "b" that are at the positions where the elements of "a" are larger than 1 we type:

>> b(a>1)
ans =

     3     3     2     2     2     2     1     1

The commands can be nested and combined:

>> c((a>1)&(b>1))
ans =

     2     3     5     6     8     9

The previous line will retrieve the elements from "c" for those cases where a>1 AND b>1. If we raise the values:

>> c((a>2)&(b>2))
ans =

     3


Using "help"



To get help over any command you can type:

help sum
 SUM Sum of elements.
    S = SUM(X) is the sum of the elements of the vector X. If
    X is a matrix, S is a row vector with the sum over each
    column. For N-D arrays, SUM(X) operates along the first
    non-singleton dimension.
    If X is floating point, that is double or single, S is
    accumulated natively, that is in the same class as X,
    and S has the same class as X. If X is not floating point,
    S is accumulated in double and S has class double.
 
    S = SUM(X,DIM) sums along the dimension DIM. 
 
    S = SUM(X,'double') and S = SUM(X,DIM,'double') accumulate
    S in double and S has class double, even if X is single.
 
    S = SUM(X,'native') and S = SUM(X,DIM,'native') accumulate
    S natively and S has the same class as X.
 
    Examples:
    If   X = [0 1 2
              3 4 5]
 
    then sum(X,1) is [3 5 7] and sum(X,2) is [ 3
                                              12];
 
    If X = int8(1:20) then sum(X) accumulates in double and the
    result is double(210) while sum(X,'native') accumulates in
    int8, but overflows and saturates to int8(127).
 
    See also PROD, CUMSUM, DIFF, ACCUMARRAY, ISFLOAT.

    Overloaded functions or methods (ones with the same name in other directories)
       help timeseries/sum.m
       help darray/sum.m
       help umat/sum.m
       help ndlft/sum.m
       help sym/sum.m

    Reference page in Help browser
       doc sum

Use help for the following functions:


sign,	subplot,    abs,        imshow, pi
surf,	colormap,   sum,        cumsum, fix
round,  subplot,    whos,       title,  for,
who,    sqrt,       conv,       floor,  det,
fft,    abs,        semilogx,   axes,   axis, 
zeros,  ones,       rand,       randn,  real,
        


There are many toolboxes with specialised functions, try:

% help images 	Image processing toolbox.
% help signal 	Signal processing toolbox.
% help stats	Statistics toolbox
% help nnet	Neural networks toolbox
    

To find out which toolboxes you have installed type ver:

 
ver
-------------------------------------------------------------------------------------
MATLAB Version  (R2007a)
MATLAB License Number: 
Operating System: Mac OS X  Version: 10.5.8 Build: 9L30 
Java VM Version: Java 1.5.0_24 with Apple Inc. Java HotSpot(TM) Client VM mixed mode, sharing
-------------------------------------------------------------------------------------
MATLAB                                                Version 7.4        (R2007a)
Simulink                                              Version 6.6        (R2007a)
Aerospace Blockset                                    Version 2.3        (R2007a)
Aerospace Toolbox                                     Version 1.1        (R2007a)
Bioinformatics Toolbox                                Version 2.5        (R2007a)
CStruct Toolbox                                       Version 2.0.1              
Communications Blockset                               Version 3.5        (R2007a)
Communications Toolbox                                Version 3.5        (R2007a)
Control System Toolbox                                Version 8.0        (R2007a)
Curve Fitting Toolbox                                 Version 1.1.7      (R2007a)
Database Toolbox                                      Version 3.3        (R2007a)
Distributed Computing Toolbox                         Version 3.1        (R2007a)
Extended Symbolic Math Toolbox                        Version 3.2        (R2007a)
Filter Design Toolbox                                 Version 4.1        (R2007a)
Financial Derivatives Toolbox                         Version 5.0        (R2007a)
Financial Toolbox                                     Version 3.2        (R2007a)
Fixed-Income Toolbox                                  Version 1.3        (R2007a)
Fixed-Point Toolbox                                   Version 2.0        (R2007a)
Fuzzy Logic Toolbox                                   Version 2.2.5      (R2007a)
GARCH Toolbox                                         Version 2.3.1      (R2007a)
Genetic Algorithm and Direct Search Toolbox           Version 2.1        (R2007a)
Image Processing Toolbox                              Version 5.4        (R2007a)
Instrument Control Toolbox                            Version 2.4.2      (R2007a)
LSM File Toolbox                                      Version 1.1.0              
MATLAB Distributed Computing Engine                   Version 3.1        (R2007a)
MATLAB Report Generator                               Version 3.2        (R2007a)
Mapping Toolbox                                       Version 2.5        (R2007a)
Model Predictive Control Toolbox                      Version 2.2.4      (R2007a)
Neural Network Toolbox                                Version 5.0.2      (R2007a)
Optimization Toolbox                                  Version 3.1.1      (R2007a)
Partial Differential Equation Toolbox                 Version 1.0.10     (R2007a)
RF Blockset                                           Version 2.0        (R2007a)
RF Toolbox                                            Version 2.1        (R2007a)
Robust Control Toolbox                                Version 3.2        (R2007a)
Signal Processing Blockset                            Version 6.5        (R2007a)
Signal Processing Toolbox                             Version 6.7        (R2007a)
SimBiology                                            Version 2.1.1      (R2007a)
SimDriveline                                          Version 1.3        (R2007a)
SimEvents                                             Version 2.0        (R2007a)
SimHydraulics                                         Version 1.2        (R2007a)
SimMechanics                                          Version 2.6        (R2007a)
SimPowerSystems                                       Version 4.4        (R2007a)
Simscape                                              Version 1.0        (R2007a)
Simulink Control Design                               Version 2.1        (R2007a)
Simulink Fixed Point                                  Version 5.4        (R2007a)
Simulink Parameter Estimation                         Version 1.2        (R2007a)
Simulink Report Generator                             Version 3.2        (R2007a)
Simulink Response Optimization                        Version 3.1.1      (R2007a)
Simulink Verification and Validation                  Version 2.1        (R2007a)
Spline Toolbox                                        Version 3.3.2      (R2007a)
Stateflow                                             Version 6.6        (R2007a)
Statistics Toolbox                                    Version 6.0        (R2007a)
Symbolic Math Toolbox                                 Version 3.2        (R2007a)
System Identification Toolbox                         Version 7.0        (R2007a)
SystemTest                                            Version 1.1        (R2007a)
Video and Image Processing Blockset                   Version 2.3        (R2007a)
Virtual Reality Toolbox                               Version 4.5        (R2007a)
Wavelet Toolbox                                       Version 4.0        (R2007a)

Trademarks
------------------
MATLAB, Simulink, Stateflow, Handle Graphics, Real-Time Workshop, and xPC
TargetBox are registered trademarks and SimBiology, SimEvents, and
SimHydraulics are trademarks of The MathWorks, Inc. Other product or
brand names are trademarks or registered trademarks of their respective
holders.