A Brief Introduction To Matlab
A Brief Introduction To Matlab
This document is not a complete reference. There is a large number of tutorials and
reference manuals available on web for your further reference.
Getting Help
Matlab is a versatile computing environment. However, to effectively utilize this tool,
you need to learn the syntax. This document gives you the basic information you need
to get started. Matlab has excellent on-line help available. To access this help, type in
the command:
>> help
and press enter. This will provide you with a list of general areas where help is
available. To get more information on this particular topic or any specific command or
function you need to know about, type;
>> help "topic-or-command"
For example, your favorite help command in this class will probably soon become:
>> help signal
For help on a specific function, such as the plot command, type in the command or
function name directly after the help command:
>> help plot
If you have way too much time on your hands, you can run the command:
>> demo
This will give you a graphical interface that will let you explore the power of Matlab and
show you how to do many of the operations you will be required to do in Matlab in this
course.
1 of 8
Elementary Operations and Functions
Variables
Variables are assigned values by typing in a mathematical expression, for
example
4log(2)
=
8 . − √23
would be written as:
>> a=4*log(2)/(8^(2.3)-sqrt(23))
giving an answer of
a=
0.0242
Suppression of results
Appending a ";" to the end of the lie suppresses the display of the results. For
example:
>> a=4*log(2)/(8^(2.3)-sqrt(23));
will be followed by the command line. However, typing:
>> a
will display the value of the variable.
For more information on operators, consult the command line help with:
>> help ops
Complex Numbers
Matlab easily deals with complex numbers. To define a complex number, use
either i or j. For example:
>> c=2+i*7;
>> d=(1+j*3)^3;
both give complex numbers:
c = 2.0000 + 7.0000I
d = -26.0000 -18.0000i
To access the real imaginary parts of complex numbers, use the commands
real and imag.
e.g. >> real(c) - gives 2
Consult command line help for use of unknown commands.
e.g. >> help real - shows how you can use the command ‘real’.
2 of 8
Elementary Functions
Elementary functions are evaluated element wise:
>> x=linspace(0,10*pi,200);
>> y=sin(x);
>> plot(y)
You can get a list of available functions with:
>> help elfun
Vectorizing Code
Definition of Vectors/Signals
Matlab provides various commands to generate vectors. A vector can be
viewed as a "sequence of samples", i.e. a digital signal. Check out the following
ones:
>> x=[ 1 2 3 4 5 ]
>> x=1:5
>> x=1:2:10
>> x=linspace(0,1,5)
For more information on the ":"-operator type:
>> help colon
Definition of Matrices
Matlab also provides various commands to generate matrices. Check out the
following ones:
>> A=[ 1 2 3 ; 4 5 6 ; 7 8 9 ]
>> B=eye(3)
>> C=ones(2,3)
>> D=diag([1 5 6 8])
>> E=zeros(3,2)
>> F=rand(1,5)
>> G=randn(5,1)
The last two commands will generate random vectors, i.e. "random signals".
3 of 8
Matrix Manipulation
The following commands are useful for matrix/vector manipulations. One can
easily take the transpose of a matrix, flip the matrix from left to right or up and
down, concatenate two matrices and so for the. Use the matrices defined above
and type:
>> P=A'
>> P=fliplr(A)
>> P=flipud(A)
>> Q=[ A D]
>> R=[ A; B]
Operators
Since Matlab generally deals with matrices you have to be careful when using
operators like "*" or "/". If you want these operators to operate in an element-
by-element fashion, you have to denote this by a leading "."! Check out the
following examples:
>> x=1:5
>> y=y+x
>> y=x.*x
>> y=x-x
>> y=x./(x+x)
Note: "*" and "/" without "." are matrix multiplication and "matrix division"
(special function of Matlab). For example:
>> P=C*A
A special case applies for scalar multiplication:
>> y=2*x
Vectorization
Many tasks that may be implemented with loop structures can be more
efficiently executed with vectorization. Search we for more information.
Graphics
Graphical representation is an important part of visualizing and understanding
signals. The easiest way to graphically display a signal is by using the plot
command:
>> s=[ 1 2 3 4 2 3 5 ];
>> plot(s)
For a complete listing of 2D graphic tools, type:
>> help plotxy
For a more complete listing of graphic commands, type:
>> help graphics
4 of 8
Graphs can be labeled as illustrated in the following example.
EXAMPLE: Plot a discrete-time sinusoid, cos(w n+q ),
where w =p /6 and q =p /6
>> w=pi/6;theta=pi/3;n=-15:15;
>> x=cos(w*n+theta);
>> stem(n,x)
This plot can be labeled. To label it, use the commands:
>> xlabel('n')
>> ylabel('x(n)')
>> title('Discrete-time sinusoid: cos(pi/6*n+pi/3)')
The axes can be set arbitrarily using the axis command. The argument
to the axis command is the vector [XMIN XMAX YMIN YMAX]. For the
above example,
>> axis([-16 16 -2 2])
would change the scale of the plot. The scale should be set so
that all of the data can be conveniently seen.
More than one plot can be placed on a page using the subplot command. For
more information, type:
>> help subplot
Finally, to putting a grid on your plot may make things easier to read. To do
this, type:
>> grid
M-Files ******************************************************************
Matlab is most useful when you write your own programs. You can use any
regular ASCII text editor to do so. Simply open a file with the extension *.m
(which is call an m-file) and edit line by line the sequence of commands you
want to include in your program. Save the file and execute the program by
typing the name of the file (without the .m) on your Matlab command line.
EXAMPLE: Invoke a text editor (e.g. emacs on UNIX or notepad or the Matlab
editor with debugger on PCs) and edit the following lines:
% This is a program that generates a noisy signal
x=linspace(0,10*pi,200);
% compute the signal
y=sin(x);
% compute the noise
z=0.3*rand(1,200);
% add the noise
y=y+z
5 of 8
% plot the signal
plot(y);grid
title('Noisy Sinusoid')
xlabel('x')
ylabel('y')
Save this program for example in a file named noisy.m. Now, make sure the
current directory of Matlab is the directory where the file is located. You can
access this directory by:
>> cd M:\ECE360
You can check the current directory and see a list of available *.m and *.mat
files by executing the commands:
>> pwd
>> what
Finally, execute your program with:
>> noisy
NOTE: You can also write your own functions in Matlab (see the User
Functions section.)
The function will work like a command from the command line if:
They contain existing commands and functions in the Matlab path
The new function is put in a file whose name defines the name of the
function
The top line defines the function syntax
6 of 8
File Import/Export
We will generally use variables saved from the Matlab workspace with
the save command. The file will be a "mat" file (*.mat) and is readable only by
Matlab. To import the variables (as you will need to do for homework) use the
command:
>> load filename
The file must be in Matlab's path (see the path command) or the current
directory should be set to the directory containing the file. (see the M-File
section.)
Often, we need to import data from files. For a list of commands used for io,
type:
>> help iofun
These low-level commands deal with ASCII files, etc.
xlsread, xlswrite can be useful commands.
Miscellaneous
A list of commands worth checking out:
>> help clc
>> help clear
>> help save
>> help open
>> help load
>> help whos
>> help disp
>> help sum
>> help mean
>> help std
>> help roots
>> help max
>> help min
>> help abs
>> help length
>> help num2str
>> help pause
Reference:
This note is adopted from https://www.egr.msu.edu/~aviyente/Matlab_intro.htm.
7 of 8
Basic control structures in Matlab
8 of 8