Sunteți pe pagina 1din 20

7/03/2016

Basic Course on
Matlab
Prepared by:
Dr Abul Khair bin Anuar
Dept of Communication Engineering, FKEE

Course Outcomes

At the end of this course, student should be able to:


Perform operation involving matrices,
Write simple Matlab code to represent a mathematical function
and operation,
Plot function
Do basic code trouble shooting

1
7/03/2016

Resources...

Can be downloaded via (local intranet only)


http://software.uthm.edu.my/matlab/
Alternatively, an open source software, Octave is available for
download from
ftp://ftp.gnu.org/gnu/octave
no license is needed
Similar to Matlab in terms of scripting
This slide is available at
https://drive.google.com/file/d/0B8Vkra47Ul9xMjAyTUJZd2RpaFk/
view?usp=sharing

Interface

Current folder
To create
new script Workspace
Command window - Showing variables
- Where you entered your
command

Command History
- Past command

2
7/03/2016

Matrix

Matlab is powerful when working with matrices. Data are


normally in matrix form, specified by the row (m) and column
(n).
Example:
In the Command Window, type the following command;
>> a = [1 2 3 4]
>> b = [1; 2; 3; 4]
>> c = [1 2; 3 4]
Observe the outcome of each command.

>> a = [1 2 3 4]
Will gives you 1 x 4 matrix

b = [1; 2; 3; 4]
Will gives you 4 x 1 matrix

>> c = [1 2; 3 4]
Will gives you 2 x 2 matrix

3
7/03/2016

The property of the matrix can be identify by typing


>> size (a) gives the size of the matrix
>> length (a) gives the length (no of column)
A matrix can also be created using special command, eg.
>> d = 1:1:10 creates a matric d with values from 1 to
10, with step of 1.
>> e = 1:2:10 creates a matric d with values from 1 to
10, with step of 2.
>> f = zeros(1,5) creates a 1 x 5 matric f, containing
value 0
>> g = ones(1,5) creates a 1 x 5 matric g, containing
value 1
>> h = linspace(0,1,10) creates a matrix h of length
10, with values equally spaced between
0 and 1

4
7/03/2016

Matrix Operations

Addition/substraction with a scalar


In Command Window, create a matric
>> a = [1 2 3 4]; semi-colon suppresses the output
Write the command
>> b = a + 3
Output
b =
4 5 6 7

Addition/substraction with another matrix


Requires both matrices to be of the same size
Let
>> a = [1 2 3 4];
>> b = [5 6 7 8];
>> c = a + b
Output
c =
6 8 10 12
Try
>> a + d
Youll get an error
Error using + _
Matrix dimensions must agree.

5
7/03/2016

Multiplication/Division with scalar


Do
>> a = [1 2 3 4];
>> b = a*2
Output
b =
2 4 6 8
Each element in the matric is multiplied by the scalar

Multiplication/Division with another matrix


Three outcomes, depending on the syntax used
Let
>> a = [1 2 3 4];
>> b = [2 2 2 2];
1. a*b
This is true matric multiplication. Youll get an error because in matric
multiplication, the inner matrix dimension must be the same, i.e.
(1x4)*(1*4) error
(1x4)*(4*1) produces (1x1) matric
Lets try
>> a*b will gives you a (1x1) matric, as in matric multiplication.
The sign after b means transposing the matrix b, i.e. changing the
shape of matrix b from (1x4) to (4x1)

6
7/03/2016

2 . a*b
This will produce a (4x4) matric since a is a (4x1) matrix, and b is
still a (1x4) matrix.
(4x1)*(1x4) = (4x4)

3. a.*b
This is element multiplication. Each element in a is multiplied with
element in b at the same position.
Output
ans =
2 4 6 8

Accessing element
An element in a matrix can be accessed individually by the following
syntax;
aMatrix(m,n)
where aMatrix is the matrix, m = is the elements row number and n is the
elements column number. In Matlab, indexing starts at 1.
Example;
>> a = [1 2 3 4]; b = [2 2 2 2];
>> aMatrix = a*b; produces (4x4) matrix
To access the element in row 1 and column 1, write the following syntax
>> aMatrix(1,1)
To access all elements in row 1
>> aMatrix(1,:)
To access all elements in column 1
>> aMatrix (:,1)
Accessing certain elements
>> aMatrix(1:2,2:3)

7
7/03/2016

Matrix manipulation

Combining matrix (Concatenate)


>> a = [1 2 3 4];
>> b = [5 6 7 8];
To combine into one row
>> c = [a b]
To combine into two rows
>> d = [a;b];
Reshaping matrix to rearrange the matrix into new shape,
keep the same number of elements
>> e = reshape(c,4,2)

Exercise

Create the following matrices


a = 0:2:10;
b = [1 2 3 4 5 6];
Solve;
a+b
2a-b
2a*b
2a.*b

8
7/03/2016

Creating a script...

A command can be entered directly via Command Window,


or in the case of more complicated script, via Editor.
Click on the icon for New Script, or
Type edit in the Command Window
Command Window is usually reserved to
Run script
Checking script output
Do troubleshooting
Accessing help function

Writing a script

A script contains the code that you want to write.


A good practice is to write some information on what the script is
for and the author (or any other important information).
Use the % sign at the beginning of the line (or you can select the line
and click the % icon)
Lines starting with % will not be executed by Matlab
% also used to include comment in the code
Start the script (without the %) with
clc to clear command window
close all to close any open figure
clear all to clear workspace memory
Script can be saved at any time.

9
7/03/2016

Comments, will not be


executed by Matlab

To clear Command
Window, close figures
and clear Workspace

