0% found this document useful (0 votes)
83 views6 pages

ELEC4042 - Signal Processing 2 MATLAB Review (Prepared by A/Prof Ambikairajah)

This document provides an overview of key aspects of MATLAB including variables, arrays, polynomials, programming loops, and M-files/functions. MATLAB is a powerful mathematical programming language where everything is treated as an array or matrix. Variables, arrays, and polynomials can be declared and manipulated using built-in functions. Programming loops like if/else statements, while loops, and for loops allow for control flow. M-files allow storing sequences of MATLAB commands in text files for reuse.

Uploaded by

Ahmad Hasan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views6 pages

ELEC4042 - Signal Processing 2 MATLAB Review (Prepared by A/Prof Ambikairajah)

This document provides an overview of key aspects of MATLAB including variables, arrays, polynomials, programming loops, and M-files/functions. MATLAB is a powerful mathematical programming language where everything is treated as an array or matrix. Variables, arrays, and polynomials can be declared and manipulated using built-in functions. Programming loops like if/else statements, while loops, and for loops allow for control flow. M-files allow storing sequences of MATLAB commands in text files for reuse.

Uploaded by

Ahmad Hasan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

ELEC4042 – Signal Processing 2

MATLAB Review (prepared by A/Prof Ambikairajah)


Introduction

MATLAB is a powerful mathematical language that is used in most engineering companies today. Its
strength lies in its numerical analysis. MATLAB is not the fastest language to process large amounts of
data, but it is certainly one of the cleanest. Everything in MATLAB is treated as an array, or more
specifically a matrix. Matrix calculations and manipulations are greatly reduced with many inbuilt
functions ready for use.

Variables

In MATLAB, variables can be assigned from the command prompt or assigned in m-files. To get a
complete listing of all the variables, use the command

>> who

MATLAB is a fairly flexible language when it comes to naming variables. They can be declared at any
time. Upon use of a variable it is considered declared and can be used thereafter. Most variables don’t
really have a type. They are usually a number or an array of numbers. It is best that all variables used
are declared at the start of an m-file or function. That way no erroneous variables are created and the
code is easier to debug.

Variables must not contain spaces. The general rules for variables are:

Variable Naming Rules Comment/Examples


Variable names are case sensitive. Cost , cost, CoST and COST are all
different MATLAB variables.
Variable names can contain up to 31 characters. howaboutthisvariablename
Any characters beyond the thirty-first are ignored
Variable names must start with a letter, followed how_about_this_variable_name
by any number of letters, digits or underscores. X51483
Punctuation characters are not allowed, since a_b_c_d_e
many of them have special meaning to MATLAB

In addition there are some MATLAB special variables:

Special Variables Description


ans Default variable name used for results
pi Ratio of the circumference of a circle to its
diameter
eps Smallest number such that, when added to one,
creates a number greater than one on the
computer.
flops Count of floating-point operations
inf Stands for infinity (e.g. 1/0).
NaN (or) nan Stands for Not-a-Number (e.g. 0/0).
i (and) j i = j = √-1
nargin Number of function input arguments used.
nargout Number of functions output argument used
realmin Smallest possible real number
realmax Largest useable positive real number.

The semi colon character ( ; ) is used to suppress output


File Navigation
All the DOS/UNIX commands work in MATLAB. These can be used to navigate the directory
structure in which the files are stored. Some typical commands are:

Command Description
ls Directory and file listing
dir Directory and file listing
cd Print current directory
cd <directory> Change directory
pwd Print working directory

For a complete listing type

>> help general

at the command prompt.

MATLAB Help

If you can’t remember the exact syntax for a function, or whether sin() takes in arguments in radians
or degrees, then the MATLAB help resource is for you. For help on a specific function, at the
command prompt type

>> help <function name>

and the help file will be displayed. Alternatively, the MATLAB toolboxes can be browsed using the
help menu at the top of the screen. Go to Help -> Help Window to browse the various toolboxes.
Usually if you think that there is a mathematical function, then it is probably useful to do a help
command on it as in most cases it will exist.

Arrays and Array Operations

Arrays, or vectors, can be declared in a multitude of ways. The easiest way to create an array is to
specify the elements:

>> x = [0 0.1*pi 0.2*pi 0.3*pi 0.4*pi 0.5*pi 0.6*pi 0.7*pi 0.8*pi


0.9*pi pi];

This creates a row vector with 11 elements in it. MATLAB arrays are a bit unusual to arrays in other
languages in that they start from element 1. Hence

» x(1)

ans =

and

» x(0)
??? Index into matrix is negative or zero. See release notes on
changes to logical indices.

Another way to specify an array is to use the colon ( : ) operator. It works as:

Variable = (start_value : step size : end_value );

So

y = (0:0.1*pi:pi);
does exactly the same thing as the array declared above.

Array concatenation is relatively straight forward. You just get two arrays and enclose them in square
brackets.

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

>> C = [A B]

C =
[1 2 3 4 5 6 7 8]

Transpose of an array is achieved using the ( ‘ )

» C = C'

C=

1
2
3
4
5
6
7
8

To do a scalar operation on an array, just use the normal mathematical operations. For example to
multiply every element in C by 2, you use the command:

>> C = 2*C
C =

2 4 6 8 10 12 14 16

Say you would like to multiply every element in a by every element in b. Then you would have to use
the ( . ) operator. It applies the statement element-wise, performing the operation on each term in one
vector by the corresponding term in the other. If the dot operator wasn’t used then MATLAB would
assume that you wanted to do a matrix manipulation and then change the vectors in the linear algebra
fashion. An example of this is as follows:

