Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Tariq Mahmood: Lab:1-2 Introduction To Matlab

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 54

Lab:1-2 Introduction to Matlab

Tariq Mahmood
Email: tariq_mehmood@comsats.edu.pk
Preview
What is MATLAB?
It is a numerical computing environment ;
A high-level programming language;
Matrix and vector-based methods;
It can be used for:
– Mathematics and computation
– Easy vector and matrix entering and manipulation
– Plotting of information
– Implementation of algorithms
– Interfacing with programs in other languages
– …
Introduction
Where to use MATLAB
– Math and computation
– Algorithm development
– Data acquisition
– Modeling, simulation, and prototyping
– Data analysis, exploration, and visualization
– Scientific and engineering graphics
– Application development, including graphical user interface
building
Introduction
MATLAB system:
Integrative Development Environment (IDE)
MATLAB Mathematical Function Library
– Including Bassel functions and fast Fourier Transformation
MATLAB Language
– high-level matrix/array language
– object-oriented
Graphics
– display vectors and matrices as graphs
API
– C/Fortran program can interact with MATHLAB
Introduction--Desktop
Introduction - Desktop
• Command Window • Command History
– enter variables – View statements

– run functions/M-files – Save: diary('filename')


Introduction -- Desktop
Editor/Debugger:
Enter a matrix
• Follow a few basic conventions: Separate the elements of a row with
blanks or commas. Use a semicolon, ; , to indicate the end of each
row. Surround the entire list of elements with square brackets, [ ].
• To enter a matrix, simply type in the Command Window
A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
• MATLAB displays the matrix you just entered:
A=
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
• This matrix matches the numbers.
sum, transpose, and diag
Special properties of a magic square have to do with the various ways
of summing its elements. If you take the sum along any row or
column, or along either of the two main diagonals, you will always
get the same number. Let us verify that using MATLAB. The first
statement to try is
sum(A)
MATLAB replies with
ans =
34 34 34 34
When you do not specify an output variable, MATLAB uses the variable
ans, short for answer, to store the results of a calculation.
You have computed a row vector containing the sums of the columns
of A. Sure enough, each of the columns has the same sum, the
magic sum, 34.
Transpose
The transpose operation is denoted by an apostrophe or single quote, '.
It flips a matrix about its main diagonal and it turns a row vector into
a column vector.
So
A'
produces
ans =
16 5 9 4
3 10 6 15
2 11 7 14
13 8 12 1
sum
and
sum(A')'
produces a column vector containing the row sums
ans =
34
34
34
34
Subscripts
The element in row i and column j of A is denoted by A(i,j).
For example, A(4,2) is the number in the fourth row and second
column.
For our magic square, A(4,2) is 15.
So to compute the sum of the elements in the fourth column of A, type
A(1,4) + A(2,4) + A(3,4) + A(4,4)
This produces
ans =
34
but is not the most elegant way of summing a single column.
Matrix
If you try to use the value of an element outside of the matrix, it is an
error:
t = A(4,5)
Index exceeds matrix dimensions.
On the other hand, if you store a value in an element outside of the
matrix, the size increases to accommodate the newcomer:
X = A;
X(4,5) = 17
X=
16 3 2 13 0
5 10 11 8 0
9 6 7 12 0
4 15 14 1 17
The Colon Operator
The colon, :, is one of the most important MATLAB operators.
It occurs in several different forms. The expression
1:10
is a row vector containing the integers from 1 to 10:
1 2 3 4 5 6 7 8 9 10
To obtain non-unit spacing, specify an increment. For example,
100:-7:50
is
100 93 86 79 72 65 58 51
and
0:pi/4:pi
is
0 0.7854 1.5708 2.3562 3.1416
Expressions
Like most other programming languages, MATLAB provides
mathematical expressions, but unlike most programming languages,
these expressions involve entire matrices. The building blocks of
expressions are
– Variables
– Numbers
– Operators
– Functions
See also Examples of Expressions in Help.
Variable name
MATLAB does not require any type declarations or dimension
statements. When MATLAB encounters a new variable name, it
automatically creates the variable and allocates the appropriate
amount of storage. If the variable already exists, MATLAB changes
its contents and, if necessary, allocates new storage. For example,
num_students = 25
creates a 1-by-1 matrix named num_students and stores the value 25
in its single element. To view the matrix assigned to any variable,
simply enter the variable name.
Variable names consist of a letter, followed by any number of letters,
digits, or underscores. MATLAB is case sensitive; it distinguishes
between uppercase and lowercase letters A and a are not the same
variable.
Numbers
MATLAB uses conventional decimal notation, with an optional decimal
point and leading plus or minus sign, for numbers. Scientific notation
uses the letter e to specify a power-of-ten scale factor. Imaginary
numbers use either i or j as a suffix. Some examples of legal
numbers are
3 -99 0.0001
9.6397238 1.60210e-20 6.02252e23
1i -3.14159j 3e5i
All numbers are stored internally using the long format specified by the
IEEE floating-point standard. Floating-point numbers have a finite
precision of roughly 16 significant decimal digits and a finite range of
roughly 10-308 to 10+308.
Operators
Expressions use familiar + Addition
arithmetic operators and
precedence rules. - Subtraction

* Multiplication

/ Division

\ Left division (described in "Matrices


and Linear Algebra" in the MATLAB
documentation)
^ Power

' Complex conjugate transpose

() Specify evaluation order


Functions
MATLAB provides a large number of standard elementary mathematical
functions, including abs, sqrt, exp, and sin. Taking the square root or
logarithm of a negative number is not an error; the appropriate complex
result is produced automatically. MATLAB also provides many more
advanced mathematical functions, including Bessel and gamma functions.
Most of these functions accept complex arguments. For a list of the
elementary mathematical functions, type
help elfun
For a list of more advanced mathematical and matrix functions, type
help specfun
help elmat
Some of the functions, like sqrt and sin, are built in.
Built-in functions are part of the MATLAB core so they are very efficient, but
the computational details are not readily accessible. Other functions, like
gamma and sinh, are implemented in M-files.
Functions: Examples of Expressions
Here are a few examples, and the resulting values:
rho = (1+sqrt(5))/2
rho =
1.6180
a = abs(3+4i)
a=
5
z = sqrt(besselk(4/3,rho-i))
z=
0.3730+ 0.3214i
huge = exp(log(realmax))
huge =
1.7977e+308
toobig = pi*huge
toobig =
Inf
Generating Matrices
Here are some examples:
Z = zeros(2,4)
Z=
0 0 0 0
0 0 0 0

F = 5*ones(3,3)
F=
5 5 5
5 5 5
5 5 5

N = fix(10*rand(1,10))
N=
9 2 6 4 8 7 4 0 8
Mathematics that can be done using Matlab

• Matrix and Linear Algebra


• Polynomial and Interpolation
• Data analysis and Statistics
• Function
• Differential Equation
• Sparse Matrics
Vectors and Matrices
EXAMPLE:
>> a=2:3, b=[a 2*a;a/2 a]
a =
2 3
b =
2.0000 3.0000 4.0000 6.0000
1.0000 1.5000 2.0000 3.0000

>> c=[b ; b]
c =
2.0000 3.0000 4.0000 6.0000
1.0000 1.5000 2.0000 3.0000
2.0000 3.0000 4.0000 6.0000
1.0000 1.5000 2.0000 3.0000
Vectors and Matrices
>> D=c(2:3, 2:3)
D =
1.5000 2.0000
3.0000 4.0000
>> who
Your variables are:
D a b c
>> whos
Name Size Bytes Class
D 2x2 32 double array
a 1x2 16 double array
b 2x4 64 double array
c 4x4 128 double array
Grand total is 30 elements using 240 bytes
Deleting Rows and Columns
You can delete rows and columns from
a matrix using just a pair of square
brackets. Start with
A = [16.0 3.0 2.0 13.0; 5.0 A =
10.0 11.0 8.0; 9.0 6.0 7.0
12.0; 4.0 15.0 14.0 1.0 ] 16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
X = A;
Then, to delete the second column of X,
use X =
X(:,2) = []
16 2 13
This changes X to 5 11 8
9 7 12
4 14 1
Deleting Rows and Columns
If you delete a single element from a matrix, the result is not a matrix
anymore. So, expressions like
X(1,2) = []
result in an error.
However, using a single subscript deletes a single element, or sequence
of elements, and reshapes the remaining elements into a row vector.
So
A =
A(2:2:10) = []
A= 16 3 2 13
Columns 1 through 7 5 10 11 8
9 6 7 12
16 9 3 6 2 7 14 4 15 14 1
Columns 8 through 11
13 8 12 1
Linear Algebra
Informally, the terms matrix and array are often used interchangeably.
More precisely, a matrix is a two-dimensional numeric array that
represents a linear transformation. The mathematical operations
defined on matrices are the subject of linear algebra.
Consider a square : A = [2 1 1 ; 1 2 1;1 1 2]

Adding a matrix to its transpose A =


2 1 1
produces a symmetric matrix:
1 2 1
B = A + A'
1 1 2
B =
4 2 2
2 4 2
2 2 4
Linear Algebra
The multiplication symbol, *, denotes the matrix multiplication involving
inner products between rows and columns. Multiplying the transpose
of a matrix by the original matrix also produces a symmetric matrix:

C = A'*A A =
2 1 1
1 2 1
1 1 2

C =
6 5 5
5 6 5
5 5 6
Linear Algebra
The determinant of matrix A is: A =
2 1 1
d = det(A)
1 2 1
d= 4 1 1 2

The reduced row echelon form R =


of A is 1 0 0
0 1 0
R = rref(A) 0 0 1

The inverse of A is Y =
0.7500 -0.2500 -0.2500
Y = inv(A) -0.2500 0.7500 -0.2500
-0.2500 -0.2500 0.7500
M-Files:
M-files are macros of MATLAB commands that are
stored as ordinary text files with the extension "m",
that is filename.m.
An M-file can be either a function with input and output
variables or a list of commands.
M-Files:
 The following describes the use of M-files on a PC version of
MATLAB.
 MATLAB requires that the M-file must be stored either in the working
directory or in a directory that is specified in the MATLAB path list.
 For example, consider using MATLAB on a PC with a user-defined M-
file stored in a directory called "\MATLAB\MFILES";.
 Then to access that M-file, either change the working directory by
typing cd\matlab\mfiles from within the MATLAB command window or
by adding the directory to the path.
 Permanent addition to the path is accomplished by editing the
\MATLAB\matlabrc.m file.
 Temporary modification to the path is accomplished by typing
path(path,'\matlab\mfiles') from within MATLAB.
Programming in MATLAB (1)

If Statement a = 3;

Syntax: b = 5;
if a < b
if expression
statements; a = a + 1;
end b = b - 1;
end
Programming in MATLAB (2)

If-else Statement(1) a=5

Syntax: b=3
if expression if a < b
statements1 a=a+1
else
statements2 b=b-1
end
else
a=a-1
b=b+1
end
Programming in MATLAB (5)

while loop % Use of While loop

Syntax: a = 1

while expression b = 5
while a <= b
statements
end a = a + 1
end
Programming in MATLAB (6)

for loop % Use of for-loop


Syntax: for j=1:10
b(j) = j*2
for x=initval:endval
end
statements;
end
for i=1:3:30
for x=initval:stepval:endval a(i) = i
statements end
end
Programming in MATLAB: M-File Scripts:(8)
MATLAB is a powerful programming language as well as an interactive
computational environment.
Files that contain code in the MATLAB language are called M-files.
You create M-files using a text editor, then use them as you would any
other MATLAB function or command.

There are two kinds of M-files:


Scripts, which do not accept input arguments or return output
arguments. They operate on data in the workspace.
Functions, which can accept input arguments and return output
arguments. Internal variables are local to the function.
Scripts
When you invoke a script, MATLAB simply executes the commands found in the
file.
Scripts can operate on existing data in the workspace, or they can create new data
on which to operate.
Although scripts do not return output arguments, any variables that they create
remain in the workspace, to be used in subsequent computations.
In addition, scripts can produce graphical output using functions like plot.
For example, create a file called script1.m that contains these MATLAB
commands:
% Investigate the random number
r = rand(1,70)
bar(r)
Typing the statement script1 causes MATLAB to execute the commands
Scripts
When you invoke a script, MATLAB simply executes the commands found in the
file.
Scripts can operate on existing data in the workspace, or they can create new data
on which to operate.
Although scripts do not return output arguments, any variables that they create
remain in the workspace, to be used in subsequent computations.
In addition, scripts can produce graphical output using functions like plot.
For example, create a file called script1.m that contains these MATLAB
commands:
% Investigate the random number
r = rand(1,70)
bar(r)
Typing the statement script1 causes MATLAB to execute the commands
Functions
 Functions are M-files that can accept input arguments
and return output arguments.
 The names of the M-file and of the function should be
the same.
 Functions operate on variables within their own
workspace, separate from the workspace you access at
the MATLAB command prompt.
 The first line of a function M-file starts with the keyword
function.
 It gives the function name and order of arguments.
Anonymous Functions
An anonymous function is a simple form of MATLAB function that does
not require an M-file. It consists of a single MATLAB expression and any
number of input and output arguments. You can define an anonymous
function right at the MATLAB command line, or within an M-file function
or script. This gives you a quick means of creating simple functions
without having to create M-files each time.
The statement below creates an anonymous function that finds the
square of a number. When you call this function, MATLAB assigns the
value you pass in to variable x, and then uses x in the equation x.^2:

% Investigate the anonymous function


sqr = @(x) x.^2;
See script2.m a = sqr(5)
b = sqr(10)
c = sqr(11)
d = sqr(12)
Anonymous Functions
An anonymous function is a simple form of MATLAB function that does
not require an M-file. It consists of a single MATLAB expression and any
number of input and output arguments. You can define an anonymous
function right at the MATLAB command line, or within an M-file function
or script. This gives you a quick means of creating simple functions
without having to create M-files each time.
The statement below creates an anonymous function that finds the
square of a number. When you call this function, MATLAB assigns the
value you pass in to variable x, and then uses x in the equation x.^2:

% Investigate the anonymous function


sqr = @(x) x.^2;
See script2.m a = sqr(5)
b = sqr(10)
c = sqr(11)
d = sqr(12)
Creating a M-file and function
You create M-files and function files using a text editor.
The process looks like this:

Create a function file using editor and save it as humps.m

function y = humps(x)
y = 1./((x-.3).^2 + .01) + 1./((x-.9).^2 + .04) - 6;

Now create a script m-file and save it as script3.m

x = 0:.002:1;
y = humps(x); Run this as script3.m
plot(x,y)
Specifying the Color and Size of Markers
Resulting
figure
Plotting commands
PLOT(X,Y) plots vector Y versus vector X.
TITLE('text') adds text at the top of the current plot.
XLABEL('text') adds text beside the X-axis on the current axis.
YLABEL('text') adds text beside the Y-axis on the current axis.
GRID, by itself, toggles the major grid lines of the current axes.
GTEXT('string') displays the graph window, puts up a cross-hair, and
waits for a mouse button or keyboard key to be pressed.
SUBPLOT(m,n,p), breaks the Figure window into an m-by-n matrix of small
or SUBPLOT(mnp), axes.
STEM(Y) stemDiscrete sequence or "stem" plot. STEM(Y) plots the
data sequence Y as stems from the x axis terminated with
circles for the data value.
SEMILOGX(...) is the same as PLOT(...), except a logarithmic (base 10)
scale is used for the X-axis.
SEMILOGY(...) is the same as PLOT(...), except a logarithmic (base 10)
scale is used for the Y-axis..
Multiple Graphs
Two ways to make multiple plots on a single graph are illustrated here.
Another way is with the hold command. The command hold freezes the
current graphics screen so that subsequent plots are superimposed on
it. Entering hold again releases the "hold". The commands hold on and
hold off are also available.
One can override the default line types and point types. For example,

% prog3.m
t = 0: 0.01: 2*pi;
y1 = sin(t);
y2 = sin(2*t);
y3 = sin(4*t);
plot(t, y1, '--', y2, ‘*', y3, '+') Graph is on
next page
Multiple Graphs
Results
Plotting colors and line styles
Colors Line Styles
y yellow . point
M magenta o circle
C cyan x x-mark
R red + plus
G green - solid
B blue * star
W white : dotted
K black -. Dashdot
-- dashed
More mark types are; square(s), diamond(d), up-triangle(v), down-
triangle(^), left-triangle(<), right-triangle(>), pentagram(p), hexagram(h)
See also help plot for more line and mark color.
Subplot
The command subplot can be used to partition the
screen so that up to four plots can be viewed
simultaneously. See help subplot.
Example for use of subplot:
% prog4.m
% Line plot of a chirp
x = 0 : 0.05 : 5;
y = sin(x.^2);
subplot(2,1,1), plot(x,y);
% Bar plot of a bell shaped curve
x = -2.9 : 0.2 : 2.9;
subplot(2,1,2), bar(x,exp(-x.*x)); Graph is on
next page
subplots

Results
Various Plotting Functions:
MATLAB supports many types of graph and surface plots:

 2 dimensions line plots (x vs. y),


 filled plots,
 bar charts,
 pie charts,
To preview some of these capabilities and
 parametric plots, others as well, enter the command
 polar plots, demos.
 contour plots,
 density plots,
 log axis plots,
 surface plots,
 parametric plots in 3 dimensions
 and spherical plots.
Line Plots of 3-D Data
The 3-D analog of the plot function is plot3. If x, y, and z are three vectors of the
same length,
plot3(x,y,z)
generates a line in 3-D through the points whose coordinates are the elements
of x, y, and z.
Then it produces a 2-D projection of that line on the screen. For example, these
statements produce a helix.

% prog5.m
t = 0:pi/50:10*pi;
plot3(sin(t),cos(t),t,'LineWidth',3)
Graph is on
axis square; grid on
next page
Line Plots of 3-D Data
Production of helix

You might also like