0% found this document useful (0 votes)
167 views

MATLAB Tutorial - 26-07-10

This document provides an overview of key topics in MATLAB: 1) MATLAB is a program for matrix computation and visualization, useful for engineers. It allows managing variables, importing/exporting data, calculations, and plotting. 2) Help is available through commands like "help" and by searching online helpdesks. 3) Variables are assigned with names starting with letters. Special variables include "ans", "pi", and "eps". 4) Vectors and matrices can represent arrays. Linear algebra operations solve systems of equations.

Uploaded by

sardingoreng
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
167 views

MATLAB Tutorial - 26-07-10

This document provides an overview of key topics in MATLAB: 1) MATLAB is a program for matrix computation and visualization, useful for engineers. It allows managing variables, importing/exporting data, calculations, and plotting. 2) Help is available through commands like "help" and by searching online helpdesks. 3) Variables are assigned with names starting with letters. Special variables include "ans", "pi", and "eps". 4) Vectors and matrices can represent arrays. Linear algebra operations solve systems of equations.

Uploaded by

sardingoreng
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Topics

 Introduction
 MATLAB Environment
MATLAB TUTORIAL  Getting Help
 Variables
 Vectors, Matrices, and Linear Algebra
 Mathematical Functions and Applications
 Plotting
 Selection Programming
 M-Files
 User Defined Functions
 Specific Topics
Reference: Engineering Problem Solving Using MATLAB, by Professor Gary Ford, University of California, Davis.

MATLAB
Introduction Environment
 What is MATLAB ? To start MATLAB:
• MATLAB is a computer program that combines computation and START  PROGRAMS 
visualization power that makes it particularly useful tool for MATLAB 6.5  MATLAB
engineers.
6.5
• MATLAB is an executive program, and a script can be made with a
list of MATLAB commands like other programming language. Or shortcut creation/activation
 MATLAB Stands for MATrix LABoratory. on the desktop
• The system was designed to make matrix computation particularly
easy.
 The MATLAB environment allows the user to:
• manage variables
• import and export data
• perform calculations
• generate plots
• develop and manage files for use with MATLAB.

Display Windows
Display Windows (con’t…)
 Graphic (Figure) Window
 Displays plots and graphs
 Created in response to graphics
commands.
 M-file editor/debugger window
 Create and edit scripts of commands called
M-files.

1
Getting Help Getting Help (con’t…)
 Google “MATLAB helpdesk”
 type one of following commands in the command  Go to the online HelpDesk provided by
window: www.mathworks.com
 help – lists all the help topic
 help topic – provides help for the specified topic
 help command – provides help for the specified command
help help – provides information on use of the help command
You can find EVERYTHING you


 helpwin – opens a separate help window for navigation


 lookfor keyword – Search all M-files for keyword need to know about MATLAB
from the online HelpDesk.

Variables Variables (con’t…)


 Variable names:  Special variables:
 Must start with a letter  ans : default variable name for the result
 May contain only letters, digits, and the underscore “_”  pi: π = 3.1415926…………
 eps: ∈ = 2.2204e-016, smallest amount by which 2 numbers can differ.
 Matlab is case sensitive, i.e. one & OnE are different variables.
 Inf or inf : ∞, infinity
 Matlab only recognizes the first 31 characters in a variable name.
 NaN or nan: not-a-number
 Assignment statement:
 Commands involving variables:
 Variable = number;
 who: lists the names of defined variables
 Variable = expression;
 whos: lists the names and sizes of defined variables
 Example: NOTE: when a semi-colon  clear: clears all varialbes, reset the default values of special
>> tutorial = 1234; variables.
”;” is placed at the end of
>> tutorial = 1234  clear name: clears the variable name
tutorial = each command, the result  clc: clears the command window
1234 is not displayed.  clf: clears the current figure and the graph window.

Vectors, Matrices and Linear Algebra Vectors


 Vectors  A row vector in MATLAB can be created by an explicit list, starting with a left bracket,
entering the values separated by spaces (or commas) and closing the vector with a right
bracket.
 Array Operations  A column vector can be created the same way, and the rows are separated by semicolons.
 Example:
 Matrices >> x = [ 0 0.25*pi 0.5*pi 0.75*pi pi ]
