%[text] %[text:anchor:T_BE3A7FCC] # 454MI: Introduction to MATLAB - Part 3 - Vectors & Matrices %[text] %[text:anchor:T_9A109268] # %[text] This is the third MATLAB live script of the collection ***Using MATLAB in the 454MI "******Data Driven Digital Systems***" course, devoted to introduce the MATLAB/Simulink environment and tools for solving practical problems related to the topics of the 454MI course, i.e. performance analysis of dynamic systems, parametric estimation, identification of models from data, and prediction of the evolution of dynamic systems. %[text] Use [this link](file:./usingMATLAB_454MI_Data_Driven_Digital_Systems.m) to go back to the main live script of the collection. %[text:tableOfContents]{"heading":"Table of Contents"} %[text] %% %[text] %[text:anchor:H_5019035D] ## Objectives %[text] %[text] The aim of this live script is %[text] - to understand how to create and manipulate vectors in MATLAB; %[text] - to understand how to create and manipulate matrices in MATLAB. \ %[text] %[text:anchor:H_170FFF23] ## %[text] %[text:anchor:H_55B88CC5] ## Introduction %[text] One of the great powers of mathematics and MATLAB is the ability to work with both with vectors and matrices of virtually any size (2 by 2, 10 by 10, 100 by 100000). Matrices and vectors are essential tools in many applications, describing quantities like the concentrations of different chemicals at different points in time, the prices of assets (stocks, companies, equipment, etc) at different points in time, and the temperature at different points in a body. Most often matrices are associated with a linear system which we want to solve, if possible. %% %[text] %[text:anchor:H_6BD0C76B] ## Row vectors %[text] %[text] In MATLAB you can create a row vector using square brackets \[ \]. Elements of the vector may be separated either by one or more blanks or a comma xr1 = [1 -3 4] xr2 = [1, -3, 4] %% %[text] %[text:anchor:H_9FC85244] ### Elements of Vectors %[text] To refer to elements in a vector MATLAB uses round brackets ( ) xr1(3) % the current value of the last element in xr1 xr1(3) = 0; % This assigns the value 0 to the last element of xr1. %% %[text] %[text:anchor:H_D7DE5517] ### Accessing Several Elements of a Vector %[text] The elements of a vector are indexed, starting with 1 continuing to the length of the vector. %[text] MATLAB uses vectors of integers between 1 and the length of a vector to refer to several elements of a vector at once. For example pippo = xr1([1 3]) % selecting the 1st and the 3rd element in xr1 pippo(4) = -pi; IDlist = [1 3 2 3 1]; sampleV = xr2(IDlist) % This produces a vector consisting of the elements of xr2 % corresponding to the values in IDlist and assigns the % result to a variable called sampleV. %% %[text] %[text:anchor:H_A64C8201] ### Number of Elements in a Vector %[text] The number of elements in an array (for instance a vector) can be found using the MATLAB command `numel` numel(sampleV) %[text] The length of a vector can also be found using the MATLAB command `length` length(sampleV) %% %[text] %[text:anchor:H_2B1D009D] ### The Colon Operator %[text] Frequently you want to create vectors whose elements are defined by a simple expression or to access a sequence of elements in a vector. The colon operator : provides a very convenient way of doing this. %[text] In its simplest form %[text] ```matlabCodeExample %[text] x = a:b %[text] ``` %[text] the first element in the vector $x$ is the $a\n$ value, then the next element is $a+1$, and so on, untill $b$ is reached x = -12:4 %[output:4a264c35] %[text] A slightly more general form of the colon operator is %[text] ```matlabCodeExample %[text] y = a:step:b %[text] ``` %[text] which starts at $a$, then adds `step` repeatedly, until $b$ is reached (or exceeded). In fact the value of `step` does not have to be an integer. It can even be negative. y1 = 5:2:10 %[output:83f3d2a7] y2 = 1+ 0.05*(0:10) %[output:52659381] y2(end) %[output:368f9d05] y3 = 1:0.05:1.5 % y2 and y3 have the same values y4 = 2:-0.05:1.65 %% %[text] %[text:anchor:H_34D15443] ### The linspace Command %[text] The task of creating a vector of equally (or linearly) spaced points between two limits occurs so commonly that MATLAB has a special command to do this: %[text] ```matlabCodeExample %[text] linspace(a, b, n) %[text] ``` %[text] The command creates $n$ equally spaced values between $a$ and $b$, including both $a$ and $b$. z1 = linspace(1, 2, 8) % 7 intervals - why? z2 = linspace(1, 2, 9) % 8 intervals %% %[text] %[text:anchor:H_5081396F] ### Indexing Vectors %[text] The colon operator is very helpful for indexing elements of a vector z2(1:5) % select the first 5 elements of the vector z2 y2(3:2:11) % select the 3rd, 5th, 7th, 9th and 11th elements of the vector y2 %[text] %[text] The MATLAB keyword `end` is used for several purposes. When referring to an element of a vector, it refers to the **last** element y4(end-3:end) % the last 4 element in y4 %% %[text] %[text:anchor:H_B3447DC8] ### Vector Arithmetic %[text] The standard vector operations of adding two vectors and multiplying a vector by a scalar work in MATLAB. %[text] %[text:anchor:H_7D0934EA] #### **Addition of Two Vectors** %[text] The sum of two vectors of the same size is obtained by adding corresponding elements a = [1 2 3]; b = [10 11 12]; c = a+b %[text] Try adding vectors of different sizes a1 = 1:3; b1 = 10:15; % a1+b1 %[text] %[text:anchor:H_8A35B427] #### **A Vector Times a Scalar** %[text] Multiplying a vector by a scalar produces another vector of the same size in which each element of the original vector has been multiplied by the scalar b2 = 2.5 *b1 %[text] %[text:anchor:H_D334A419] #### Adding a Scalar to a Vector %[text] A scalar may be added to any vector producing a new vector with the scalar added to **each** element of the vector b3 = b2+2.2 %% %[text] %[text:anchor:H_08766214] ### Element by Element Operations %[text] Sometimes it is very useful to apply arithmetic operations to each element of a vector (or even a matrix). These element by element operations are %[text] - .\* to multiply corresponding elements of two vectors %[text] - ./ to divide corresponding elements of two vectors %[text] - .^ to take powers of each element of a vector \ %[text] Evaluate %[text]{"align":"center"} $x\_k = k^2\\;,\\quad k=1\\,,\\;2\\,,\\;\\ldots 5$ iv = (1:5); xa = iv .* iv xb = iv .^2 % compare xa and xb %[text] Many MATLAB functions, for example `exp` and `sqrt`, work with vectors, applying the function to each element of the vector. %% %[text] %[text:anchor:H_684C3312] ## Column Vectors %[text] %[text] In MATLAB you can also create a column vector using square brackets \[ \]. However, elements of a column vector are separated either by a semicolon ; or a newline xv1 = [-1; 2; 3; 0] xv2 = [-1 2 3 0] % they have the same elements %[text] %[text:anchor:H_C90F1AAE] ### Operations with Column Vectors %[text] Elements of a column vector are accessed using round brackets ( ), exactly the same as for row vectors. %% %[text] %[text:anchor:H_4F9D68EE] ## Add Row and Column Vectors %[text] By **adding** a **row** **vector** $x$ and a **colum** **vector** $y$, you will obtain a **matrix** with each element $(i,\\,j)$ in the matrix equal to $x(i)+y(j)$ rv = [1 2 3]; cv = [4; 5; 6;7]; z = rv+cv %[output:0ea62320] %[text] Please **pay attention**: this is a handy MATLAB programming feature that does not obey a linear algebra rule. %% %[text] %[text:anchor:H_8482DC54] ## Transpose of a Vector %[text] You can convert a row vector into a column vector (and vice versa) using the transpose operator ' (an apostrophe) x_c = [1 2 3 4]' y_r = [4; 3; 2; 1]' y_r2 = transpose([4; 3; 2; 1]) %% %[text] %[text:anchor:H_795A50D4] ## Creating a Matrix %[text] %[text] In MATLAB you can create a matrix using square brackets \[ \]. Elements of a row are separated either by one or more blanks or a comma. Rows are separated by a semicolon ; or a newline. %[text] A matrix must have the same number of elements in each row and the same number of elements in each column, thus an m by n matrix is a array of m rows each of n elements or equivalently n columns each with m elements. A = [ 1 2 3 4; 5 6 7 8; 0 9 8 7] %[output:9052dbca] %% %[text] %[text:anchor:H_BC04F3E9] ### Joining Matrices %[text] You can join matrices together using square brackets \[ \], provided the sizes match. r1 = 1:3; r2 = 4:6; A = [r1 r2;-r1 2*r2;-4*r1 r2] % two row vectors, stacked on top of each other %[output:937a27c5] %% c1 = [1; 4] c2 = [2; 5] c3 = [3 6]' A = [c1 c2 c3] % The matrix A has three columns joined side by side. %% A = [1 2 3; 4 5 6] B = [10 11 12; 13 14 15] C = [A B] % As A and B have the same number of rows they may be joined side by side. C is a 2 by 6 matrix. D = [A; B] % As A and B have the same number of columns they may be stacked. D is a 4 by 3 matrix. %% %[text] %[text:anchor:H_911B32FE] ## Fast Ways to Create a Matrix %[text] MATLAB provides efficient functions to create some commonly used matrices: %[text] - The command `zeros(m,n)` creates an m by n array (matrix) of zeros. %[text] - The command `ones(m,n)` creates an m by n array (matrix) of ones. %[text] - The command `eye(n,n)` creates an n by n identity matrix. %[text] - The command `rand(m,n)` creates an m by n matrix whose elements are random numbers, uniformly distributed between 0 and 1. %[text] - The command `randn(m,n)` creates an m by n matrix whose elements are random numbers, gaussianly distributed with mean value 0 and variance 1. \ A1 = zeros(5, 3) A2 = ones(3, 5) I4 = eye(4) % compact form, equivalent to eye(4,4) R1 = rand(3,4) G1 = randn(3,3) %% %[text] %[text:anchor:H_7F2C7783] ### Size of a Matrix %[text] The dimensions (number of rows, number of columns) of a matrix can be found using the MATLAB command `size` size(I4) size(R1) %% %[text] %[text:anchor:H_5B0AA2F9] ### Elements of a Matrix - Indexing %[text] %[text] In MATLAB `A(i,j)` accesses the element $A\_{i\\,,\\,j}$ in row $i$, column $j$ of the matrix A A = zeros(3); % compact form of zeros(3, 3) A(1,3) = 3; A(3,1) = -3; A %% %[text] %[text:anchor:H_FECF5C7C] #### Rows/Columns of a Matrix %[text] You can access a row or a column of a matrix using the colon : operator to refer to all of a row or all of a column A = [1 2 3; 4 5 6; 7 8 9] r2 = A(2, :) c3 = A(:, 3) %% %[text] %[text:anchor:H_A4E5148E] #### Several Elements %[text] The colon : referring to the whole row or column, can be replaced by a vector of indices u = A(1, [1 3]) v = A([1 20], 1) %% %[text] %[text:anchor:H_19AD2B89] #### Sub-matrices %[text] If you refer to more than one row and more than one column of a matrix, then you get a sub-matrix consisting of all the elements in those rows and columns B1 = A(1:2, [1 3]) B2 = A(:, [1 3]) %% %[text] %[text:anchor:H_27C60A74] ### Matrix Arithmetic %[text] Addition and subtraction are defined for matrices of the same dimensions, and work elementwise. %[text] Multiplication of a matrix by a scalar is also defined elementwise, just as for vectors. A = [1 2 3 0; 3 4 5 -1; 5 6 7 8] B = -2*A C = 2*A + B %% %[text] %[text:anchor:H_DEE558B9] ### Matrix Multiplication %[text] In MATLAB the multiplication operator \* represents **matrix multiplication**. %[text] If A and B are not scalars, then A\*B is **only** defined if the number of columns in A is equal to the number of rows in B. A = [1 2; 3 4; 5 6] B = [5 6; 7 8] C = A*B %[text] **Remember**: matrix multiplication is **not commutative**. %% %[text] %[text:anchor:H_3E199A5B] ### Connections Between Vectors and Matrices %[text] %[text] A **row** vector with n elements is equivalent to a 1 by n matrix. %[text] A **column** vector with m elements is equivalent to a m by 1 matrix. A = [1 2 3 0; 3 4 5 -1; 5 6 7 8] b = [1;2;3;4] v = A*b r = [3 2 1] w = r*A x = rand(3,1) y = rand(3,1) p = x'*y % the dot product of x and y %% %[text] %[text:anchor:H_E53A9B3A] ### Matrix Powers %[text] Just as \* represents matrix multiplication, ^ represents the multiplication of matrices together A = [1 2; 3 4] B = A^2 C = A^3 %% %[text] %[text:anchor:H_7B09CA15] ### Element-wise Operations %[text] MATLAB provides the operators .\* for element by element multiplication, ./ for element by element division and .^ for element by element powers. This works is the same way as with vectors. A = [1 2 3; 4 5 6] B = 1./A %% %[text] %[text:anchor:H_1C0427F3] ### Matrix Manipulation Functions help elmat %[output:407fc7c6] %% %[text] %[text:anchor:H_BE2690D8] ## Summary %[text] %[text] Using this live script you have: %[text] - learned how to use square brackets \[ \] to create row or column vectors; %[text] - learned how to access elements of a vector and to find the number of elements in a vector; %[text] - learned about fast ways to create vectors using the : operator; %[text] - learned about indexing to refer to some elements of a vector; %[text] - learned about vector arithmetic, both in the usual mathematical sense and element by element operations; %[text] - learned about the transpose operator '; %[text] - learned how to use square brackets \[ \] to create matrices; %[text] - learned about fast ways to create matrices using `zeros`, `ones`, `rand` and `eye`; %[text] - learned about ways access elements, rows, columns or sub-matrices of a matrix; %[text] - learned about matrix arithmetic; %[text] - learned about elementary and specialized matrix functions. \ %[text] %[text] %[text] %[text:anchor:H_B713125A] #### Back to the Index %[text] Use [this link](file:./usingMATLAB_454MI_Data_Driven_Digital_Systems.m) to go back to the main live script of the collection. %[text] %[text] %[text:anchor:H_C8A86778] #### Back to the Previous Part: Numbers, Arithmetic Operations, Formats and Variables %[text] Use [this link](file:./Intro_MATLAB4DDDS_p2.m) to go back to the previous live script of this collection. %[text] %[text] %[text:anchor:H_A2D5477B] #### Go to the Next Part: Functions %[text] Use [this link](file:./Intro_MATLAB4DDDS_p4.mlx) to go to the next live script of the collection. %[text] %[text] %[text] %[appendix]{"version":"1.0"} %--- %[metadata:view] % data: {"layout":"inline","rightPanelPercent":40} %--- %[output:4a264c35] % data: {"dataType":"matrix","outputData":{"columns":17,"name":"x","rows":1,"type":"double","value":[["-12","-11","-10","-9","-8","-7","-6","-5","-4","-3","-2","-1","0","1","2","3","4"]]}} %--- %[output:83f3d2a7] % data: {"dataType":"matrix","outputData":{"columns":3,"name":"y1","rows":1,"type":"double","value":[["5","7","9"]]}} %--- %[output:52659381] % data: {"dataType":"matrix","outputData":{"columns":11,"name":"y2","rows":1,"type":"double","value":[["0","0.050000000000000","0.100000000000000","0.150000000000000","0.200000000000000","0.250000000000000","0.300000000000000","0.350000000000000","0.400000000000000","0.450000000000000","0.500000000000000"]]}} %--- %[output:368f9d05] % data: {"dataType":"textualVariable","outputData":{"name":"ans","value":" 0.500000000000000"}} %--- %[output:0ea62320] % data: {"dataType":"matrix","outputData":{"columns":3,"name":"z","rows":4,"type":"double","value":[["5","6","7"],["6","7","8"],["7","8","9"],["8","9","10"]]}} %--- %[output:9052dbca] % data: {"dataType":"matrix","outputData":{"columns":4,"name":"A","rows":3,"type":"double","value":[["1","2","3","4"],["5","6","7","8"],["0","9","8","7"]]}} %--- %[output:937a27c5] % data: {"dataType":"matrix","outputData":{"columns":6,"name":"A","rows":3,"type":"double","value":[["1","2","3","4","5","6"],["-1","-2","-3","8","10","12"],["-4","-8","-12","4","5","6"]]}} %--- %[output:407fc7c6] % data: {"dataType":"text","outputData":{"text":" Elementary matrices and matrix manipulation.\n \n Elementary matrices.\n zeros<\/a> - Zeros array.\n ones<\/a> - Ones array.\n eye<\/a> - Identity matrix.\n repmat<\/a> - Replicate and tile array.\n repelem<\/a> - Replicate elements of an array.\n combinations- Generate all element combinations of arrays.\n linspace<\/a> - Linearly spaced vector.\n logspace<\/a> - Logarithmically spaced vector.\n freqspace<\/a> - Frequency spacing for frequency response.\n meshgrid<\/a> - X and Y arrays for 3-D plots.\n accumarray<\/a> - Construct an array with accumulation.\n :<\/a> - Regularly spaced vector and index into matrix.\n \n Basic array information.\n size<\/a> - Size of array.\n length<\/a> - Length of vector.\n ndims<\/a> - Number of dimensions.\n numel<\/a> - Number of elements.\n disp<\/a> - Display matrix or text.\n isempty<\/a> - True for empty array.\n isequal<\/a> - True if arrays are numerically equal.\n isequaln<\/a> - True if arrays are numerically equal, treating NaNs as equal.\n height<\/a> - Number of rows.\n width<\/a> - Number of columns.\n \n Matrix manipulation.\n cat<\/a> - Concatenate arrays.\n reshape<\/a> - Reshape array by rearranging existing elements.\n resize<\/a> - Resize data by adding or removing elements.\n paddata<\/a> - Pad data.\n trimdata<\/a> - Trim data.\n diag<\/a> - Diagonal matrices and diagonals of matrix.\n blkdiag<\/a> - Block diagonal concatenation.\n tril<\/a> - Extract lower triangular part.\n triu<\/a> - Extract upper triangular part.\n fliplr<\/a> - Flip matrix in left\/right direction.\n flipud<\/a> - Flip matrix in up\/down direction.\n flip<\/a> - Flip the order of elements.\n rot90<\/a> - Rotate matrix 90 degrees.\n :<\/a> - Regularly spaced vector and index into matrix.\n find<\/a> - Find indices of nonzero elements.\n end<\/a> - Last index.\n sub2ind<\/a> - Linear index from multiple subscripts.\n ind2sub<\/a> - Multiple subscripts from linear index.\n bsxfun<\/a> - Binary singleton expansion function.\n \n Multi-dimensional array functions.\n ndgrid<\/a> - Generate arrays for N-D functions and interpolation.\n permute<\/a> - Permute array dimensions.\n ipermute<\/a> - Inverse permute array dimensions.\n shiftdim<\/a> - Shift dimensions.\n circshift<\/a> - Shift array circularly.\n squeeze<\/a> - Remove singleton dimensions.\n \n Array utility functions.\n isscalar<\/a> - True for scalar.\n isvector<\/a> - True for vector.\n isrow<\/a> - True for row vector.\n iscolumn<\/a> - True for column vector.\n ismatrix<\/a> - True for matrix.\n \n Special variables and constants.\n eps<\/a> - Floating point relative accuracy.\n realmax<\/a> - Largest positive floating point number.\n realmin<\/a> - Smallest positive floating point number.\n intmax<\/a> - Largest positive integer value.\n intmin<\/a> - Smallest integer value.\n flintmax<\/a> - Largest consecutive integer in floating point format.\n pi<\/a> - 3.1415926535897....\n i<\/a> - Imaginary unit.\n inf<\/a> - Infinity.\n nan<\/a> - Not-a-Number.\n isnan<\/a> - True for Not-a-Number.\n isinf<\/a> - True for infinite elements.\n isfinite<\/a> - True for finite elements.\n j<\/a> - Imaginary unit.\n true<\/a> - True array.\n false<\/a> - False array.\n \n Specialized matrices.\n compan<\/a> - Companion matrix.\n gallery<\/a> - Test matrices.\n hadamard<\/a> - Hadamard matrix.\n hankel<\/a> - Hankel matrix.\n hilb<\/a> - Hilbert matrix.\n invhilb<\/a> - Inverse Hilbert matrix.\n magic<\/a> - Magic square.\n pascal<\/a> - Pascal matrix.\n rosser<\/a> - Classic symmetric eigenvalue test problem.\n toeplitz<\/a> - Toeplitz matrix.\n vander<\/a> - Vandermonde matrix.\n wilkinson<\/a> - Wilkinson's eigenvalue test matrix.\n \n Controlling multithreading setting.\n maxNumCompThreads<\/a> - Controls the maximum number of computational threads.\n\n","truncated":false}} %---