Академический Документы
Профессиональный Документы
Культура Документы
1
Dr Biswajit Nayak CIT/MECH/MATLAB-25-11-14
What is Matlab?
• MATLAB is a powerful programming language for technical computing.
– math computations,
– Algorithm development.
2
Dr Biswajit Nayak CIT/MECH/MATLAB-25-11-14
Why use Matlab?
• Advantages:
3
Dr Biswajit Nayak CIT/MECH/MATLAB-25-11-14
How to start and quit Matlab?
To start double click on MATLAB icon
To quit either write quit or exit
>>quit
>>exit MATLAB windows
MATLAB works through three basic windows.
MATLAB desktop: This is where MATLAB puts you when you launch it.
• Command window: This is the main window.
It is characterized by the MATLAB command prompt (>>)
All commands, including those for running user-written
programs, are typed in this window at the MATLAB prompt .
• Current Directory pane: this is where all your files from the current directory are
listed
• Workspace pane: This sub window lists all variables that you generate and
shows their type and size
• Command History pane: All commands typed on the MATLAB prompt in the
command window get recorded.
• Figure window: The out put of all graphics commands typed in the command window
are flushed to the graphics or figure window.
• Editor window: This is where you write, edit, create, and save your own programs in
files called M-files.
Dr Biswajit Nayak CIT/MECH/MATLAB-25-11-14 4
5
Dr Biswajit Nayak CIT/MECH/MATLAB-25-11-14
Matlab Desktop
Figure window
Editor window
Output display
The output of every command is displayed on the screen unless MATLAB is directed
otherwise.
A semicolon at the end of a command suppresses the screen output, except for
graphics and on-line help commands.
7
Dr Biswajit Nayak CIT/MECH/MATLAB-25-11-14
Output format
The user can control the format in which MATLAB displays output on screen
8
Dr Biswajit Nayak CIT/MECH/MATLAB-25-11-14
General Commands of MATLAB
12
Dr Biswajit Nayak CIT/MECH/MATLAB-25-11-14
Trigonometric Math Functions
The inverse trigonometric functions are asin(x), acos(x), atan(x) and acot(x). The
hyperbolic trigonometric functions are sinh(x), cosh(x), tanh(x) and coth(x).
Variable names:
Can be up to 63 characters long.
Can contain letters, digits, and the underscore characters.
Must begin with a letter.
MATLAB is case sensitive; it distinguishes between uppercase and lowercase letters.
For example, AA, Aa, aA and aa are the names of four different variables.
Avoid using the names of a build-in function for a variable (i.e. avoid using
: cos, sin, exp, sqrt, etc) Once a function name is used to define a variable, the
function can not be used.
The array is a fundamental form that MATLAB uses to store and manipulate data.
An array is a list of numbers arranged in rows and /or columns.
The simplest array (one dimensional) is a row or a column of numbers.
A more complex array (two dimensional) is a collection of numbers arranged in rows
and columns.
1
C 3 3×1 array; 3 elements, column vector
5
row column
5 x ln 2 x 7 sin 3 y
B
3i 5 13i
The MATLAB input command is
B = [–5*x log(2*x) + 7*sin(3*y); 3i 5 – 13i]
Addressing Arrays
A colon can be used in MATLAB to address a range of elements in a vector or a matrix.
For a matrix:
A(:,n) Refers to the elements in all the rows of column n of the matrix A.
A(n,:) Refers to the elements in all the columns of row n of the matrix A.
A(:,m:n) Refers to the elements in all the rows between columns m and n of the matrix A.
A(m:n,:) Refers to the elements in all the columns between rows m and n of the matrix A.
A(m:n,p:q) Refers to the elements in rows m through n and columns p through q of the matrix A.
Creating a vector with constant spacing by specifying the first term, the
spacing, and the last term:
In a vector with constant spacing the difference between the elements is the same.
For example, in the vector v= 2 4 6 8 10, the spacing between the elements is 2.
A vector in which the first term is m, the spacing is q, and the last term is n is created by typing:
variable_name = [m:q:n] variable_name = m:q:n
A variable that exists as a vector or a matrix can be changed by adding elements to it.
Addition of elements is done by assigning values of the additional elements, or by appending
existing variables.
Rows and/or columns can be added to an existing matrix by assigning values to the new rows or
columns.
AW=[3 6 9; 8 5 11]
AW =
3 6 9 Assign a value to the (4,5) element.
8 5 11
AW(4,5)=17 MATLAB changes the matrix size to 4×5 , and
AW = assigns zeros to the new elements.
3 6 9 0 0
8 5 11 0 0
0 0 0 0 0 Assign a value to the (3,4) element of a new
0 0 0 0 17 matrix.
BG(3,4)=15 MATLAB creates a matrix and assigns zeros to
BG = all the elements except BG(3,4).
0 0 0 0
0 0 0 0
0 0 0 15
DELETINGE LEMENTS
An element, or a range of elements, of an existing variable can be deleted by reassigning nothing
to these elements. This is done by using square brackets with nothing typed in between them.
By deleting elements a vector can be made shorter and a matrix can be made to have a smaller
size. Examples are:
Dr Biswajit Nayak CIT/MECH/MATLAB-06-12-13 25
kt=[2 8 40 65 3 55 23 15 75 80] Define a vector with 10 elements.
kt =
2 8 40 65 3 55 23 15 75 80
kt(6)=[] Eliminate the 6th element.
kt =
2 8 40 65 3 23 15 75 80 The vector now has 9 elements.
kt(3:6)=[] Eliminate elements 3 through 6.
kt =
2 8 15 75 80 The vector now has 5 elements.
Define a 3 × 5 matrix
mtr=[5 78 4 24 9; 4 0 36 60 12; 56 13 5 89 3]
mtr =
5 78 4 24 9
4 0 36 60 12
56 13 5 89 3 Eliminate all the rows of columns 2 through 4
mtr(:,2:4)=[]
mtr =
5 9
4 12
56 3
Dot Product
The dot product is a scalar computed from two vectors of the same size.
The scalar is the sum of the products of the values in corresponding positions in the vectors.
For n elements in the vectors A and B:
dot(A, B): Computes the dot product of A and B. If A and B are matrices, the dot product is a row
vector containing the dot products for the corresponding columns of A and B.
Array Multiplication
The value in position ci,j of the product C of two matrices, A and B, is the dot product of row i of the
first matrix and column of the second matrix.
GRAPHICS
MATLAB has many commands that can be used to create basic plots such as 2-D plots, 3-D plots,
surface plots etc.
Plot (x,y)
Vector Vector
The arguments x and y are each a vector (one-dimensional array).
The two vectors must have the same number of elements.
The curve is constructed of straight-line segments that connect the points whose coordinates are
defined by the elements of the vectors x and y.
Each of the vectors, of course, can have any name.
The vector that is typed first in the plot command is used for the horizontal axis, and the vector
that is typed second is used for the vertical axis
For example
x=[1 2 3 5 7 7.5 8 10];
y=[2 6.5 7 7 5.5 4 6 8];
plot(x,y)
Vector Vector (Optional) Specifiers that (Optional) Properties with values that can
define the type and color of be used to specify the line width, and a
Line Specifiers: the line and markers. marker’s size and edge, and fill colors
Line specifiers are optional and can be used to define the style and color of the line and the type of
markers (if markers are desired).
line style specifiers Within the string the specifiers can be typed in any order.
The specifiers are optional. This means that none, one,
two, or all three types can be included in a command.
Some examples:
plot(x,y) A blue solid line connects the points with no
line color specifiers markers (default).
plot(x,y,‘r’) A red solid line connects the points.
plot(x,y,‘--y’) A yellow dashed line connects the points.
plot(x,y,‘*’) The points are marked with * (no line between
the points).
plot(x,y,‘g:d’) A green dotted line connects the points that are
marker type specifiers
marked with diamond markers
Dr Biswajit Nayak and Mr Nabin Chandra Sahu CIT/MECH/MATLAB-06-12-13
38
Example
yr=[1988:1:1994];
sle=[8 12 20 22 18 24 27];
plot(yr,sle,'--r*','linewidth',2,'markersize',12)
Plot of a Function
Function y = f(x)
Example,
y 3.5 0.5 x cos(6 x) for 2 x 4
A script file that creates a plot of % the function: 3.5.^(-0.5*x).*cos(6x)
x=[-2:0.01:4]; Create vector x with the domain of the function.
y=3.5.^(-0.5*x).*cos(6*x); Create vector y with the function value at each x.
plot(x,y) Plot y as a function of x.
‘function’: The function can be typed directly as a string inside the command.
The function cannot include previously defined variables.
For example,
y x 2 4 sin( 2 x) 1 for 3 x 3
fplot('x^2+4*sin(2*x)-1',[-3 3])
• The number zero cannot be plotted on a log scale (since a log of zero is not defined).
• Negative numbers cannot be plotted on log scales (since a log of a negative number is not defined).
hist(y)
• y is a vector with the data points.
• MATLAB divides the range of the data points into 10 equally spaced subranges (bins) and then plots
the number of data points in each bin.
For example, the following data points are the daily maximum temperature (in oF) in Bhubaneswar, DC, during the
month of April 2002: 58 73 73 53 50 48 56 73 73 66 69 63 74 82 84 91 93 89 91 80 59 69 56 64 63 66 64 74 63 69
polar(theta,radius,‘line specifiers’)
For example, a plot of the function r 3 cos2 0.5 for
0≤ɵ≤2 π
z=inline('-5./(1+x.^2+y.^2)'); inline (expr) constructs an inline function object from the MATLAB
ezsurf(z,[-3,3,-3,3]) expression contained in the string expr.
ezsurfc(Z,[-3,3,-3,3])
The result can be used in other mathematical operations, in addressing arrays, and together with
When two numbers are compared, the result is 1 (logical true) if the comparison, according to the
If two scalars are compared, the result is a scalar 1 or 0. If two arrays are compared (only arrays of
the same size can be compared), the comparison is done element-by-element, and the result is a
logical array of the same size with 1s and 0s according to the outcome of the comparison at each
address.
If a scalar is compared with an array, the scalar is compared with every element of the array, and
the result is a logical array with 1s and 0s according to the outcome of the comparison of each
element.
Order of precedence:
Arithmetic, relational, and logical operators can be combined in mathematical expressions.
Precedence Operation
1 (highest) Parentheses (if nested parentheses exist, inner ones have precedence)
2 Exponentiation
3 Logical NOT (~)
4 Multiplication, division
5 Addition, subtraction
6 Relational operators (>, <, >=, <=, = =, ~=)
7 Logical AND (&)
8 (lowest) Logical OR ( | )
Examples
>> 3&7 3 AND 7.
ans =
1 3 and 7 are both true (nonzero), so the outcome is 1.
>> a=5|0 5 OR 0 (assign to variable a).
a= 1 is assigned to a since at least one number is true (nonzero).
1
>> ~25 NOT 25.
ans = The outcome is 0 since 25 is true (nonzero) and the opposite is
0 false.
Dr Biswajit Nayak and Mr Nabin Chandra Sahu CIT/MECH/MATLAB-06-12-13 52
>> t=25*((12&0)+(~0)+(0|5)) Using logical operators in a math expression.
t=
50
>> x=[9 3 0 11 0 15]; y=[2 0 13 -11 0 4]; Define two vectors x and y.
>> x&y
ans = The outcome is a vector with 1 in every position where
100101 both x and yare true (nonzero elements), and 0s otherwise.
>> z=x|y
z= The outcome is a vector with 1 in every position where
111101 either or both x and yare true (nonzero elements), and 0s
>> ~(x+y) otherwise.
ans =
000110 The outcome is a vector with 0 in every position where the
vector x+ y is true (nonzero elements), and 1 in every
position where x+ y is false (zero elements).
CONDITIONAL STATEMENTS
• A conditional statement is a command that allows MATLAB to make a decision of whether to execute
a group of commands that follow the conditional statement, or to skip these commands.
• In a conditional statement a conditional expression is stated. If the expression is true, a group of
commands that follow the statement are executed.
• If the expression is false, the computer skips the group.
Example
% This script file calculates the average of points scored in three games.
% The points from each game are assigned to the variables by using the input command.
game1=input('Enter the points scored in the first game ');
game2=input('Enter the points scored in the second game ');
game3=input('Enter the points scored in the third game ');
ave_points=(game1+game2+game3)/3
The following shows the command window when this script file is executed
Example
>> abc = [5 9 1; 7 2 4];
>> disp(abc)
5 9 1
7 2 4
>> disp('The problem has no solution.')
The problem has no solution.
Using the fprintf command to display a mix of text and numerical data:
fprintf(‘text as string %-5.2f additional text’, variable_name)
The % sign marks the Formatting elements The name of the variable
spot where the number is (define the format of the whose value is displayed
inserted within the text. number).
62
Dr Biswajit Nayak and Mr Nabin Chandra Sahu CIT/MECH/MATLAB-06-12-13
The formatting elements are
–5.2f
q = quad(function,a,b)
64
Dr Biswajit Nayak and Mr Nabin Chandra Sahu CIT/MECH/MATLAB-06-12-13
Dr Biswajit Nayak and Mr Nabin Chandra Sahu CIT/MECH/MATLAB-06-12-13
65
Plotting simple graphs
z=inline('-5./(1+x.^2+y.^2)');
ezsurf(z,[-3,3,-3,3])
print f8.jpg -djpeg
Hadamard,
hankel,
hilb,
invhilb, >Help specmat
kron,
pascal,
Toeplitz,
vander,
magic
>> logspace(0,3,4)
ans =
1 10 100 1000
Script file
Write all valid matlab command in a file and save it as
.m file (e.g., amp.m).
All the variables are global variables
Results obtained from executing the script file are left
in the workspace.
Execute it by typing the file name (e.g., >amp)
A function file is also an m-file, like script file, except that the
variables are local (name should be same as the function name)
feval=Function evaluation
>> f =inline('r^3+2*r-10');
>> Output=fzero(f,2)
Output =
1.8474
function f= bar1(r)
f =r^3+2*r-10;
>>a=fzero(@bar1,2)
a=
1.8474
sum=0.0;
sum=0.0;
for m=1:1:10
for m=1:100
sum=sum+m;
sum=sum+m;
end
end
sum=
sum=
55
5050
clc;
v=1; num=1; i=1;
while num<300
num=3^i; v=[v;num]; i=i+1;
end
>> v'
ans =
1 3 9 27 81 243 729
clc;
A=[1 2 3; 2 5 7; 7 8 3] % solve with Gaussian elimination
>>x = cr =rref ( C )
• Double integration
Integral=dblquad(‘fun’, xmin,xmax,ymin,ymax,tol)
F=inline(‘1-5*x^y’);
A=dblquad(F,0,2,-1,1)
>> syms x
>> Z=exp(x)*cos(x)*x^2;
>> P=int(Z)
P=
(1/2*x^2-1/2)*exp(x)*cos(x)-(-
1/2*x^2+x-1/2)*exp(x)*sin(x)
>> P=int(Z,0,1)
P=
1/2
81
Dr Biswajit Nayak CIT/MECH/BN/MATLAB-06-12-13
•For numerical integration
Syntax
q = quad or quadl or quad8(fun,a,b)
q = quad or quadl or quad8(fun,a,b,tol)
%------------------Example-----------
>> F = @(x)1./(x.^3-2*x-5); >> F = inline('1./(x.^3-2*x-5)');
>> Q = quad(F,0,2) or >> Q = quad(F,0,2)
Q= Q=
-0.4605 -0.4605
Double integration
Syntax
q = dblquad(fun,xmin,xmax,ymin,ymax)
%------------------------ Example--------------------------
This example explains and illustrates the steps you need to solve an initial value
ODE problem:
1.Rewrite the problem as a system of first-order ODEs. By substituting