x=
 Solutions to Systems of Linear 0 0.7854 1.5708 2.3562 3.1416 x is a row vector.
>> y = [ 0; 0.25*pi; 0.5*pi; 0.75*pi; pi ]
Equations. y=
0
0.7854 y is a column vector.
1.5708
2.3562
3.1416

2
Vectors (con’t…) Vectors (con’t…)
 Vector Addressing – A vector element is addressed in MATLAB with an integer Some useful commands:
index enclosed in parentheses.
 Example: x = start:end create row vector x starting with start, counting by
one, ending at end
>> x(3)
x = start:increment:end create row vector x starting with start, counting by
ans = increment, ending at or before end
1.5708  3rd element of vector x create row vector x starting with start, ending at
linspace(start,end,number)
 The colon notation may be used to address a block of elements. end, having number elements

(start : increment : end) length(x) returns the length of vector x

start is the starting index, increment is the amount to add to each successive index, and end y = x’ transpose of vector x
is the ending index. A shortened format (start : end) may be used if increment is 1. dot (x, y) returns the scalar dot product of the vector x and y.
 Example:
>> x(1:3)
ans =
0 0.7854 1.5708  1st to 3rd elements of vector x

NOTE: MATLAB index starts at 1.

The format function The format function


 format short 1.3333 0.0000 >> 1.33333333333
 format short e 1.3333e+000 1.2345e-006
ans =
 format short g 1.3333 1.2345e-006
 format long 1.33333333333333 1.33333333333000
0.00000123450000
 format long e 1.333333333333333e+000 >> format short
1.234500000000000e-006 >> ans
 format long g 1.33333333333333
1.2345e-006 ans =

 format bank 1.33 0.00 1.3333


 format rat 4/3 1/810045
 format hex 3ff5555555555555 >>
3eb4b6231abfd271

Array Operations Array Operations (con’t…)


Scalar-Array Mathematics

 Element-by-Element Array-Array Mathematics.
For addition, subtraction, multiplication, and division of an array by a
scalar simply apply the operations to all elements of the array.
Operation Algebraic Form MATLAB
 Example:
>> f = [ 1 2; 3 4] Addition a+b a+b
f= Subtraction a–b a–b
1 2 Multiplication axb a .* b
3 4 Division a÷b a ./ b
>> g = 2*f – 1 Exponentiation ab a .^ b
g=
Each element in the array f is
1 3 multiplied by 2, then subtracted
 Example:
5 7 by 1. >> x = [ 1 2 3 ];
>> y = [ 4 5 6 ];
Each element in x is multiplied by
>> z = x .* y the corresponding element in y.
z=
4 10 18

3
Matrices Matrices (con’t…)
 A Matrix array is two-dimensional, having both multiple rows and multiple columns,
similar to vector arrays:  Matrix Addressing:
 it begins with [, and end with ] -- matrixname(row, column)
 spaces or commas are used to separate elements in a row -- colon may be used in place of a row or column reference to select
 semicolon or enter is used to separate rows. the entire row or column.
 Example:
•Example: recall:
A is an m x n matrix. >> f(2,3)
>> f = [ 1 2 3; 4 5 6] f=
f=
ans = 1 2 3
1 2 3
4 5 6 6 4 5 6
>> h = [ 2 4 6
1 3 5] >> h(:,1) h=
h=
ans = 2 4 6
2 4 6
1 3 5 2
1 3 5
the main diagonal
1

Generating Basic Matrices and


Load function Matrices (con’t…)
 Zeros All zeros Some useful commands:
 Ones All ones zeros(n) returns a n x n matrix of zeros
zeros(m,n) returns a m x n matrix of zeros
 Rand Uniformly distributed ones(n) returns a n x n matrix of ones
random elements ones(m,n) returns a m x n matrix of ones

 randn Normally distributed size (A) for a m x n matrix A, returns the row vector [m,n]
containing the number of rows and columns in
random elements matrix.

length(A) returns the larger of the number of rows or


columns in A.

Matrices (con’t…) Solutions to Systems of Linear Equations


