Array and Matrix Operations Dr. Marco A. Arocha INGE3016-MATLAB Sep 11, 2007, Dic 7,
2 Array and Matrix Operations OPERATIONCommandsComments Array additiona + barray addition and matrix addition are identical Array subtractiona - barray subtraction and matrix subtraction are identical Array multiplication a.* belement-by-element multiplication of a and b; both arrays must be the same shape, or one of them must be a scalar Array right division a./ belement-by-element division of a by b: a(i,j)/b(i,j); both arrays must be the same shape, or one of them must be a scalar Array left divisiona.\ belement-by-element division of b by a: b(i,j)/a(i,j); both arrays must be the same shape, or one of them must be a scalar Array exponentiation a.^ be-by-e exponentiation of a to b exponents: a(i,j)^b(i,j); both arrays must be the same shape, or one of them must be a scalar Matrix Multiplication a * bthe number of columns in a must equal the number of rows in b Matrix right division a / ba * inv(b), where inv(b) is the inverse of matrix b Matrix left divisiona \ binv(a) * b, where inv(a) is the inverse of matrix a Matrix exponentiation a^bmatrix multiplication of a: a*a*a*...a, b times
Array Operations 3
Array Addition With 1D arrays: >> A=[1 3 5 ]; >> B=[2 4 6]; >> A+B ans = With 2D arrays: >> A=[1 3 5; 2 4 6] A = >> B=[ ; 2 0 9] B = >> A+B ans =
Array Multiplication >> A=[1,3,5;2,4,6] A = >> B=[2,3,4;-1,-2,-3] B = >> A.*B ans = Arrays must be of the same size
Array Division >> A=[2,4,6] A = >> B=[2,2,2] B = >> A./B% num/den Right division ans = >> A.\B% den\num Left division ans =
Array Exponentiation >> A=[2,4,6] A = >> B=[2,2,2] B = >> B.^A ans =
Special Cases: array scalar scalar array >> A+2 ans = >> A-1 ans = >> A.*5 ans = >> A./2 ans If one of the arrays is a scalar the following are valid expressions. Given: >> A=[1 2 3]; Dot is optional in the above two examples
Special Cases: array scalar scalar array >> a*2 ans = >> a.*2 ans = >> a/2 ans = >> a./2 ans = Given: a=[1 2 3] If one of the arrays is a scalar the following are valid expressions:
Special Cases >> A=[5] A = 5 >> B=[2,4,6] B = >> A.*B ans = Period is optional here
The basic data element in the MATLAB language is the array Scalar 1x1 array Vectors: 1-D arrays Column-vector: m x 1 array Row-vector: 1 x n array Multidimensional arrays m x n arrays 11
MATRIX Special case of an array: 12 Rectangular array m, rows n, columns
Square Matrix m=n 13 Square matrix of order three Z=3*A(2,3) Can reference individual elements Main diagonal: [2,5,3], i.e, A i,j where i=j
Self-dimensioning Upon initialization, MATLAB automatically allocates the correct amount of memory space for the array—no declaration needed, e.g., a=[1 2 3]; % creates a 1 x 3 array % without previously separate memory for storage 14
Self-dimensioning Upon appending one more element to an array, MATLAB automatically resizes the array to handle the new element >> a=[2 3 4]% a contains 3 elements a = >> a(4)=6% now a contains 4 elements a = >> a(5)=7% now a contains 5 elements a =
More on appending elements to an array: >> a=[1 2 3] a = >> a=[a 4] a = >> b =[a; a] b = >> c=[a; 2*b] c =
Self-dimensioning is a MATLAB key feature This MATLAB key feature is different from most programming languages, where memory allocation and array sizing takes a considerable amount of programming effort Due to this feature alone MATLAB is years ahead, such high level languages as: C-language, FORTRAN, and Visual Basic for handling Matrix Operations 17
Deleting array elements >>A=[3 5 7] A = >> A(2)=[ ] A = 3 7 >> B=[1 3 5; 2 4 6] B = >> B(2,:)=[ ] B = Deletes row-2, all column elements
Storage Mechanism for Arrays 19
Storage mechanism for arrays A = Two common ways of storage mechanism, depending on language: One row at a time: row-major order (*) One column at a time: column-major order Last one is the MATLAB way of array storage (*) C Language uses row-major order col-2 Row-2 Row-3 col-1 col-3 Row-1
Accessing Individual Elements of an Array >> A=[1 3 5; 2 4 6; 3 5 7] A = >> A(2,3)% row 2, column 3 ans = 6 21 Two indices is the usual way to access an element
Accessing elements of an Array by a single subscript >> A=[1 3 5; 2 4 6; 3 5 7] A = In memory they are arranged as: If we try to access them with only one index, e.g.: >> A(1) ans = 1 >> A(4) ans = 3 >> A(8) ans = 6 22 Recall: column- major order in memory
Accessing Elements of an Array by a Single Subscript >> A=[1 3 5; 2 4 6; 3 5 7] A = With one index & colon operator: >> A(1:2:9) ans = The index goes from 1 up to 9 in increments of 2, therefore the indices referenced are: 1, 3, 5, 7, 9, and the referenced elements are: A(1), A(3), A(5), A(7),and A(9) 23 In memory A(1)=1A(4)=3 A(7)=5 A(2)=2 A(5)=4 A(8)=6 A(3)=3 A(6)=5 A(9)=7
Example Given: A(1:1:3;1:1:3)=1 Answer-1: for ii=1:1:9 A(ii)=A(ii)+1; end 24
Example, continuation Answer-2: A(1:1:9)=A(1:1:9)+1; Answer-3: A=A(1:1:9)+1; % one index Answer-4: A=A.*2; Answer-5: A=A+1; 25
Exercise Initialize this Matrix with one index: for k =1:1:25 if mod(k,6)==1 A(k)='F';% ‘F’ elements are in indices: 1, 7, 13, 19, and 25 else A(k)='M'; end % looks beautiful but doesn’t work at all, elements are not distributed as desired % We can make reference to the elements of a 2-D array with one index % however we can’t initialize a 2-D array with only one index. 26 With one index, Referencing is OK, Initializing is not.
Accessing Elements of an Array >> A=[1 3 5; 2 4 6; 3 5 7] A = >> A(2,:) ans = (2, :) means row 2, all columns 27 A colon alone “ : “ means all the elements of that dimension
Accessing Elements of an Array >> A=[1 3 5; 2 4 6; 3 5 7] A = >> A(2:3, 1:2) ans = Means: rows from 2 to 3, and columns from 1 to 2, referenced indices are: (2,1) (2,2) (3,1) (3,2) 28 row,column
Vectorization 29
Vectorization The term “vectorization” is frequently associated with MATLAB. Means to rewrite code so that, instead of using a loop iterating over each scalar-element in an array, one takes advantage of MATLAB’s vectorization capabilities and does everything in one go. It is equivalent to change a Yaris for a Ferrari 30
Vectorization Operations executed one by one: x = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; y = zeros(size(x)); % to speed code for k = 1:1:size(x) y(k) = x(k)^3; end Vectorized code: x = [ 1 :1:10 ]; y = x.^3; 31
Vectorization Operations executed one by one: x = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; y = zeros(size(x)); for ii = 1:1:size(x) y(ii) = sin(x(ii)); end Vectorized code: x = [ 1 :1:10 ]; y = sin(x); 32
Vectorization Operations executed one by one: x = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; y = zeros(size(x)); for ii = 1:1:size(x) y(ii) = sin(x(ii))/x(ii); end Vectorized code: x = [ 1 :1:10 ]; y = sin(x)./x; 33
Vectorization Operations executed one by one: % 10 th Fibonacci number (n=10) f(1)=0; f(2)=1; for k = 3:1:n f(k) = f(k-1)+f(k-2); end WRONG Vectorization: % 10th Fibonacci number (n=10) f(1)=0; f(2)=1; k= [ 3 :1:n]; f(k) = f(k-1)+f(k-2); CAN’T 34
Vectorization Operations executed one by one: % Find factorial of 5: 5! x=[1:1:5]; p=1; for ii = 1:1:length(x) p=p*x(ii); end Wrong Vectorization: Why this code doesn’t work?: x=[1:1:5]; p(1)=1; ii=2:1:length(x); p(ii)=p(ii-1)*x(ii); 35
Vectorization-Exercise: Vectorize the following loop: for ii=1:1:n+1 tn(ii)=(to(ii-1)+to(ii+1))/2; end Note: to, the old temperatures array has been initialized previously, i.e., all elements already exist in memory Answer: ii=[1:1:n+1]; tn(ii)=(to(ii-1)+to(ii+1))/2; 36
Matrix Operations Follows linear algebra rules 37
Vector Multiplication Dot product (or inner product or scalar product) Adding the product of each pair of respective elements in A and B A must be a row vector B must be a column vector A and B must have same number of elements 38
Vector Multiplication >> A=[1,5,6] A = >> B=[-2;-4;0] B = >> A*B ans = ~ No period before the asterisk * ~ The result is a scalar ~ Compare this with array multiplication 1*(-2)+5*(-4)+6*0=-22
Matrix Multiplication Compute the dot products of each row in A with each column in B Each result becomes a row in the resulting matrix 40 AB A*B No commutative: AB≠BA
Matrix Multiplication Math Syntax: AB MATLAB Syntax: A*B(NO DOT) >> A=[1 3 5; 2 4 6] A = Sample calculation: The dot product of row one of A and column one of B: (1*-2)+(3*3)+(5*12)=67 >> A*B ans = >> B=[-2 4; 3 8; 12 -2] B =
Transpose 42 Columns become rows
Transpose MATLAB: >> A=[1,2,3;4,5,6;7,8,9] A = >> A' ans =
Determinant Transformation of a square matrix that results in a scalar Determinant of A: |A| or det A If matrix has single entry: A=[3] det A = 3 44
Determinant Example with matrix of order 2: 45 >> A=[2,3;6,4] A = >> det(A) ans = -10 MATLAB instructions
Matrix Exponentiation A must be square: A 2 =AA (matrix multiplication) A 3 =AAA MATLAB >> A=[1,2;3,4] A = >> A^2 ans = >> A^3 ans =
Operators Comparison Array Operations .* ./ .^ Matrix Operations */^*/^ 47 “+” and “-” apply to both array and matrix operations and produce same results
Operators Comparison Array Operations a=[1,2,3,4,5]; b=[5,4,3,2,1]; c=a.*b Matrix Operations a=[1,2,3,4,5]; b=[5,4,3,2,1]; c=a*b 48 Find the results of the two statements above, discuss the results
Operators Comparison Array Operations a=[1,2,3,4,5]; b=[5,4,3,2,1]’; c=a.*b Matrix Operations a=[1,2,3,4,5]; b=[5,4,3,2,1]’; c=a*b 49 Find the results of the two statements above, discuss the results
Operator Precedence You can build expressions that use any combination of arithmetic, relational, and logical operators. Precedence levels determine the order in which MATLAB evaluates an expression. Within each precedence level, operators have equal precedence and are evaluated from left to right. The precedence rules for MATLAB operators are shown in this list, ordered from highest precedence level to lowest precedence level: Parentheses () Transpose (.'), power (.^), complex conjugate transpose ('), matrix power (^) Unary plus (+), unary minus (-), logical negation (~) Multiplication (.*), right division (./), left division (.\), matrix multiplication (*), matrix right division (/), matrix left division (\) Addition (+), subtraction (-) Colon operator (:) Less than ( ), greater than or equal to (>=), equal to (==), not equal to (~=) Element-wise AND (&) Element-wise OR (|) Short-circuit AND (&&) Short-circuit OR (||) 50
Built-in Matrix Generators To cop with arrays that are used very frequently 51
Zero Matrix >> A=zeros(2) A = 0 0 >> A=zeros(2,4) A = If you specify one parameter, it returns a square matrix of order 2 If you specify 2 parameters, It returns a 2 x 4 matrix
Ones Matrix >> A=ones(3) A = >> A=ones(3,2) A = Same syntax as zeros matrix row column
Quiz n=10; ones(1,n+1) output ans = 54
Random function Generates an array of pseudorandom numbers whose elements are distributed in the range [0,1] A 2x3 matrix of random numbers: >> A=rand(2,3) A =
Identity Matrix: eye function >> eye(3) ans = >> eye(4) ans = >> eye(2,3) ans = >> eye(4,3) ans =
Useful Array Functions Better knowing their existance 57
Number of dimensions >> A=[1,2;3,4;5,6] A = >> ndims(A) ans = 2 >> B=ones(2,3,2) B(:,:,1) = B(:,:,2) = >> ndims(B) ans = 3 58
Size Returns the length of each dimensions of its argument >> A=[1,2;3,4;5,6] A = >> size(A) ans = 3 2 >> B=zeros(2,3,2,4) >> size(B) ans = >> [m,n,s,t]=size(B) m = 2 n = 3 s = 2 t = 4 59
Diagonal Returns the elements of the main diagonal Elements with equal row and column indices: (1,1), (2,2), (3,3), etc. >> A=[1 3 5; 2 4 6; 0 2 4] A = >> diag(A) ans =
Length Returns the length of the largest dimension of an array Array is 3x2: >> A=[1 3; 2 4; 0 2] A = >> length(A) ans = 3 61
Sort If a vector, the sort is in ascending order >> A=[ ] A = >> sort(A) ans = If a 2-D array, it sorts each column >> A=[4 5 6; 7 8 9; 1 2 3] A = >> sort(A) ans =
Sort >> A=[4 6 5; 8 7 9; 1 3 2] A = >> sort(A,1) ans = >> sort(A,2) ans = sort by column sort by row
Linear Systems of Equations Matrix Division Matrix Inverse 64 Two ways
65 In general a system of m equations in n unknowns can be written as: In matrix form:
66 In general a system of m equations in n unknowns can be written as: The solution to the linear system: X=A\B (matrix left division)
67 Example: A XB
X=A\B, the MATLAB solution >> A=[3 2 1; 1 2 3; ] A = >> B=[5;13;0] B = >> X=A\B X = Verify the answer: >> B= A*X B =
Matrix Inverse A is the coefficient matrix X is the solution vector m = n, A is square matrix i.e., number of rows equal the number of columns det A is non-zero, 69 IF Then A -1 exist
Inverse Inverse is a square matrix such that A -1 A= I, the identity matrix The solution of the system is given by A -1 AX = IX = X=A -1 B 70 If A is order 3, the identity matrix is also order 3:
Example A system of 2 equations and 2 unknowns: 2x 1 - x 2 = 2 x 1 + x 2 = 5 71 >> A=[2 -1; 1 1] A = >> B=[2;5] B = 2 5 >> X=inv(A)*B X =
72
Logical Arrays and Masks Section 4.3 Textbook 73
Two possible values Logical Data Type 74 True—(1) False—(0)
Logical Arrays Example: n=10; ii=[1:1:n+1]; c= mod(ii,2)==0 c= % Produces a n+1-element Logical Array named c in which elements are true (1) if ii is even and false (0) otherwise 75 Memory: ii(1)=1 ii(2)=2 ii(3)=3 … ii(11)=11 Memory: c(1)=0 c(2)=1 c(3)=0 … c(11)=0
Application-Midpoint Rule clc, clear; a = 0; b = 3; n = 100; h = (b-a)/n; x = [a:h:b]; f=exp(-x./2).* (2.*x-x.^2./2); ii=[1:1:n+1]; c = mod(ii,2)==0; t=c.*f; I=2*h*sum(t); 76 Only f’s with coefficients equal to 1 survive
Logical Arrays Example: >> n = 12; >> iia= [1:1:n+1]; >> coeff = 2*(mod(iia,3)==1) coeff = % Produces the Logical Array coeff in which their n+1 elements are true (1) if the reminder of iia divided by 3 is one and false (0) otherwise % This result could be adapted to solve Simpson 1/3 integration rule 77
Masks Logical arrays have a very important special property—they serve as a mask for arithmetic operations. A mask is an array that selects particular elements of another array for use in an operation The specified operation will be applied to the selected elements, and not to the remaining elements 78 Mascaras sirven para “enmascarar” los elementos que no queremos que entren en efecto
mask, example: >> a=[4, 5, 6] a = >> b= a > 5 b = >> a(b)=sqrt(a(b)) a = sqrt(a(b)) will take the square root of all elements for which the logical array b is true. a(b) in the LHS will affect only those elements of a for which b is true. a(b)=sqrt(a(b)) will replace in the original a array only those elements that has been square rooted. The instruction doesnot affect the rest of the elements (i.e., 4, and 5) To understand these instructions after defining a and b=a>5, run sequentially sqrt(a(b)) and a(b)=sqrt(a(b)) b is a logical array
mask, example: >> a=[1 2 3; 4 5 6; 7 8 9] a = >> b=a>5 b = >> a(b)=sqrt(a(b)) a = sqrt(a(b)) will take the square root of all elements for which the logical array b is true. a(b) in the LHS will affect only those elements of a for which b is true. a(b)=sqrt(a(b)) will replace in the original a array only those elements that has been square rooted. The instruction doesnot affect the rest of the elements (i.e., 1, 2, 3, 4, and 5) To understand these instructions after defining a, and b=a>5, run sequentially sqrt(a(b)) and a(b)=sqrt(a(b)) b is a logical array
mask, example: >> a=[1 2 3; 4 5 6; 7 8 9] a = >> b=a>5 b = >> sqrt(a(b)) ans = To understand these instructions after defining a, and b=a>5, run sequentially sqrt(a(b)) and a(b)=sqrt(a(b)) b is a logical array
With loops and if statement for ii=1:1:3 for jj=1:1:3 if a(ii,jj)>5 a(ii,jj)= sqrt(a(ii,jj)); end 82 Please don’t be confused this is not a method by logical arrays and masks. This just to show you how difficult it is without logical arrays.
masks: simpson rule example SOLUTION-1 c=ones(1,n+1); ii=[1:1:n+1]; b=mod(ii,2)==0; c(b)=4*c(b); bb=mod(ii,2)~=0; c(bb)=2*c(bb); c(1)=1; c(n+1)=1; (8 lines) SOLUTION-2 c=ones(1,n+1); ii=[1:1:n+1]; b=mod(ii,2)==0 c(b)=4*c(b); c(~b)=2*c(~b); c(1)=1; c(n+1)=1; (7 lines) 83 Produce: c=[ … 4 1]
mask: simpson rule example SOLUTION-3 c=ones(1,n+1); b=mod(1:1:n+1,2)==0; c(b)=4*c(b); bb=mod(1:1:n+1,2)~=0; c(bb)=2*c(bb); c(1)=1; c(n+1)=1; (7 lines) SOLUTION-4 c=ones(1,n+1); b=mod(1:1:n+1,2)==0 c(b)=4*c(b); c(~b)=2*c(~b); c(1)=1; c(n+1)=1; (6 lines) 84 Produce: c=[ … 4 1]
mask: simpson rule example SOLUTION-5 c=ones(1,n+1); b=mod(1:1:n+1,2)==0; c(b)=4; bb=mod(1:1:n+1,2)~=0; c(bb)=2; c(1)=1; c(n+1)=1; (7 lines) SOLUTION-6 c=ones(1,n+1); b=mod(1:1:n+1,2)==0 c(b)=4; c(~b)=2; c(1)=1; c(n+1)=1; (6 lines) 85 Produce: c=[ … 4 1]
mask: simpson rule example SOLUTION-7: c=2*ones(1,n+1); b=mod(1:1:n+1,2)==0 c(b)=4; c(1)=1; c(n+1)=1; (5 lines) 86 Produce: c=[ … 4 1] SOLUTION-8: c(3:2:n-1)=2; c(2:2:n)=4 c(1)=1; c(n+1)=1; (4 lines)
Produce: c=[ … 3 3 1] n=12; c=3*ones(1,n+1); % also c(1:1:n+1)=3 % initially all are 3 ii=[1:1:n+1]; b=mod(ii,3)==1; % also b=mod(1:1:n+1,3)==1 c(b)=(2/3)*c(b); % also c(b)=2/3 c(1)=1; c(n+1)=1; c % to print the results 87
Example 1.Create a 1000-elements array containing the values, 1, 2,…, Then take the square root of all elements whose value is greater than 5,000 using a for loop and if construct 2.Create a 1000-elements array containing the values, 1, 2,…, Then take the square root of all elements whose value are smaller than 5000 using a logical array & masks 88
Quiz-Solution Create a 10,000- elements array containing the values, 1, 2,…, 10,000. Then take the square root of all elements whose value is greater than 5,000 using a logical array x=[1:1:10000]; b=x>5000; x(b)=sqrt(x(b)); 89
Quiz Create a 100-elements array containing the values, 1, 2,…, 100. Then take the square of all elements whose values are between 50 and 75 using logical arrays Solution ii=[1:1:100]; b=ii>50 & ii<75; ii(b)=ii(b).^2; 90
Example 91
Solution % Square rooted and squared elements % Using loops and if constructs clc; clear; a=[1,3,4,7;7,8,2,3;5,2,9,6] for ii=1:1:3 for jj=1:1:4 if a(ii,jj)>5 a(ii,jj)=sqrt(a(ii,jj)) else a(ii,jj)=a(ii,jj)^2 end 92 Please don’t be confused this is not a method by logical arrays and masks. This just to show you how difficult it is without logical arrays.
Solution % Square rooted and squared elements % Using logical arrays and masks clc; clear; a=[1,3,4,7;7,8,2,3;5,2,9,6] b= a>5; a(b)=sqrt(a(b)); a(~b)=a(~b).^2; a 93