introduction to matlab
TRANSCRIPT
1
An Introduction to MATLAB
Santosh K Venu
2
What is MATLAB?
• MATLAB– MATrix LABoratory: MATLAB is a program for doing numerical
computation. It was originally designed for solving linear algebra type problems using matrices. It’s name is derived from MATrix LABoratory.
– MATLAB has since been expanded and now has built-in functions for solving problems requiring data analysis, signal processing, optimization, and several other types of scientific computations. It also contains functions for 2-D and 3-D graphics and animation.
3
• Stands for MATrix LABoratory• Interpreted language• Scientific programming environment• Very good tool for the manipulation of matrices• Great visualisation capabilities• Loads of built-in functions• Easy to learn and simple to use
4
MATLAB Overview
• Strengths of MATLAB
• Weaknesses of MATLAB
5
Strengths of MATLAB
• MATLAB is relatively easy to learn• MATLAB code is optimized to be relatively quick
when performing matrix operations• MATLAB may behave like a calculator or as a
programming language• MATLAB is interpreted, errors are easier to fix
6
Weaknesses of MATLAB
• MATLAB is NOT a general purpose programming language
• MATLAB is an interpreted language (making it for the most part slower than a compiled language such as C, C++)
• MATLAB is designed for scientific computation and is not suitable for some things (such as design an interface)
7
Matlab Desktop
• Command Window– type commands
• Workspace– view program variables– clear to clear
• clear all: removes all variables, globals, functions and MEX links
• clc: clear command window– double click on a variable to see it in the Array Editor
• Command History– view past commands
• Launch Pad– access help, tools, demos and documentation
8
Matlab Desktop - con’t
Workspace
Current DIrectory
Command Window History
Launch Pad
9
How to Resume Default Desktop
10
Matlab Help
• Different ways to find information
– help
– help general, help mean, sqrt...
– helpdesk - an html document with links to further information
11
Matlab Help - con’t
12
Matlab Help - con’t
13
Command window
• The MATLAB environment is command oriented somewhat like UNIX. A prompt (>>) appears on the screen and a MATLAB statement can be entered. When the <ENTER> key is pressed, the statement is executed, and another prompt appears.
• If a statement is terminated with a semicolon ( ; ), no results will be displayed. Otherwise results will appear before the next prompt.
» a=5;» b=a/2
b =
2.5000
»
14
MATLAB Special Variables
ans Default variable name for resultspi Value of inf InfinityNaN Not a number e.g. 0/0i and j i = j = square root of minus one: (-1) (imaginary number)
e.g. sqrt(-1) ans= 0 + 1.0000irealmin The smallest usable positive real numberrealmax The largest usable positive real number
Variables
• No need for types. i.e.,
• All variables are created with double precision unless specified and they are matrices.
• After these statements, the variables are 1x1 matrices with double precision
int a;double b;float c;
Example:>>x=5;>>x1=2;
Working with Matrices and Arrays
• Since Matlab makes extensive use of matrices, the best way for you to get started with MATLAB is to learn how to handle matrices.– 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, [ ].
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 135 10 11 89 6 7 124 15 14 1
• Once you have entered the matrix, it is automatically remembered in the MATLAB workspace. You can simply refer to it as A.
• Keep in mind, variable names are case-sensitive
18
Manipulating Matrices
• Access elements of a matrix>>A(1,2)ans=3• Remember Matrix(row,column)• Naming convention Matrix variables start with a capital
letter while vectors or scalar variables start with a simple letter
A =16 3 2 135 10 11 89 6 7 124 15 14 1
indices of matrix element(s)
19
MATLAB Relational Operators
• MATLAB supports six relational operators.
Less Than <Less Than or Equal <=Greater Than >Greater Than or Equal >=Equal To ==Not Equal To ~=
20
MATLAB Logical Operators
• MATLAB supports three logical operators.
not ~ % highest precedenceand & % equal precedence with oror | % equal precedence with and
21
MATLAB Matrices
• MATLAB treats all variables as matrices. For our purposes a matrix can be thought of as an array, in fact, that is how it is stored.
• Vectors are special forms of matrices and contain only one row OR one column.
• Scalars (1,1)are matrices with only one row AND one column
22
MATLAB Matrices
• A matrix with only one row AND one column is a scalar. A scalar can be created in MATLAB as follows:
» a=23
a =
23
23
MATLAB Matrices
• A matrix with only one row is called a row vector. A row vector can be created in MATLAB as follows (note the commas):
» rowvec = [12 , 14 , 63] or rowvec = [12 14 63]
rowvec =
12 14 63
24
MATLAB Matrices
• A matrix with only one column is called a column vector. A column vector can be created in MATLAB as follows (note the semicolons):
» colvec = [13 ; 45 ; -2]
colvec =
1345-2
25
MATLAB Matrices
• A matrix can be created in MATLAB as follows (note the commas AND semicolons):
» matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]
matrix =
1 2 34 5 67 8 9
26
Extracting a Sub-Matrix
• A portion of a matrix can be extracted and stored in a smaller matrix by specifying the names of both matrices, the rows and columns. The syntax is:
sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;
where r1 and r2 specify the beginning and ending rows and c1and c2 specify the beginning and ending columns to be extracted to make the new matrix.
27
MATLAB Matrices
• A column vector can be extracted from a matrix. As an example we create a matrix below:
» matrix=[1,2,3;4,5,6;7,8,9]
matrix =1 2 34 5 67 8 9
• Here we extract column 2 of the matrix and make a column vector:
» col_two=matrix( : , 2)
col_two =258
28
MATLAB Matrices
• A row vector can be extracted from a matrix. As an example we create a matrix below:
» matrix=[1,2,3;4,5,6;7,8,9]
matrix =
1 2 34 5 67 8 9
• Here we extract row 2 of the matrix and make a row vector. Note that the 2:2 specifies the second row and the 1:3 specifies which columns of the row.
» rowvec=matrix(2 : 2 , 1 : 3)
rowvec =
4 5 6
29
Matrices transpose
• a vector x = [1 2 5 1]
x =
1 2 5 1
• transpose y = x’ y =
1
2
5
1
30
Scalar - Matrix Addition
» a=3;» b=[1, 2, 3;4, 5, 6]b =
1 2 34 5 6
» c= b+a % Add a to each element of bc =
4 5 67 8 9
31
Scalar - Matrix Subtraction
» a=3;» b=[1, 2, 3;4, 5, 6]b =
1 2 34 5 6
» c = b - a %Subtract a from each element of bc =
-2 -1 01 2 3
32
Scalar - Matrix Multiplication
» a=3;» b=[1, 2, 3; 4, 5, 6]b =
1 2 34 5 6
» c = a * b % Multiply each element of b by ac =
3 6 912 15 18
33
Scalar - Matrix Division
» a=3;» b=[1, 2, 3; 4, 5, 6]b =
1 2 34 5 6
» c = b / a % Divide each element of b by ac =
0.3333 0.6667 1.00001.3333 1.6667 2.0000
34
Math & Assignment Operators
Power ^ or .^ a^b or a.^b
Multiplication * or .* a*b or a.*b
Division / or ./ a/b or a./b
- (unary) + (unary)Addition + a + bSubtraction - a - bAssignment = a = b (assign b to a)
35
Other operators
[ ] concatenation
( ) subscription
x = [ zeros(1,3) ones(1,2) ]
x =
0 0 0 1 1
x = [ 1 3 5 7 9]
x =
1 3 5 7 9
y = x(2)
y =
3
y = x(2:4)
y =
3 5 7
Introduction to Matlab Sumitha Balasuriya
36
The : operator
• VERY important operator in Matlab• Means ‘to’>> 1:10ans =
1 2 3 4 5 6 7 8 9 10>> 1:2:10ans =
1 3 5 7 9
Try the following >> x=0:pi/12:2*pi;>> y=sin(x)
• Length• Max• Mean• Median• Min• Prod• Size• Var• Sum• Det• Rank• Eig• sort/flipr 37
38
Matlab Graphics
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')
39
Multiple Graphs
t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
plot(t,y1,t,y2)
grid on
• Plotting Multiple Data Sets in One Graph– Multiple x-y pair arguments create multiple graphs with a
single call to plot.For example: x = 0:pi/100:2*pi;
y = sin(x);y2 = sin(x-.25);y3 = sin(x-.5);plot(x,y,x,y2,x,y3)
41
Multiple Plots
t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
subplot(2,2,1)
plot(t,y1)
subplot(2,2,2)
plot(t,y2)
42
Graph Functions (summary)
• plot linear plot• stem discrete plot• grid add grid lines• xlabel add X-axis label• ylabel add Y-axis label• title add graph title• subplot divide figure window • figure create new figure window• pause wait for user response
43
Some Useful MATLAB commands
• who List known variables• whos List known variables plus their size• help >> help sqrt Help on using sqrt• lookfor >> lookfor sqrt
Search for keyword sqrt in on MATLABPATH.• what >> what ('directory')
List MATLAB files in directory • clear Clear all variables from work space• clear x y Clear variables x and y from work space• clc Clear the command window
Flow Control
• if • for • while • break • ….
Control Structures
• If Statement Syntax
if (Condition_1)Matlab Commands
elseif (Condition_2)Matlab Commands
elseif (Condition_3)Matlab Commands
elseMatlab Commands
end
Some Dummy Examples
if ((a>3) & (b==5))Some Matlab Commands;
end
if (a<3)Some Matlab Commands;
elseif (b~=5) Some Matlab Commands;
end
if (a<3)Some Matlab Commands;
else Some Matlab Commands;
end
Control Structures
• For loop syntax
for i=Index_ArrayMatlab Commands
end
Some Dummy Examples
for i=1:100Some Matlab Commands;
end
for j=1:3:200Some Matlab Commands;
end
for m=13:-0.2:-21Some Matlab Commands;
end
for k=[0.1 0.3 -13 12 7 -9.3]Some Matlab Commands;
end
Control Structures
• While Loop Syntax
while (condition)Matlab Commands
end
Dummy Example
while ((a>3) & (b==5))Some Matlab Commands;
end
Classification of flow
48
%|-------------------------------------|This function classifies a flow |according to the values of the Reynolds (Re) and Mach (Ma). |Re <= 2000, laminar flow 2000 < Re <= 5000, transitional flowRe > 5000, turbulent flow Ma < 1, sub-sonic flow Ma = 1, sonic flow Ma > 1, super-sonic flow %|-------------------------------------|
Vector Function
49
Consider now a vector function f(x) = [f1(x1,x2,x3) f2(x1,x2,x3) f3(x1,x2,x3)]T, where x =[x1,x2,x3]T (The symbol []T indicates the transpose of a matrix). Specifically,f1(x1,x2,x3) = x1 cos(x2) + x2 cos(x1) + x3f2(x1,x2,x3) = x1x2 + x2x3 + x3x1f3(x1,x2,x3) = x12 + 2x1x2x3 + x32A function to evaluate the vector function f(x) is shown below.
Summation
50
%Check if m or n are matricesif length(n)>1 | length(m)>1 thenerror('sum2 - n,m must be scalar values')abortend%Calculate summation if n and m are scalarsS = 0; %initialize sumfor i = 1:n %sweep by index ifor j = 1:m %sweep by index jS = S + 1/((i+j)^2+1);endend
51
Thank U