ec247 lec1

54
Lecture 01 MATLAB Basics

description

matlab basis

Transcript of ec247 lec1

Page 1: ec247 lec1

Lecture 01

MATLAB Basics

Page 2: ec247 lec1

Today’s Lesson

• Introduction to MATLAB

• Variables and Operators

• Built-in Functions

• Vectors and Matrices

• M-files

Page 3: ec247 lec1

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

Page 4: ec247 lec1

• Interpreted language like Pascal

• Executed line by line

• No object-oriented features

• Computations, Algorithm developments,

Modelling, Simulations, Data analysis,

Explorations, Data visualisation, GUI

developments

Page 5: ec247 lec1

Command WindowCommand History

Current DirectoryCommand Prompt

Workspace

Page 6: ec247 lec1

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

Page 7: ec247 lec1

Variables and Operators

• 2 + 3

ans =5

• Result will be assigned to a variable ans

• You can reuse the results

• ans + 2

ans = 7

Page 8: ec247 lec1

• 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

Page 9: ec247 lec1

• 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)

Page 10: ec247 lec1

• 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)

Page 11: ec247 lec1

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’)

Page 12: ec247 lec1

• % 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

Page 13: ec247 lec1

Built-in Functions

• MATLAB has a library of built-in functions

• Sqrt(2), log(), log10(), cos()

• floor(), ceil(), abs(), clock, factor()

• sum(), prod(), exp(),

Page 14: ec247 lec1

Exercise

• Which of the following is the best approximation to the square root of 7

– 2709/1024

– 10583/4000

– 2024/765

Page 15: ec247 lec1

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)

Page 16: ec247 lec1

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)

Page 17: ec247 lec1

• 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)

Page 18: ec247 lec1

Matrices

• a = [2 3 4; 5 6 7] (2x3 Matrix)

• size (a) – Give the dimensions of a Matrix

2 3 4

5 6 7

Page 19: ec247 lec1

Concatenating Matrices

• A = [10 20] b = [30 40] c = [50; 60]

• D = [a b]

• E = [a; b]

• F = [e c]

Page 20: ec247 lec1

• 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)

Page 21: ec247 lec1

Element by Element Operations

• Use . (dot) with all the Operators (+, -, /, *, ^ - Exponentiation)

A = [2 5; 4 1]

a.^2 => [4 25; 16 1]

a.*b

Page 22: ec247 lec1

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

Page 23: ec247 lec1

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

Page 24: ec247 lec1

• 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)

Page 25: ec247 lec1

Matrices, Program Controls, User-defined Functions

Page 26: ec247 lec1

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)

Page 27: ec247 lec1

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)

Page 28: ec247 lec1

• 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)

Page 29: ec247 lec1

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

Page 30: ec247 lec1

Concatenating Matrices

• A = [10 20] b = [30 40] c = [50; 60]

• D = [a b]

• E = [a; b]

• F = [e c]

Page 31: ec247 lec1

• 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)

Page 32: ec247 lec1

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]

Page 33: ec247 lec1

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

Page 34: ec247 lec1

• 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

Page 35: ec247 lec1

Exercise

• Use clock function to find the number of hours left to the end of this month

Page 36: ec247 lec1

Conditional Controls

• Relational Operatorsequal ==not equal ~=greater than or equal >=

• Logical OperatorsAnd & Or |Not ~All true all Any true any0 is false

Page 37: ec247 lec1

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

Page 38: ec247 lec1

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

Page 39: ec247 lec1

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

Page 40: ec247 lec1

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

Page 41: ec247 lec1

User-defined Functions

• Function must have a functional declaration

function [avg, range] = stats(x)

• Function name should match MATLAB M-file name

OutputsInputs

Page 42: ec247 lec1

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

Page 43: ec247 lec1

Exercise

• Write a function to delete 0s from a vector

Page 44: ec247 lec1

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)

Page 45: ec247 lec1

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 . *’)

Page 46: ec247 lec1

Plot Strings

Page 47: ec247 lec1

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)’)

Page 48: ec247 lec1

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');

Page 49: ec247 lec1

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)

Page 50: ec247 lec1

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’)

Page 51: ec247 lec1

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

Page 52: ec247 lec1

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)

Page 53: ec247 lec1

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

Page 54: ec247 lec1

Read/Write to Excel

• Writing to an Excel File

xlswrite(‘CK’, a.data)

• Reading from an Excel File

xlsread(‘CK.xls)