an introduction to matlab® dr m ali ahmadi-pajouh kn toosi university
TRANSCRIPT
An Introduction to
MATLAB® Dr M Ali Ahmadi-Pajouh
KN Toosi University
• MATLAB= Matrix + Laboratory• Usage :
–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 –…
Development Environment
Desktop Tools
• Command Window
Desktop Tools• Start = easy access to tools, demos, and
documentation.
Current Directory Browserfile you want to run must either be in the current directory or on the search path
Workspace Browser
Editor/DebuggerM-files are programs you write to run MATLAB functions.
Matrix
• 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
Transpose
So A'
produces ans = 16 5 9 4 3 10 6 15 2 11 7 14 13 8 12 1
A = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1
Diagonal Elementsdiag(A)
produces
ans = 16 10 7 1
A = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1
Assigning a new Value to an Element
X(4,4) = 17
X = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 17
A = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1
Storing an Element
>>t = A(4,3)
t=
14
A = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1
The Colon Operator
• 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 nonunit spacing, specify an increment. For example, 100:-7:50 is
100 93 86 79 72 65 58 51
The Colon Operator
• Subscript expressions involving colons refer to portions of a matrix.
A(1:k , j)
is the first k elements of the jth column of A• colon by itself refers to all the elements in
a row or column of a matrix .
A( : , 1)
A( 2 , :)
Some Other Good Operations
• To swap the two middle columns. A = B(:,[1 3 2 4])• To Erase an entire row or column
A(1,:)=[]• To Add a new row or column
B=[A;[1 2 1 5]]
Variable
• MATLAB does not require any type declarations or dimension statements.
• the variable already exists, MATLAB changes its contents
• MATLAB is case sensitive• To view the matrix assigned to any
variable, simply enter the variable name
Format All computations in MATLAB are done in double precision.
FORMAT may be used to switch between different output
display formats as follows:
FORMAT Default. Same as SHORT.
FORMAT SHORT Scaled fixed point format with 5 digits
FORMAT LONG Scaled fixed point format with 15 digits
FORMAT HEX Hexadecimal format.
Cell Arrays
They are multidimensional arrays whose elements are copies of other arrays.
Example:>>C = {A sum(A) prod(prod(A))}ans=C = [4x4 double] [1x4 double] [20922789888000]
If you subsequently change A, nothing happens to C
useful constants.
• Pi 3.14159265...• i Imaginary unit sqrt(-1)• j Same as i• eps Floating-point relative precision 2 -52 • realmin Smallest floating-point number, 2-1022
• realmax Largest floating-point number, 2-21023
• Inf Infinity• NaN Not-a-number
Operations+ Addition- Subtraction* Multiplication/ Division\ Left division (described in "Matrices
and Linear Algebra" in the MATLAB documentation)
^ Power‘ Complex conjugate transpose( ) Specify evaluation order
Example
[1+j 2+2*j]'
ans =
1.0000 - 1.0000i
2.0000 - 2.0000i
>>3/10
ans =
0.3000
>> 10\3
ans =
0.3000
rho = (1+sqrt(5))/2rho = 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*hugetoobig = Inf
Generating Matrices
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 = 4 9 4 4 8 5 2 6 8 0
R = randn(4,4)R = 1.0668 0.2944 -0.6918 -1.4410 0.0593 -1.3362 0.8580 0.5711 -0.0956 0.7143 1.2540 -0.3999 -0.8323 1.6236 -1.5937 0.6900
Some Useful functions
• A'• d = det(A)• X = inv(A)• e = eig(A)• poly(A)• sin(x)• sinh(x)• asin(x)
Array Operators
+ Addition
- Subtraction
.* Element-by-element multiplication
./ Element-by-element division
.\ Element-by-element left division
.^Element-by-element power
.' Unconjugated array transpose
Examplen = (0:9)';Then pows = [n n.^2 2.^n]builds a table of squares and powers of 2. pows = 0 0 1 1 1 2 2 4 4 3 9 8 4 16 16 5 25 32 6 36 64 7 49 128 8 64 256 9 81 512
>> a=[1 2 3 4]>> b=[1 2 3 4]'
>> a*bans = 30
>> b*aans = 1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16
>> a.*b'ans = 1 4 9 16
B = 7.5 -5.5 -6.5 4.5 -3.5 1.5 2.5 -0.5 0.5 -2.5 -1.5 3.5 -4.5 6.5 5.5 -7.5
>>B(1:2,2:3) = 0
B = 7.5 0 0 4.5 -3.5 0 0 -0.5 0.5 -2.5 -1.5 3.5 -4.5 6.5 5.5 -7.5
Geraphics
PLOT:x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)
Multiple Data Sets in One Graph
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3)
Colors'c‘= cyan
'm‘=magenta
'y‘= yellow
'r‘= red
'g‘= green
'b‘= blue
'w‘= white
'k‘=black
plot(x,y,'ks')
0 1 2 3 4 5 6 7-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
plot(x,y,'k>')
plot(x,y,'r:+')
0 1 2 3 4 5 6 7-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
This example plots the data twice using a different number of points
for the dotted line and marker plots.
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:',x2,sin(x2),'r+')
0 1 2 3 4 5 6 7-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Complex Data
• When the arguments to plot are complex, the imaginary part is ignored
• For the special case of giving the plot a single complex argument, the command is a shortcut for a plot of the real part versus the imaginary part. Therefore, plot(Z) where Z is a complex vector or matrix, is equivalent to plot(real(Z),imag(Z))
Adding Plots to an Existing Graph
• hold on• Example:
[x,y,z] = peaks;
contour(x,y,z,20,'k')
hold on
pcolor(x,y,z)
shading interp
hold off
Multiple Plots in One Figure
• subplot(m,n,p)• Example:
t = 0:pi/10:2*pi;[X,Y,Z] = cylinder(4*cos(t));subplot(2,2,1); mesh(X)subplot(2,2,2); mesh(Y)subplot(2,2,3); mesh(Z)subplot(2,2,4); mesh(X,Y,Z)
Setting Axis
• axis([xmin xmax ymin ymax zmin zmax])• axis auto
• axis on• axis off
• grid on• grid off
Example
• t = -pi:pi/100:pi;• y = sin(t);• plot(t,y)• axis([-pi pi -1 1])• xlabel('-\pi \leq {\itt} \leq \pi')• ylabel('sin(t)')• title('Graph of the sine function')• text(1,-1/3,'{\itNote the odd symmetry.}')
Mesh and Surface Plots
• Mesh (x,y,z)
produces wireframe surfaces that color only the lines connecting the defining points.
• surf (x,y,z)
displays both the connecting lines and the faces of the surface in color.
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
mesh(X,Y,Z,'EdgeColor','black')
transparency
• hidden off
Surf Example
surf(X,Y,Z)colormap hsvcolorbar
Viewview(az,el) view([az,el])
Surface Plots with Lighting
• surf(X,Y,Z,'FaceColor','red','EdgeColor','none');• camlight left; lighting phong• view(-15,65)
Flow Control
if rem(n,2) ~= 0
…………….
elseif rem(n,4) ~= 0
………………
else
……………….
end
Important!
• when A and B are matrices, A == B does not test if they are equal, it tests where they are equal; the result is another matrix of 0's and 1's showing element-by-element equality.
• Solution:
if isequal(A,B), ...
Some Other Helpful Functions• Isequal(A,B,…):
Determine if arrays are numerically equal• Isempty(A):
Determine if item is an empty array• isequalwithequalnans(A,B,...):
Determine if arrays are numerically equal, treating NaNs as equal
• ismember(A,S):Detect members of a specific set
• isnumeric(A):Returns logical true (1) if A is a numeric array
and logical false (0) otherwise.
Some Other Helpful Functions• isprime(A):
returns an array the same size as A containing logical true (1) for the elements of A which are prime.
• isreal(A):
returns logical false (0) if any element of array A has an imaginary component, even if the value of that component is 0.
• ischar(A):
ischar(A) returns logical true (1) if A is a character array and logical false (0) otherwise.
• all(A):
If A is a vector, all(A) returns logical true (1) if all of the elements are nonzero, and returns logical false (0) if one or more elements are zero.
If A is a matrix, all(A) treats the columns of A as vectors, returning a row vector of 1s and 0s.
B = any(A):
If A is a vector, any(A) returns logical true (1) if any of the elements of A are nonzero, and returns logical false (0)
if all the elements are zero.
If A is a matrix, any(A) treats the columns of A as vectors, returning a row vector of 1s and 0s.
Example:>>A = [0.53 0.67 0.01 0.38 0.07 0.42 0.69]
B = (A < 0.5)
Ans=
0 0 1 1 1 1 0
>>all(B)
Ans= 0
>>any(B)
Ans= 1
تابع ماتريسي
Relational Operators
A < B
A > B
A <= B
A >= B
A == B
A ~= B
EXAMPLE:>>X = 5*ones(3,3);>>X >= [1 2 3; 4 5 6; 7 8 10];
ans =
1 1 1 1 1 0 0 0 0
Logical Operators
The precedence for the logical operators The truth table
The second operand is evaluated only when the result is not fully determined by the first operand.
Example
>>u = [0 0 1 1 0 1];
>>v = [0 1 1 0 0 1];
>>u | v
ans =
0 1 1 1 0 1
to avoid generating a warning when the divisor, b, is zero.
x = (b ~= 0) && (a/b > 18.5)
Logical Operation on Elements Short Circuit and
Flow Control
switch (rem(n,4)==0) + (rem(n,2)==0) case 0 ……………………. case 1 ……………………. case 2 ……………………… otherwise error('This is impossible') end
Important!
Unlike the C language switch statement, MATLAB switch does not fall through. If the first case statement is true, the other case statements do not execute. So, break statements are not required.
Flow Controlfor variable = scalar1 : step : scalar2 statement 1 ... statement nend
Example: a = zeros(k,k) % Preallocate matrixfor m = 1:k
for n = 1:k a(m,n) = 1/(m+n -1); end
end
while expression statements End
The statements are executed while the real part of expression has all nonzero elements.
Two Useful Functions for Loops
• Continue:
Passes control to the next iteration of for or while loop
• Break:
statement lets you exit early from a for or while loop.
Characters and Numbers• To define a string:
>>s = 'Hello‘characters are stored as numbers, but not in floating-point format.
• To see the characters as numbers:>>a = double(s)a =
72 101 108 108 111• To reverses the conversion:
>>s = char(a)
M-files:
1. Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace.
2. Functions, which can accept input arguments and return output arguments. Internal variables are local to the function.
Functions1. Checks to see if the name is a variable.2. Checks to see if the name is an internal function (eig,
sin) that was not overloaded.3. Checks to see if the name is a local function (local in
sense of multifunction file).4. Checks to see if the name is a function in a private
directory. 5. Locates any and all occurrences of function in method
directories and on the path. Order is of no importance. At execution, MATLAB:
6. Checks to see if the name is wired to a specific function (2, 3, & 4 above)
7. Uses precedence rules to determine which instance from 5 above to call (we may default to an internal MATLAB function). Constructors have higher precedence than anything else.
Functions
• nargin and nargout indicate how many input or output arguments, respectively, a user has supplied.
if nargout == 0 plot(x,y)else x0 = x; y0 = y;end
if nargin < 5, subdiv = 20; endif nargin < 4, angl = 10; endif nargin < 3, npts = 25; end
function [x0,y0] = myplot(fname,lims,npts,angl,subdiv)% MYPLOT Plot a function.% MYPLOT(fname,lims,npts,angl,subdiv)% The first two input arguments are% required; the other three have default values. ...if nargin < 5, subdiv = 20; endif nargin < 4, angl = 10; endif nargin < 3, npts = 25; end ...if nargout == 0 plot(x,y)else x0 = x; y0 = y;end
function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;
A review on Mathematical Functions
• Binary addition A+B plus(A,B)• Unary plus +A uplus(A) Binary• Subtraction A-B minus(A,B)• Unary minus -A uminus(A) Matrix • Multiplication A*B mtimes(A,B) Array-wise • Multiplication A.*B times(A,B) Matrix right • Division A/B mrdivide(A,B) Array-wise
right • Division A./B rdivide(A,B) Matrix left • Division A\B mldivide(A,B) Array-wise
left • Division A.\B ldivide(A,B) Matrix • Power A^B mpower(A,B) Array-wise • Power A.^B power(A,B) Complex • Transpose A‘ ctranspose(A) Matrix • Transpose A.‘ transpose(A)