ec247 lec1
-
Upload
malith-wox -
Category
Documents
-
view
232 -
download
1
description
Transcript of ec247 lec1
Lecture 01
MATLAB Basics
Today’s Lesson
• Introduction to MATLAB
• Variables and Operators
• Built-in Functions
• Vectors and Matrices
• M-files
Introduction
• MATLAB (Matrix Laboratory)
• Everything in MATLAB is a Matrix
• Powerful graphical computation Tool
• The MathWorks Inc. (http://www.mathworks.com)
• MATLAB 6 (Release 12 and 13)
• MATLAB 7 (Release 14) and 7.5
• Interpreted language like Pascal
• Executed line by line
• No object-oriented features
• Computations, Algorithm developments,
Modelling, Simulations, Data analysis,
Explorations, Data visualisation, GUI
developments
Command WindowCommand History
Current DirectoryCommand Prompt
Workspace
MATLAB Help
• helpdesk : Will open help window
• help function : Give information about the function on the command window
E.g. help sqrt
• doc function : Give more information about the function on the help window
E.g. doc sqrt
Variables and Operators
• 2 + 3
ans =5
• Result will be assigned to a variable ans
• You can reuse the results
• ans + 2
ans = 7
• Variables can be defined by the user
• No need to initialise like int a = 0
a = 2; b= 5
a*b
ans =
10
• You can save, clear and load the variables
– save myFile a b (save in myFile.mat)
– clear a b
– load myFile
• MATLAB uses double-precision floating
point numbers (64 bit)
• It shows only 5 digits by default
• 1/3
0.3333
• You can change the number of digits
format long (15 digits) -> format short (5 digits)
• You can define character variables (16 bits)
x = ‘Hi, How are you.’
• Variable names– First character should be a letter
– Any letter, a number or _
– Case sensitive
• Built-in variables– i, j (for complex numbers), pi (π), ans, Inf
(Infinity), NaN (Not a number)
MATLAB Output• disp () : Print output to the screen
– disp(‘Hi, How are you.)
– disp(a)
• fprintf () : Can be used with formatting– fprintf(‘Answer = %2.3f.\n’, 3*pi)
• Graphical outputs will be displayed in the Figure window– ezplot(‘x^2+x’)
• % is used for Comments– Anything after that is not executed
– Improve readability of the program
• Semicolon (;) at the end will suppressthe output
A = 12 *2;
• clc Clears the command window
Built-in Functions
• MATLAB has a library of built-in functions
• Sqrt(2), log(), log10(), cos()
• floor(), ceil(), abs(), clock, factor()
• sum(), prod(), exp(),
Exercise
• Which of the following is the best approximation to the square root of 7
– 2709/1024
– 10583/4000
– 2024/765
Vectors and Matrices
• Row Vectora = [2, 4, 5]
or
a = [2 4 5]
• Column Vectorb = [10; 20; 30]
• Use transpose operator to converta’ or transpose(a)
Indexing Elements
• MATLAB indexing starts from 1 not from 0a = [ 5 3 4] (Square brackets)a(1) = 5 a(2) = 3 a(3) = 4
(Parenthesis)A(2:3) = 3 4 A(1:end-1) = 5 3
• length (a) – Vector Lengthmin/max(a)
• sort(a) : Sort in Ascending order• find (a == 3) find (a < 3 & a > 6)
• a = 1:10 (Array of integers between 1 and 10)
• b = 1:2:10 (With increment 2)
• Increment could be – or a fragment
• linspace (start, end, no of points): Can divide a range into equal spaces
linspace (1, 9, 5)
Matrices
• a = [2 3 4; 5 6 7] (2x3 Matrix)
• size (a) – Give the dimensions of a Matrix
2 3 4
5 6 7
Concatenating Matrices
• A = [10 20] b = [30 40] c = [50; 60]
• D = [a b]
• E = [a; b]
• F = [e c]
• Create a matrix with zeroszeros (rows, columns)zeros(1, 10)
• Creates a matrix with 1sones (rows, columns)ones (2, 3)
• Creates a matrix with random numbers(uniformly distributed 0-1)
rand (2, 3)
Element by Element Operations
• Use . (dot) with all the Operators (+, -, /, *, ^ - Exponentiation)
A = [2 5; 4 1]
a.^2 => [4 25; 16 1]
a.*b
Exercise
• Find a way to delete 0s from a vector
• Use clock function to find the number hours left to the end of this month
M-Files
• Scripts can be run with MATLAB– Collection of commands
– Executed in sequence
– Use MATLAB editor
– Save as MATLAB file (Extension .m)
• From command prompt – edit abc.m
• From MATLAB Desktop – File -> New -> M-File
• Click the new file button on the Toolbar
• To run the M-File script– Move to the directory where file is saved
– Type the file name (without .m extension)
>> cd the directory
>> abc (abc.m file)
Matrices, Program Controls, User-defined Functions
Vectors and Matrices
• Row Vectora = [2, 4, 5]
or
a = [2 4 5]
• Column Vectorb = [10; 20; 30]
• Use transpose operator to converta’ or transpose(a)
Indexing Elements
• MATLAB indexing starts from 1 not from 0a = [ 5 3 4] (Square brackets)a(1) = 5 a(2) = 3 a(3) = 4 (Parenthesis)A(2:3) = 3 4 A(1:end-1) = 5 3
• length (a) – Vector Length
• min(a), max(a), sum(a)
• sort(a) : Sort in Ascending order
• find (a == 3) find (a < 3 & a > 6)
• a = 1:10 (Array of integers between 1 and 10)
• b = 1:2:10 (With increment 2)
• Increment could be – or a fragment
• linspace (start, end, no of points): Can divide a range into equal spaces
linspace (1, 9, 5)
Matrices
• Matrix is a two dimensional array of items
a = [2 3 4; 5 6 7] (2x3 Matrix)
• size (a) – Gives the dimensions of a Matrix
2 3 4
5 6 7
Concatenating Matrices
• A = [10 20] b = [30 40] c = [50; 60]
• D = [a b]
• E = [a; b]
• F = [e c]
• Create a matrix with zeroszeros (rows, columns)zeros(1, 10)
• Creates a matrix with 1sones (rows, columns)ones (2, 3)
• Creates a matrix with random numbers(uniformly distributed 0-1)
rand (2, 3)
Element by Element Operations
• Use . (dot) with all the Operators (+, -, /, *, ^ - Exponentiation)
a = [2 5; 4 1] b = [5 10; 3 2]
a.^2 => [4 25; 16 1]
a.*b => [10 50; 12 2]
Matrix Operations
• A matrix can be multiply by any scalar (c)A 3A
4 6 => 3*A => 12 1810 20 30 60
• If A and B have the same dimensions A+B and A-B are valid
A B A-B4 6 - 2 4 => 2 210 20 6 8 4 12
• Multiplication of matrices A with dimensions nxm and B with dimensions mxlwill produce A*B with dimensions nxl
A2x3 * B3x1 => AB2x1
2 4 3 10 2x10+4x5+3x2 46
5 1 2 5 5x10+1x5+2*2 59
2
Exercise
• Use clock function to find the number of hours left to the end of this month
Conditional Controls
• Relational Operatorsequal ==not equal ~=greater than or equal >=
• Logical OperatorsAnd & Or |Not ~All true all Any true any0 is false
if-else• Conditional statement will be evaluated for true
or falseif condition
command block 1else
command block 2end
• elseif can be used for more than one conditionse. g. n = 4;
if n > 3x = ‘A’
else x = ‘B’
end
for Loop
• Use for a know number of iterations• Loop variable can be sequential or can be
given as a vector
for loop variable = start: endcommand block
end
e. g.for n = 1:100
fprintf (‘n = %d\n’, n);end
while Loop
• Do not know about the number of iterations
while condition
command block
end
• Command block is executed while the condition is true
• Careful about infinite loops
switch • Execute one set among several
switch numbercase 1
command block 1case 2
command block 2|case n
command block nend
e. g. mynumber = input('Enter a number:');switch mynumber
case 1disp(‘Student');
case 2disp(‘Staff');
otherwisedisp(‘Not a valid Option)
end
User-defined Functions
• Function must have a functional declaration
function [avg, range] = stats(x)
• Function name should match MATLAB M-file name
OutputsInputs
function [s, r]=stats(x);
s = sum(x)
r = max(x) - min(x)
>> a = [2 4 1]
>> stats(a)
s =
7
r =
3
M-file (stats.m)
Command Prompt
Exercise
• Write a function to delete 0s from a vector
2D Graphs
• plot() cab be used to draw 2D graphs
plot (x, y, ‘c - *’)
Color Style Marker
plot (x, y, ‘c - -’, ‘LineWidth’, 2,
‘MarkerSize’, 10)
x = 0:0.5:20 % x values
y = x.^2+3*x-3 % y values
plot (x, y, ‘c - -’)
title(‘2D Graph’) % Add Title
xlabel(‘X’) % Add X-axis Label
ylabel(‘Y’) % Add y-axis label
grid on % Add Grids
hold on % Can draw another
plot (x, 300, ‘c . *’)
Plot Strings
figure
x = -pi:pi/40:pi
plot(x, cos(x), ‘y-o’, x, sin(x), ‘c.-’)
h1 = legend (‘cos_x’, sin_x’)
set(h1, 'Location', 'NorthWest')
text(2, 0.5, ‘cos(x)’)
3D Line Plots
time=0:0.001:4*pi;
x=sin(time);
y=cos(time);
z=time;
plot3(x,y,z,'k','LineWidth',2);
zlabel('Time');
Multiple Plots in One Figure
• Figure window can be partitioned and locate the graphs using subplot()
subplot (rows, columns, location)
subplot(2, 2, 1) subplot(2, 2, 2)
subplot(2, 2, 3) subplot(2, 2, 4)
x = -pi:pi/40:pi
subplot(1, 3, 1) % First graph
plot(x, sin(x))
title (‘sin’)
subplot(1, 3, 2) % Second graph
plot(x, cos(x))
title (‘cos’)
subplot(1, 3, 3) % Third graph
plot(x, tan(x))
title (‘tan’)
Surface Plotting
[X,Y] = meshgrid (-8:.5:8);
R = sqrt(X.^2 + Y.^2) ;
Z = sin(R)./R;
mesh (X,Y,Z,'EdgeColor','black')
surf (X,Y,Z) % Has filled colors
colormap hsv
colorbar
Contours • Contours in 2D
[c, h] = contour (X, Y, Z, 20)
Number of Contours
clabel (c, h) % Label the contours
• Filled contourscontourf (X, Y, Z, 20)
• Contours in 3Dcontour3 (X, Y, Z, 20)
File Input/Output
• Data can be entered in a Text Filex , y2 , 326 , 65
• Data can be imported to an array
a = importdata(‘myData.txt’, ‘ , ’)
Delimiter
x = a.data(:, 1) % Extract first columny = a.data(:, 2) % Extract second column
Read/Write to Excel
• Writing to an Excel File
xlswrite(‘CK’, a.data)
• Reading from an Excel File
xlsread(‘CK.xls)