more commands  Example: a system of 3 linear equations with 3 unknowns (x1, x2, x3):
Transpose B = A’ 3x1 + 2x2 – x3 = 10
-x1 + 3x2 + 2x3 = 5
Identity Matrix eye(n)  returns an n x n identity matrix
eye(m,n)  returns an m x n matrix with ones on the main x1 – x2 – x3 = -1
diagonal and zeros elsewhere. Let :
Addition and subtraction C=A+B 3 2 1  x1  10 
C=A–B A = − 1 3 2 x =  x2  b =  5 
   
Scalar Multiplication B = αA, where α is a scalar.  1 − 1 − 1
 x3  − 1
Matrix Multiplication C = A*B
Matrix Inverse B = inv(A), A must be a square matrix in this case.
rank (A)  returns the rank of the matrix A. Then, the system can be described as:
Matrix Powers B = A.^2  squares each element in the matrix
C = A * A  computes A*A, and A must be a square matrix. Ax = b
Determinant det (A), and A must be a square matrix.
A, B, C are matrices, and m, n, α are scalars.

4
Solutions to Systems of Linear Equations
(con’t…) Matrices
 Solution by Matrix Inverse:
Ax = b
 Solution by Matrix Division:
The solution to the equation
 Entering Matrices
A-1Ax = A-1b
x = A-1b
Ax = b
can be computed using left division.
 Magic
MATLAB:

>> A = [ 3 2 -1; -1 3 2; 1 -1 -1];
 MATLAB:
>> A = [ 3 2 -1; -1 3 2; 1 -1 -1];
 Sum
>> b = [ 10; 5; -1];
>> x = inv(A)*b
>> b = [ 10; 5; -1];
>> x = A\b
 Diag
x= x=
-2.0000 -2.0000  Transpose
5.0000 5.0000
-6.0000 -6.0000  Subscripts
Answer: Answer:
x1 = -2, x2 = 5, x3 = -6 x1 = -2, x2 = 5, x3 = -6  Colon Operator
NOTE:
left division: A\b  b ÷ A right division: x/y  x ÷ y

Mathematical Functions and Signal Representations, and


Applications Processing
 Signal Representations, and Processing  Sinusoidal Signals:
x(t ) = 2 cos 2πt
 Polynomials y (t ) = 2 cos[2π (t − 0.125)]
 Partial Fraction Expansion z (t ) = 2 sin 2πt

 Example:
t = linspace (-1, 1, 101);
x = 2*cos(2*pi*t);
y = 2*cos(2*pi*(t-0.125));
z = 2*sin(2*pi*t);

Polynomials Polynomials (con’t…)


 The polynomials are represented by their coefficients in MATLAB.
 Example:
 Consider the following polynomial:
>> s = linspace (-5, 5, 100);
A(s) = s3 + 3s2 + 3s + 1 >> coeff = [ 1 3 3 1];
 For s is scalar: use scalar operations >> A = polyval (coeff, s);
A = s^3 + 3*s^2 + 3*s + 1;

A(s) = s3 + 3s2 + 3s + 1 >> plot (s, A),
 For s is a vector or a matrix: use array or element by element >> xlabel ('s')
operation >> ylabel ('A(s)')
 A = s.^3 + 3*s.^2 + 3.*s + 1;
 function polyval(a,s): evaluates a polynomial with coefficients in
vector a for the values in s.

5
Polynomials (con’t…) Partial Fraction Expansion (PFE)
Operation MATLAB command Description
Addition c=a+b sum of polynomial A and B, the coefficient vectors must be the
same length.
Scalar Multiple b = 3*a multiply the polynomial A by 3 B (s ) , where B(s) and A(s) are polynomials.
H ( s) =
Polynomial c = conv(a,b) returns the coefficient vector for the polynomial resulting from A( s )
Multiplication the product of polynomial A and B.
Polynomial [q,r] = deconv(a,b) returns the long division of A and B.
Division q is the quotient polynomial coefficient, and r is the remainder H(s) can also be represented in the following form:
polynomial coefficient.
Derivatives polyder(a) returns the coefficients of the derivative of the polynomial A c1 c c
H ( s) = + 2 + ... + n
polyder(a, b) returns the coefficients of the derivative of the product of s − r1 s − r2 s − rn
polynomials A and B.
[n,d]=polyder(b,a) returns the derivative of the polynomial ratio B/A, represented
as N/D
Find Roots roots(a) returns the roots of the polynomial A in column vector form.
Find Polynomials poly(r) returns the coefficient vector of the polynomial having roots r.