Variables
Most computer codes begin with variable/constant
declaration. In Matlab, this is done simply by writing the name
and its value before any attempt to use the variable.
A good practice is to use name that it should be self explained.
Eg. To declare a variable for temperature, the name
temperature = 30; %initial temperature, degree Celcius
Each line is normally ended with semi-colon.
Comment is placed after the declaration
for information on the variable.
is much better than just;
t = 30; %initial temperature
Constants are usually represented using CAPITAL LETTERS, eg.
SPEED_OF_LIGHT = 3e8; How to write 3 x 108
Use small and capital letters for long variable names, eg.
initialTemperatureCelcius = 30; Since the variable is self-explained,
no comment is needed

10
7/03/2016

Plotting

Use the Editor to plot a sine function. Let the x-axis represents
the angle, and y-axis represents the values.
Write
angle = -pi:0.1:pi; to create the matrix of x-axis from
to with step size of 0.1
y = sin (angle); sine function (and all trigonometric
functions) only works with radian values
Run the script by clicking the run icon. You might be asked to
save the file first. Save it as Example1.m.
On the main window, you should observe the following.
In Workspace, youll see two variables, angle and y. You can see
the values(by clicking on it) and size of each variable.

To plot the sine function, you can use the Command Window or
add the command in your script.
plot(angle,y); x-axis followed by y-axis
In Command Window, it will be one off command.
In script, the line will be executed everytime the code is executed.
A popup figure will appear. And the plot of sin should be
plotted.
The property of the plot can be change according to your needs.
In Command Window, type
help plot
The help function should be your best tool to understand the
syntax of any Matlab function.

11
7/03/2016

Lets write
plot(angle,y,rx--);
This shows how to control the colour, marker and the linetype of
the plot.
In addition to plot function, there are other types of plotting
tool available. If you type
help plot
you will see related function to plot at the end of the
document.
Try using stem to plot the signal
stem(angle,y);

12
7/03/2016

13
7/03/2016

Multiple Plot

Add the following lines to your Example1.m file.


z = 2*cos(angle);
Now there are two outputs, y and z. The plot of these two
outputs can be done either in separate figure windows, in the
same graph, or in the same window, but on different axes.
To plot in separate windows, type in your editor
figure (1); %to create window for graph 1
plot (angle,y); %plot y in figure 1
figure (2); %to create window for graph 2
plot (angle,z); %plot z in figure 2

To plot in the same graph;


Add the line,
figure (3) % assuming you want to plot in figure 3
%plot y, hold the axes for the next plot
plot(angle,y); hold on
%plot z (red color), release the figure
plot(angle,z,r); hold off

14
7/03/2016

To plot in the same window, different axes, use the subplot


command.
figure (4);
subplot(2,1,1);
plot (angle,y);
subplot(2,1,2)
plot (angle,z);
The subplot(m,n,p) command creates multiple axes based
on the number of row (m) and column(n). The letter p
represent the sequence of axis, counting from the first row
onward.

15
7/03/2016

Plot legends, title, axis, grid


Let us use the second plot (figure 3) as example.
figure (3) % assuming you want to plot in figure 3
%plot y, hold the axes for the next plot
plot(angle,y); hold on
%plot z (red color), release the figure
plot(angle,z,'r'); hold off
Add
legend(y function,z function)
title(y and z versus angle)
xlabel(angle)
ylabel(Values)
axis([-pi pi -2 2])
grid

16
7/03/2016

Conditional Operation

Executing certain operation only if certain conditions are met.


If, elseif,while, for, end, switch, case, break
Operators == equal, ~= Not equal, < less than, > greater
than, <= less than or equal, >= greater than or equal
Type on Command Window
>> help if
the syntax of is shown in the help text.
For end is used to loop through a sequence of number
>> help for

17
7/03/2016

Example 2
Write a script that ask user to choose any number between 1 to 10. For
odd number, do the square of the number, and for even number find the
square root.
n = input('Please choose a number between 1 and 10\n');
To ask user to if mod(n,2)==0 Modulus. It gives the remainder of
pass in value for the operation n/2
a variable disp('The number you choose is even number ');
A command to convert the type of variable from
disp(num2str(n)); number to string. Check str2num using help.
Display a variable
value of type string
disp('The root of the number is');
disp(num2str(sqrt(n)));
Square root
else
disp('The number you choose is odd number ');
disp(num2str(n));
disp('The square of the number is');
disp(num2str(n^2)); The power operator
power normally use more
end memory than simply n*n !

Basic Troubleshooting

Matlab works by executing the command in your script line by


line. You can place the keyword keyboard at any point on
your code to pause the execution up to that point.
dbquit to exit the debugging mode
return to continue with the rest of the code
Suitable for checking whether the script is giving you the correct
output
If place inside a loop, will cause the execution to pause in every
cycle of the loop.

18
7/03/2016

Errors in the code can be of two types:


Syntax error
Trying to do element multiplication of two matrices of different sizes
Missing signs, or bracket, not enough arguments for certain functions
Easier to fix since errors will prevent the script from being executed

Process error
Much harder to detect, unless you know what are you expecting
Script can be executed, but you get wrong output
Eg. Instead of adding two numbers, you do multiplication.
Use keyboard to check the output of the code at different stages of
execution.

Exercise 2

Solve the following mathematical function and plot the


function for 0 5.

sinc

is a matrix with values between 0 and 5. The step size/ length


need to be set up accordingly.

sinc

Use exp(x) for . The letters i and j in Matlab is reserved for


complex number
can be done using for loop

19
7/03/2016

Basic functions

max (aMatrix) or min(aMatrix) to find the maximum


or minimum value of matrix aMatrix
floor(a);ceil(a);round(a) to get the next lowest
integer (floor), highest integer (ceil) or to round to nearest
integer (round). Work for positive and negative values.
fix(a) round towards the neares integer towards zero
Sum(a) sum of elements

20

S-ar putea să vă placă și