matrices week-2 functionsakademik.thk.edu.tr/~nsengil/adw2.pdf · •matlab, just like other...
TRANSCRIPT
Week-2Matrices
Functions 1
http://catlikecoding.com/unity/tutorials/rendering/part-1/
MATLAB Matrices• The basic unit with which
we work in MATLAB is thematrix.
• We solve problems bymanipulating matrices.
• Operators are the primarymeans by which wemanipulate them.
• We will learn how to useoperators to:• add, • subtract,• multiply, and • divide matrices.
2
Vector• A vector in MATLAB is simply a matrix with exactly
one column or exactly one row.
• These two types of vectors are called, respectively, a column vector and a row vector.
3
𝐱 =𝑎𝑏𝑐
𝐲 = 𝑎 𝑏 𝑐
• A scalar, which is a single number in mathematics, is treated in MATLAB, surprisingly perhaps, as a 1-by-1 matrix or array.
• To see the size of a matrix or array in MATLAB, we can use the function called size.
4
Matrices And Arrays
A =
0.0759 0.1299 0.1622 0.6020 0.45050.0540 0.5688 0.7943 0.2630 0.08380.5308 0.4694 0.3112 0.6541 0.22900.7792 0.0119 0.5285 0.6892 0.91330.9340 0.3371 0.1656 0.7482 0.1524
b =
5 5
A=rand(5)b=size(A)
Matrices And Arrays• A matrix is a two-dimensional, rectangular
arrangement of numbers, such as this 2-by-3, matrix, which has 2 rows and 3 columns:
1 2 32.3 6.1 5
• A matrix whose number of rows equals its number of columns, as for example, 3-by-3, is called asquare matrix.
4 6 −25 3 14 8 2
5
• The square brackets ( [ ] ) indicate that we are asking MATLAB to form a matrix, and they mark its beginning and its end.
• Individual elements are separated by spaces (one or more).
• A semicolon (;) marks the end of a row.
• If you want to see more of those digits printed on the screen, you can use the command format.
(Exn 1)
6
Matrices And Arrays
Sum, transpose,diagonal, colon operator• Sum command produce a column vector containing the
row sums:
• Exn 2:
• Transpose operation is denoted by an apostrophe (‘)
• Exn 3:
• The sum of the elements on the main diagonal is obtained with diag function.
• Exn 4:
7
D =
1.0000 2.0000 3.00003.4000 3.1416 -4.00002.3000 24.5000 5.5000
T =
1.00003.14165.5000
TT =
9.6416
The “Colon Operator”• The elements of the vector x = [1 4 7] are regularly
spaced: they increase regularly by 3.
• MATLAB provides a convenient way to produce this vector: x = 1:3:7, which means, "Assign x to be the vector whose elements begin with 1, increase by 3, and go no higher than 7.
Exn 5:
8
Y =
1 2 3 4 5 6 7 8 9 10
G =
0 0.7854 1.5708 2.3562 3.1416
clc;format shortY=1:10G=0:pi/4:pi
Variables, Numbers, Operators, Functions
• Variables• num_students=35
• Start with letter, max 31 characters, case sensitive
• Numbers• Decimal point 3.6
• + - sign -4.2
• Exponential 1.60210e-15
• Imaginary numbers -3.14159j or -3.14159i
9
Operators• + addition
• - subtraction
• * multiplication
• / division
• ^ power
• ‘ complex conjugate transpose
• Exn6
10
CY =
2.8076 - 8.4229i 0.6077 - 1.8232i 1.4713 - 4.4138i4.1060 -12.3180i 1.9193 - 5.7580i 1.9196 - 5.7589i3.2145 - 9.6434i 0.9866 - 2.9597i 3.3381 -10.0144i
clc;clear all;format shortY=rand(3,3)*8 %random numbers% between 0 and 8YY=Y'CY=Y*(1-3i)
Generating Matrices• zeros
• magic
• ones
• rand uniformly between 0 and 1
• randn normally distributed
• Concatenation small to bigger matrices
• Deleting rows and columns
• Exn7
11
clc;clear all;format shortY=magic(3) %magic numbers B=[Y Y+22 ;Y+11 Y-5] %concatenationBB=magic(4)X=BBX(:,2)=[ ]X(:,1)=[ ]X(1,:)=[ ]
Linear Algebra• Symmetric matrices
• A+A’
• A’*A
• d=det(A) determinant
• [V,E]=eig(A) eigenvalues and eigenvectors
• poly(A) characteristic polynomial
• inv(A) matrix inverse
• [U*S*V]=svd(A) Singular Value Decomposition
• U,V orthogonal, S diagonal
• Exn8
12
clc;clear all;format short A=rand(4)D=A+A'DD=A'*Ad=det(A)[V,E]=(eig(vpa(A)))P=poly(A)I=inv(A)[U,S,V]=svd(A)det(V)det(U)
Array Operations
• Multiplication• Matrix multiplication
• Division
• .* element by element multiplication
• ./ element by element division• Array multiplication
• .\ element by element left division
• .^ element by element power
• .’ unconjugated array transpose
• Exm9
13
clc;clear all;format shortA=rand(3)B=rand(3)AB=A*BE=A.*BBA=A/BF=A./BG=A.\BH=B./AI=A.^2J=A^2
Building Tables
• Exn10
14
clc;clear all;format shortx=(1:0.12:2)'logs=[x log10(x)]
x =
1.00001.12001.24001.36001.48001.60001.72001.84001.9600
logs =
1.0000 01.1200 0.04921.2400 0.09341.3600 0.13351.4800 0.17031.6000 0.20411.7200 0.23551.8400 0.26481.9600 0.2923
Basic Plotting• The plot function has different forms,depending on
the input arguments.
• Label the axes and add a title
• Exn11
• Multiple plots in one Figureuse Subplot(m,n,p)
• Exn 12
• By default MATLAB finds the maxima and minima and adjust axis limits.
• Exn13
• Grid on/off
15
Mesh and Surface Plots
16
mesh(X,Y,Z) creates a mesh plot, which is a three-dimensional surface that has solid edge colors and no face colors. The function plots the values in matrix Z as heights above a grid in the x-y plane defined by X and Y. The edge colors vary according to the heights specified by Z.Exn 14AnimationExn 15
Flow Control• if statement
• switch statement
• for loops
• while loops
• continue statements
• break statements
17
Flow Control
if expression
statements
elseif expression
statements
else
statements
end
Exn16
Exn 17
18
for index = valuesstatements
end
while expressionstatements
end
Operator Precedence And Associativity
• We have seen that matrices, vectors, and scalars can be operated on by +, -,*, /, \, ^, and the “dotted” versions of these operators (e.g., .*).
• Arbitrarily complicated expressions can be formed by combining more than one operation,• >> x = a*b + c;• >> y = c + a*b;• >> z = a*(b + c);
• It is clear from our experience with algebra that in the first command above, a and b are multiplied first.
• Their product is then added to c.
• The same sequence is followed for the second command, even though the plus sign precedes the multiplication sign.
• On the other hand, in the third command, because of the parentheses, b and c are added first, and their sum is then multiplied by a.
19
20
Operator Precedence And Associativity
Associativity• If more than one binary operator of the same
precedence occurs in an expression, then the precedence table is no help.
• MATLAB’s rule for the order for applying multiple operators of the same precedence is that the order is left-to-right.
• 8/4*2=(8/4)*2=4
• 2^3^4 = (2^3)^4=4096
• 2-3+4 = (2-3)+4=3
21
• A function in mathematics is any operation that produces a result that depends only on its input.
• The major distinction between mathematical and programming definitions of “function” is that a mathematical function will always produce the same output for a given input, whereas a programming function may not.
• The input to a function is given as a list of values separated by commas inside a pair of parentheses that follows the name, as in plot(x,y).
• Each such value is called an argument.
22
Functions
Functions• Functions let us break up complex problems into
smaller, more manageable parts.
• MATLAB, just like other programming languages,comes with hundreds of built-in functions.
• Still it cannot possibly contain all functions that would be useful to carry out any given programming task.
• It is, therefore, a very important characteristic of programming languages to support the creation of user-defined functions.
23
Functions• a = 9 * rand(3,4) + 1
• We call rand with 3 and 4 specifying that we need a 3-by-4 matrix.
• The function returns numbers between 0 and 1, so multiplying by 9 and adding 1 creates exactly what we want: random numbers between 1 and 10.
• Let’s create a function instead, so that we need only to remember the function’s name when we need the functionality.
• Type edit myRand in the Command Window.
• This opens a text editor with which we can enter our code:function myRanda = 9* rand(3,4) + 1end
• According to the syntax rules, a function always starts with the word function followed by the name of the function.• >> myRand
24
• The variables inside the function are not visible from the outside, so they do not appear in the Command Window workspace.
• Variables inside functions are called “local variables”.
• A local variable is accessible only by statements inside the function, and they exist only during the function call.
• Once the function finishes its execution (or returns, using computer science terminology), all local variables cease to exist.
25
Functions
Function Output• How can we get anything out of a function and into a
variable in the Command Window?
• Functions would not be very useful if they were not able to propagate their results back to the caller.
• The answer is that functions can provide results through output arguments.
• An output argument is a local variable that you designate to hold a value that is passed to the caller by the function.
function a = myRand2
a = 9* rand(3,4) + 1
26
• >> b = myRand2
• Also, we assigned the output of the function to the variable b which is created in the Command-Window workspace.
• The a in the Command Window is still undefined.
• If we want a variable a to contain the output of the function, we have to do this:• >> a = myRand2
27
Function Output
Function Input• Our little myRand function works fine, but what if you
wanted a 3-by-4 array of random numbers between 2 and 22 instead of 1 and 10?
• How about 10 and 100? • Or −10 and 10? • Writing a new function for every possible combination
is not really a good solution. • Wouldn’t it be great, if we could tell our myRand
function the lower and upper limit somehow and let it supply the correct answer?
• Fortunately, it is quite easy to do just that. • We can supply parameters to the function when we call
it. • These parameters are called “input arguments”.
28
• Let’s modify myRand, so that it works with user
• supplied lower and upper limits:function a = myRand3(low, high)
a = (high-low) * rand(3,4) + low;
• >> myRand3(10,100)
29
Function Multi-input
• Now we are ready to modify myRand to provide not just the random matrix but also the sum of its elements:
function [a, s] = myRand(low, high)
a = (high-low) * rand(3,4) + low;
s = sum(a(:));
• >> [x y] = myRand4(0,1)
30
Function Multi-output
Symbolic Math
• syms a x b c real• 𝑓 = 𝑎𝑥2 + 𝑏𝑥 + 𝑐
• Differentiation
• Integration
31
Solving Coupled Ordinary Differential Equations
32
2𝑢′′ + 5𝑢′-3u=0𝑢 0 = −4𝑢′ 0 = 9
𝒙′ = 𝐴 𝒙
𝑥1′
𝑥2′=
0 11.5 −2.5
𝑥1𝑥2
𝑢 = 𝑢(𝑡)
odeex: Solution with eigenvectors and eigen values odeex2: Solution with ODE45 Matlab solver
• The transpose of a column vector is a row vector.
• The transpose operator has the following properties:
• Exn 27:
• If A=AT , then A is a symmetric matrix, if A=-AT , then A is a skew symmetric matrix.
• Exn 28:
• A diagonal matrix is a square matrix with nonzero elements only on the main diagonal and all other elements equal to zero.
• Exn 29:
• An important special case of a diagonal matrix is the identity matrix:
•
• Exn 30:
• It has the property that IA=A and BI=B if the matrices are conformable. (a matrix is conformable if its dimensions are suitable for defining some operation)
Matrices
TTT
TTT
TT
ABAB
BABA
scalarAA
)(
])11....111([diagI
33
• An upper triangular matrix is a matrix in which all the entries below the main diagonal are zero.
• Exn 31:• A lower triangular matrix has all zeros above the main
diagonal.• Exn 32:• Two useful scalar quantities can be defined for square
matrices, the trace and the determinant. • The trace of an n x n matrix is simply the sum of the
diagonal elements:• Exn 33:• The vector operation yxT is known as the outer
product.• Exn 34:
34
Matrices
• The determinant of an nxn matrix can be computed using an expansion about any row i or any column j:
• Exn 35:
• Thus we see that a nonsingular matrix, which is a square matrix with a nonzero determinant, has an inverse.
• A-1A=AA-1=I
• (AB)-1 =B-1 A-1
• Exn 36:
35
Matrices
• The dot product, inner product,or scalar product of two vectors of equal dimension, nx1, is given by:
• Exn 37:
• If the dot product is zero, then the vectors are said to be orthogonal.
• Exn 38:
• A measure of the length of a vector is given by its Euclidean norm, which is the square root of the inner product of the vector with itself:
• Exn 39:
36
Vectors
n
i
ii
TT yxxyyxyx1
2/1
1
2
n
i
ixxxx
• A vector with norm equal to unity is said to be a unit vector.
• Any nonzero vector can be made into a unit vector by dividing it by its norm:
• This is referred to as normalizing the vector x.
• Exn 40:
• The angle θ between the vectors x and y by:
• Exn 41:
37
Vectors
x
xxunit
yx
yx cos