NOTE: a, b, and c are polynomial coefficient vectors whose corresponding polynomials are A, B, and C

PFE(con’t…) Plotting
 For more information on 2-D plotting, type help graph2d
Example (Distinct Real Roots):  Plotting a point: the function plot () creates a
s+2 c c c >> plot ( variablename, ‘symbol’) graphics window, called a Figure
H ( s) = = 1 + 2 + 3 window, and named by default
s 3 + 4s 2 + 3s + 0 s − r1 s − r2 s − r3 “Figure No. 1”

 Example : Complex number


MATLAB: >> z = 1 + 0.5j;
>> b = [ 1 2]; NOTE: a zero is needed in the coefficient >> plot (z, ‘.’)
>> a = [ 1 4 3 0]; vector to represent the constant 0.
>> [c,r] = residue (b, a)
c=
-0.1667 c1
c2
Answer: commands for axes:
-0.5000
0.6667 c3 1/ 6 1/ 2 2 / 3 command description
r= H (s) = − − + axis ([xmin xmax ymin ymax]) Define minimum and maximum values of the axes
-3 r1 s + 3 s +1 s axis square Produce a square plot
-1 r2
0 r3 axis equal equal scaling factors for both axes
axis normal turn off axis square, equal
axis (auto) return the axis to defaults

Plotting (con’t…) Plotting (con’t…)


 Plotting Curves:  Example: (polynomial function)
 plot (x,y) – generates a linear plot of the values of x (horizontal axis) and y (vertical axis). plot the polynomial using linear/linear scale, log/linear scale, linear/log scale, & log/log
 semilogx (x,y) – generate a plot of the values of x and y using a logarithmic scale for x and a scale:
linear scale for y y = 2x2 + 7x + 9
 semilogy (x,y) – generate a plot of the values of x and y using a linear scale for x and a logarithmic
scale for y. % Generate the polynomial:
 loglog(x,y) – generate a plot of the values of x and y using logarithmic scales for both x and y x = linspace (0, 10, 100);
 Multiple Curves: y = 2*x.^2 + 7*x + 9;
 plot (x, y, w, z) – multiple curves can be plotted on the same graph by using multiple arguments in a
plot command. The variables x, y, w, and z are vectors. Two curves will be plotted: y vs. x, and z vs. w. % plotting the polynomial:
figure (1);
 legend (‘string1’, ‘string2’,…) – used to distinguish between plots on the same graph
subplot (2,2,1), plot (x,y);
 exercise: type help legend to learn more on this command.
title ('Polynomial, linear/linear scale');
 Multiple Figures: ylabel ('y'), grid;
 figure (n) – used in creation of multiple plot windows. place this command before the plot() command, subplot (2,2,2), semilogx (x,y);
and the corresponding figure will be labeled as “Figure n” title ('Polynomial, log/linear scale');
 close – closes the figure n window. ylabel ('y'), grid;
 close all – closes all the figure windows. subplot (2,2,3), semilogy (x,y);
title ('Polynomial, linear/log scale');
 Subplots: xlabel('x'), ylabel ('y'), grid;
 subplot (m, n, p) – m by n grid of windows, with p specifying the current plot as the pth subplot (2,2,4), loglog (x,y);
window title ('Polynomial, log/log scale');
xlabel('x'), ylabel ('y'), grid;

6
Plotting (con’t…) Plotting (con’t…)
 Adding new curves to the existing graph:
 Use the hold command to add lines/points to an existing plot.
 hold on – retain existing axes, add new curves to current axes. Axes are
rescaled when necessary.
 hold off – release the current figure window for new plots
 Grids and Labels:

Command Description
grid on Adds dashed grids lines at the tick marks
grid off removes grid lines (default)
grid toggles grid status (off to on, or on to off)
title (‘text’) labels top of plot with text in quotes
xlabel (‘text’) labels horizontal (x) axis with text is quotes
ylabel (‘text’) labels vertical (y) axis with text is quotes
text (x,y,’text’) Adds text in quotes to location (x,y) on the current axes, where (x,y) is in
units from the current plot.

Additional commands for plotting Selection Programming


 Flow Control