» a = [2 2 2 2]

a =

2 2 2 2

» b = [1 2 3 4]

b =

1 2 3 4

» a.*b

ans =

2 4 6 8
If a*b was used, the result would have been

» a*b
??? Error using ==> *
Inner matrix dimensions must agree.

This was because MATLAB was trying to perform a matrix calculation on the data, which cannot be
done in this case as two row vectors cannot be multiplied in matrix form.

To access elements in a matrix is the same way as it is done for a vector. Say that M is a 5x5 matrix. To
access the (1,4) element, the command is

>> M(1,4)

There are some MATLAB commands that make creating vectors easy. Two of the more useful ones are

>> zeros(n,m);
>> ones (n,m);

Zeros creates a matrix (n,m) made entirely of zeros. This can be used to initialize matrices or to setup
an impulse vector. Ones , on the other hand, returns a (n,m) matrix composed entirely of ones. This is
useful for some FIR filter realizations.

Polynomials

Polynomials in MATLAB are represented by arrays. The usual representation is that the elements in an
array are the coefficients of the polynomial starting from the highest order term to the lowest order
term. If a term is not present then its coefficient is entered as 0. An example is:
3
y 5. x 9. x 1

is represented by

>> y = [5 0 9 1];

The other way to represent polynomials is via their roots. In MATLAB these are also represented by
arrays. The polynomial:

y ( x 3) . ( x 5) . ( x 9)

is represented by

>> y = [-3 5 -9];

The more common representation is the first one but either is used depending upon the application.

Two very useful commands are roots and poly. The command roots() will factorize a
polynomial into its roots and return the roots in an array. The function poly() does the opposite. It
takes in the roots of a polynomial and returns the coefficients of the polynomial. To multiply two
polynomials, you have to use the conv() command. This multiplies two arrays in the polynomial
sense and returns the resultant polynomial

Programming loops.

All the usual programming loops can be implemented in MATLAB. If statements, while and for loops
can all be implemented with the following syntax.

if statement: - syntax
Statement syntax Example

if <case> if x > 10
<do this> y = y + 1;
elseif <case> elseif x > 5
<do this> y = y – 1;
else else
<do this> y = y – 4;
end end

while loops

Statement syntax Example

while <case> while x < 20


<do this> y = y/3;
end x = x + 1;
end

For loops

Statement syntax Example

for <variable = statement> for n = 1:1:10


<do this> x(n) = 2*n;
end end

M-files and Functions

Instead of writing command line parameters in MATLAB, a text file can be assembled of commands.
These are called m-files because the files are named <filename>.m (m standing for MATLAB).
MATLAB has a text editor in which you can create and save m-files. You place code in an m-file as
you would at the command prompt and upon calling the script the code executes sequentially. To
execute an m-file, change to the directory in which it is located and type the name of the file. For
example if there is an m-file called lab1.m in the current directory execute it by typing at the
command prompt:

>> lab1
If commands are placed into an m-file and it is executed, the variables created and used go into the
MATLAB workspace and for all intents and purposes can be treated as global variables. To restrict a
cluttering up of the workspace, functions can be created. Create an m-file as usual but at the start use
the keyword function with this syntax.

function [output1,output2,…] = functionName(input1,input2,…)

Save the m-file with the same name as functionName and then the function may be called from the
command prompt as you would any other function. Functions obey the scope and privacy laws of most
programming languages. So any variables declared within the function are local and disappear upon
exiting the function. The only things returned to the workspace are the outputs of the function.

Plotting

One of the most useful abilities of MATLAB is its ability to plot data easily. To plot a vector type

>> plot(vectorName)
at the command prompt and a scaled plot of the vector appears. There are a lot of inputs to plot to make
the plot nicer looking so type help plot at the command prompt to find the usefulness of plotting.
Another useful plot for discrete data is stem(). It will plot a discrete plot for you that is sometimes
more illustrative.

To clear the graph type clf.

Plots can be manipulated easily. Titles, x-labels, and y-labels can be added by in the following manner:

>> title(‘Frequency Curve’);


>> xlabel(‘Frequency (Hz)’);
>> ylabel(‘Amplitude (Volts)’);

More than one graph can be plotted at the one time. The subplot(n,m,x) command does this and
takes in arguments (n,m) which are the number of axes to display i.e. (3,2) gives six axes, three down
and two across. The final argument to subplot is which graph is currently being referred to. This is
best illustrated with an example. The following is a snippet of MATLAB code and its corresponding
output.

% initialize variables
t = (0:0.01:3);
x = 3*sin(2*pi*t);
y = 4*cos(2*pi*t);

% plot the sine wave in the top graph


subplot(2,1,1),plot(t,x);
subplot(2,1,1),title('Sine wave (frequency 1Hz)');
subplot(2,1,1),xlabel('Time (sec)');
subplot(2,1,1),ylabel('Amplidtude (Volts)');

%plot the cos wave in the bottom graph


subplot(2,1,2),plot(t,y);
subplot(2,1,2),title('Cos wave (frequency 1Hz)');
subplot(2,1,2),xlabel('Time (sec)');
subplot(2,1,2),ylabel('Amplidtude (Volts)');

Sine wave (frequency 1Hz)


4
Amplidtude (Volts)

-2

-4
0 0.5 1 1.5 2 2.5 3
Time (sec)
Cos wave (frequency 1Hz)
4
Amplidtude (Volts)

-2

-4
0 0.5 1 1.5 2 2.5 3
Time (sec)

You might also like