color of the point or curve Marker of the data points Plot line styles
Symbol Color Symbol Marker Symbol Line Style
 Loops
y yellow . • – solid line
m magenta o ° : dotted line
c cyan x × –. dash-dot line
r red + + –– dashed line
g green * ∗
b blue s □
w white d ◊
k black v ∇
^ ∆
h hexagram

Flow Control Flow Control (con’t…)


 Simple if statement:  The switch statement:
if logical expression switch expression
commands case test expression 1
end commands
 Example: (Nested) case test expression 2
if d <50 commands
count = count + 1; otherwise
disp(d); commands
if b>d end
b=0;
end
 Example:
end switch interval < 1
 Example: (else and elseif clauses) case 1
if temperature > 100 xinc = interval /10;
case 0
disp (‘Too hot – equipment malfunctioning.’)
elseif temperature > 90 xinc = 0.1;
disp (‘Normal operating range.’); end
elseif (‘Below desired operating range.’)
else
disp (‘Too cold – turn off equipment.’)
end

7
Loops M-Files
•Example (for loop): So far, we have executed the commands in the command window.
 for loop
for t = 1:5000
for variable = expression y(t) = sin (2*pi*t/10);
But a more practical way is to create a M-file.
commands end
 The M-file is a text file that consists a group of
end •Example (while loop):
 while loop
EPS = 1; MATLAB commands.
while ( 1+EPS) >1
while expression EPS = EPS/2;  MATLAB can open and execute the
commands end
EPS = 2*EPS
commands exactly as if they were entered at
end the MATLAB command window.
 the break statement  To run the M-files, just type the file name in
break – is used to terminate the execution of the loop. the command window. (make sure the current
working directory is set correctly)
All MATLAB commands are M-files.

Exercice
 Use the following and create an a Matlab file
% Generate the polynomial:  Add % followed by a description of the
x = linspace (0, 10, 100);
y = 2*x.^2 + 7*x + 9; program at the top
% plotting the polynomial:
figure (1);
subplot (2,2,1), plot (x,y);
title ('Polynomial, linear/linear scale');
ylabel ('y'), grid;
subplot (2,2,2), semilogx (x,y);
title ('Polynomial, log/linear scale');
ylabel ('y'), grid;
subplot (2,2,3), semilogy (x,y);
title ('Polynomial, linear/log scale');
xlabel('x'), ylabel ('y'), grid;
subplot (2,2,4), loglog (x,y);
title ('Polynomial, log/log scale');
xlabel('x'), ylabel ('y'), grid;

User-Defined Function User-Defined Function


Add the following command in the beginning of your m-file:
 Example (plot.m): 

function [output variables] = function_name (input variables);


>> help
NOTE: the function_name should
be the same as your file name to
avoid confusion.
 calling your function:
-- a user-defined function is called by the name of the m-file, not
the name given in the function definition.
-- type in the m-file name like other pre-defined commands.
 Comments:
-- The first few lines should be comments, as they will be
displayed if help is requested for the function name. the first
comment line is reference by the lookfor command.

8
Exercice
 Create the following m file called  Change the previous program as follows:
% Generate the polynomial:
x = linspace (0, 10, 100);
function [y]=poly2ord(x) NOTE: the y = poly2ord(x);

y = 2*x.^2 + 7*x + 9; function_name should % plotting the polynomial:


figure (1);
 Save the file be the same as your subplot (2,2,1), plot (x,y);
title ('Polynomial, linear/linear scale');
file name to avoid ylabel ('y'), grid;
subplot (2,2,2), semilogx (x,y);
confusion. title ('Polynomial, log/linear scale');
ylabel ('y'), grid;
subplot (2,2,3), semilogy (x,y);
 In the command window execute title ('Polynomial, linear/log scale');
xlabel('x'), ylabel ('y'), grid;

 >> poly2ord subplot (2,2,4), loglog (x,y);


title ('Polynomial, log/log scale');
xlabel('x'), ylabel ('y'), grid;
 >> poly2ord(2)

Specific Topics

 This tutorial gives you a general background


on the usage of MATLAB.
 There are thousands of MATLAB commands
for many different applications, therefore it is
impossible to cover all topics here.
 For a specific topic relating to a class, you
should consult the TA or the Instructor.

You might also like