Array and Matrix Operations Dr. Marco A. Arocha INGE3016-MATLAB Sep 11, 2007, Dic 7, 2012 1 Array and Matrix Operations OPERATION Commands Comments Array addition a+b array addition and matrix addition are identical Array subtraction a-b array subtraction and matrix subtraction are identical Array multiplication a .* b element-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 ./ b element-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 division a .\ b element-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 .^ b e-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*b the number of columns in a must equal the number of rows in b Matrix right division a/b a * inv(b), where inv(b) is the inverse of matrix b Matrix left division a\b inv(a) * b, where inv(a) is the inverse of matrix a Matrix exponentiation a^b matrix multiplication of a: a*a*a*...a, b times 2 Array Operations Assume the following arrays of length n: A [a1 a2 a3 ...a n ] B [b1 b2 b3 ...bn ] Addition of arrays of the same length is defined as: A B [a1 b1 , a2 b2 ,..., an bn ] Subtraction of arrays of the same length: A B [a1 b1 , a2 b2 ,..., an bn ] Multiplication of arrays of the same length: ‘.*’ A . * B [a1 * b1 , a2 * b2 ,..., an * bn ] Division of arrays of the same length: ‘./’ A. / B [a1 / b1, a2 / b2 ,..., an / bn ] Exponentiation of arrays of the same length ‘ .^’ A.^B=[a1^b1, a2^b2, a3^b3,…,an^bn] 3 Array Addition With 1D arrays: With 2D arrays: >> A=[1 3 5 ]; >> B=[2 4 6]; >> A+B >> A=[1 3 5; 2 4 6] A= 1 3 5 2 4 6 ans = 3 7 11 >> B=[-5 6 10; 2 0 9] B= -5 6 10 2 0 9 >> A+B ans = -4 9 15 4 4 15 4 Array Multiplication >> A=[1,3,5;2,4,6] A= 1 3 5 2 4 6 >> B=[2,3,4;-1,-2,-3] B= 2 3 4 -1 -2 -3 >> A.*B ans = 2 9 20 -2 -8 -18 Arrays must be of the same size 5 Array Division >> A=[2,4,6] A= 2 4 6 >> B=[2,2,2] B= 2 2 2 >> A./B % num/den ans = 1 2 3 >> A.\B % den\num ans = 1.0000 0.5000 0.3333 Right division Left division 6 Array Exponentiation >> A=[2,4,6] A= 2 4 6 >> B=[2,2,2] B= 2 2 2 >> B.^A ans = 4 16 64 7 Special Cases: array <operator> scalar scalar<operator> array If one of the arrays is a scalar the following are valid expressions. Given: >> A=[1 2 3]; >> A.*5 >> A+2 ans = 3 4 5 >> A-1 ans = 0 1 ans = 5 10 15 >> A./2 2 ans 0.5 1.0 1.5 8 Dot is optional in the above two examples Special Cases: array <operator> scalar scalar<operator> array Given: a=[1 2 3] If one of the arrays is a scalar the following are valid expressions: >> a*2 ans = 2 4 >> a.*2 ans = 2 4 >> a/2 6 ans = 0.5000 1.0000 1.5000 >> a./2 ans = 0.5000 1.0000 1.5000 6 9 Special Cases >> A=[5] A= 5 >> B=[2,4,6] B= 2 4 6 Period is optional here >> A.*B ans = 10 20 30 10 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: n, columns m, rows Rectangular array 12 Square Matrix • m=n Square matrix of order three 2 4 6 A 3 5 7 1 2 3 Can reference individual elements Z=3*A(2,3) Main diagonal: [2,5,3], i.e, Ai,j where i=j 13 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= 2 3 4 >> a(4)=6 a= 2 3 4 6 >> a(5)=7 a= 2 3 4 6 % a contains 3 elements % now a contains 4 elements % now a contains 5 elements 7 15 More on appending elements to an array: >> a=[1 2 3] a= 1 2 3 >> a=[a 4] a= 1 2 3 4 >> b =[a; a] b= 1 2 3 1 2 3 >> c=[a; 2*b] c= 1 2 3 2 4 6 2 4 6 4 4 4 8 8 16 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= 3 5 7 >> A(2)=[ ] A= 3 7 >> B=[1 3 5; 2 4 6] B= 1 3 5 2 4 6 >> B(2,:)=[ ] B= 1 3 5 Deletes row-2, all column elements 18 Storage Mechanism for Arrays 19 Storage mechanism for arrays Two common ways of storage mechanism, depending on language: A= 1 2 3 • One row at a time: row-major order (*) 1 3 5 2 4 6 3 5 7 3 4 5 5 6 7 Row-1 Row-2 Row-3 • One column at a time: column-major order 1 2 3 3 4 5 5 6 7 col-1 col-2 col-3 Last one is the MATLAB way of array storage 20 (*) C Language uses row-major order Accessing Individual Elements of an Array >> A=[1 3 5; 2 4 6; 3 5 7] A= 1 2 3 3 4 5 >> A(2,3) ans = 6 5 6 7 % row 2, column 3 Two indices is the usual way to access an element 21 Accessing elements of an Array by a single subscript >> A=[1 3 5; 2 4 6; 3 5 7] A= 1 2 3 3 4 5 5 6 7 In memory they are arranged as: 123345567 If we try to access them with only one index, e.g.: >> A(1) Recall: ans = column1 major >> A(4) order in ans = memory 3 >> A(8) ans = 6 22 Accessing Elements of an Array by a Single Subscript >> A=[1 3 5; 2 4 6; 3 5 7] A= 1 2 3 3 4 5 5 6 7 In memory With one index & colon operator: >> A(1:2:9) ans = 1 3 4 5 7 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) A(1)=1 A(4)=3 A(7)=5 A(2)=2 A(5)=4 A(8)=6 A(3)=3 A(6)=5 A(9)=7 23 Example Add one unit to each element in A: 1 1 𝑎= 1 1 1 1 1 1 1 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: Answer-4: • A(1:1:9)=A(1:1:9)+1; • A=A.*2; Answer-3: Answer-5: • A=A(1:1:9)+1; • % one index • A=A+1; 25 Exercise With one index, Referencing is OK, Initializing is not. A= Initialize this Matrix with one index: for k =1:1:25 if mod(k,6)==1 A(k)='F'; else A(k)='M'; end end F M M M M M F M M M M M F M M M M M F M M M M M F % ‘F’ elements are in indices: 1, 7, 13, 19, and 25 % 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 Accessing Elements of an Array >> A=[1 3 5; 2 4 6; 3 5 7] A= 1 2 3 3 4 5 5 6 7 >> A(2,:) ans = 2 4 6 (2, :) means row 2, all columns A colon alone “ : “ means all the elements of that dimension 27 Accessing Elements of an Array >> A=[1 3 5; 2 4 6; 3 5 7] row,column A= 1 2 3 >> A(2:3, 1:2) 3 4 5 5 6 7 ans = 2 4 3 5 Means: rows from 2 to 3, and columns from 1 to 2, referenced indices are: (2,1) (2,2) (3,1) (3,2) 28 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: Vectorized code: x = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; y = zeros(size(x)); % to speed code x = [ 1 :1:10 ]; y = x.^3; for k = 1:1:size(x) y(k) = x(k)^3; end 31 Vectorization Operations executed one by one: Vectorized code: x = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; y = zeros(size(x)); x = [ 1 :1:10 ]; y = sin(x); for ii = 1:1:size(x) y(ii) = sin(x(ii)); end 32 Vectorization Operations executed one by one: Vectorized code: x = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; y = zeros(size(x)); x = [ 1 :1:10 ]; y = sin(x)./x; for ii = 1:1:size(x) y(ii) = sin(x(ii))/x(ii); end 33 Vectorization Operations executed one by one: WRONG Vectorization: % 10th Fibonacci number (n=10) % 10th Fibonacci number (n=10) f(1)=0; f(2)=1; f(1)=0; f(2)=1; for k = 3:1:n f(k) = f(k-1)+f(k-2); end 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: Answer: for ii=1:1:n+1 tn(ii)=(to(ii-1)+to(ii+1))/2; end ii=[1:1:n+1]; tn(ii)=(to(ii-1)+to(ii+1))/2; Note: to, the old temperatures array has been initialized previously, i.e., all elements already exist in memory 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= 1 5 6 >> B=[-2;-4;0] B= -2 -4 0 >> A*B ans = -22 1*(-2)+5*(-4)+6*0=-22 ~ No period before the asterisk * ~ The result is a scalar ~ Compare this with array multiplication 39 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 A B A*B m AB pij aik bkj k 1 ( n x m) * ( m x p ) n x p 40 No commutative: AB≠BA Matrix Multiplication Math Syntax: AB MATLAB Syntax: A*B (NO DOT) >> A=[1 3 5; 2 4 6] A= 1 3 5 2 4 6 >> B=[-2 4; 3 8; 12 -2] B= -2 4 3 8 12 -2 >> A*B ans = 67 80 18 28 Sample calculation: The dot product of row one of A and column one of B: (1*-2)+(3*3)+(5*12)=67 41 Transpose Columns become rows 42 Transpose MATLAB: >> A=[1,2,3;4,5,6;7,8,9] 1 A 4 7 1 T A 2 3 2 3 5 6 8 9 4 7 5 8 6 9 A= 1 4 7 2 5 8 3 6 9 4 5 6 7 8 9 >> A' ans = 1 2 3 43 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: a11 a12 det a11 a22 a21 a12 a21 a22 >> A=[2,3;6,4] A= 2 3 6 4 >> det(A) ans = -10 MATLAB instructions 45 Matrix Exponentiation • A must be square: A2=AA (matrix multiplication) A3=AAA MATLAB >> A=[1,2;3,4] A= 1 2 3 4 >> A^2 ans = 7 10 15 22 >> A^3 ans = 37 54 81 118 46 Operators Comparison Array Operations .* ./ .^ Matrix Operations * / ^ “+” and “-” apply to both array and matrix operations and produce same results 47 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 Find the results of the two statements above, discuss the results 48 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 Find the results of the two statements above, discuss the results 49 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 (<), less than or equal to (<=), greater 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) If you specify one parameter, it returns a square matrix of order 2 A= 0 0 0 0 >> A=zeros(2,4) A= 0 0 0 0 0 0 0 0 If you specify 2 parameters, It returns a 2 x 4 matrix 52 Ones Matrix >> A=ones(3) A= 1 1 1 >> A=ones(3,2) column A= 1 1 1 1 1 1 1 1 1 row 1 1 1 Same syntax as zeros matrix 53 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= 0.9501 0.6068 0.8913 0.2311 0.4860 0.7621 55 Identity Matrix: eye function >> eye(3) ans = 1 0 0 0 1 0 >> eye(2,3) ans = 0 0 1 1 0 0 1 0 0 0 0 >> eye(4,3) ans = >> eye(4) ans = 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 1 0 56 Useful Array Functions Better knowing their existance 57 Number of dimensions >> A=[1,2;3,4;5,6] A= 1 3 5 2 4 6 >> ndims(A) ans = 2 >> B=ones(2,3,2) B(:,:,1) = 1 1 1 1 1 1 B(:,:,2) = 1 1 1 1 1 1 >> ndims(B) ans = 3 58 Size Returns the length of each dimensions of its argument >> A=[1,2;3,4;5,6] A= 1 3 5 2 4 6 >> size(A) ans = 3 2 >> B=zeros(2,3,2,4) >> size(B) ans = 2 3 2 4 >> [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= 1 2 0 3 4 2 5 6 4 >> diag(A) ans = 1 4 4 60 Length • Returns the length of the largest dimension of an array Array is 3x2: >> A=[1 3; 2 4; 0 2] A= 1 2 0 3 4 2 >> length(A) ans = 3 61 Sort If a vector, the sort is in ascending order >> A=[4 2 3 9 1 2] A= 4 2 3 9 1 2 >> sort(A) ans = 1 2 2 3 4 9 If a 2-D array, it sorts each column >> A=[4 5 6; 7 8 9; 1 2 3] A= 4 5 6 7 8 9 1 2 3 >> sort(A) ans = 1 2 3 4 5 6 7 8 9 62 sort by column Sort >> A=[4 6 5; 8 7 9; 1 3 2] A= 4 8 1 6 7 3 5 9 2 >> sort(A,1) ans = 1 4 8 3 6 7 2 5 9 >> sort(A,2) ans = 4 7 1 5 8 2 sort by row 6 9 3 63 Linear Systems of Equations Two ways Matrix Division Matrix Inverse 64 In general a system of m equations in n unknowns can be written as: a11 x1 a12 x2 ... a1n xn b1 a21 x1 a22 x2 ... a2 n xn b2 ... AX B am1 x1 am 2 x2 ... amn xn bm In matrix form: a11 a12 ... a1n a a ... a 2n A 21 22 ... am1 am 2 ... amn x1 x X 2 ... xn b1 b B 2 ... bm 65 In general a system of m equations in n unknowns can be written as: a11x1 a12 x2 a1n xn b1 a21x1 a22 x2 a2 n xn b2 ... AX B am1 x1 am 2 x2 amn xn bm a11 a12 a1n x1 b1 a a a x b 21 22 2 n 2 2 ... ... ... am1 am 2 amn xn bm The solution to the linear system: X=A\B (matrix left division) 66 Example: 3x1 x1 5 x1 2 x2 2 x2 10 x2 x3 5 3x3 13 AX B 5 x3 0 2 1 3 1 2 3 5 10 5 A x1 5 x 13 2 x3 0 X B 67 X=A\B, the MATLAB solution >> A=[3 2 1; 1 2 3; -5 -10 -5] A= >> X=A\B X= 2.5000 -4.5000 6.5000 3 2 1 1 2 3 -5 -10 -5 >> B=[5;13;0] B= Verify the answer: 5 13 0 >> B= A*X <E> B= 5 13 0 68 Matrix Inverse IF • 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, Then A-1 exist 69 Inverse • Inverse is a square matrix such that A-1A= I , the identity matrix • The solution of the system is given by A-1AX = IX = X=A-1B • If A is order 3, the identity matrix is also order 3: 1 0 0 I 0 1 0 0 0 1 70 Example A system of 2 equations and 2 unknowns: 2x1- x2 = 2 >> A=[2 -1; 1 1] x1+ x2 = 5 A= 2 -1 1 1 >> B=[2;5] B= 2 5 >> X=inv(A)*B X= 2.3333 2.6667 71 72 Logical Arrays and Masks Section 4.3 Textbook 73 Two possible values Logical Data Type True—(1) False—(0) 74 Logical Arrays Example: n=10; ii=[1:1:n+1]; c= mod(ii,2)==0 c= 0 1 0 1 0 1 0 1 Memory: Memory: ii(1)=1 c(1)=0 ii(2)=2 c(2)=1 ii(3)=3 c(3)=0 … … ii(11)=11 c(11)=0 0 1 0 % Produces a n+1-element Logical Array named c in which elements are true (1) if ii is even and false (0) otherwise 75 Application-Midpoint Rule 𝑏=3 −𝑥 𝑒 2 (2𝑥 𝑎=0 − 𝑥2 )dx 2 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); Only f’s with coefficients equal to 1 survive 76 Logical Arrays Example: >> n = 12; >> iia= [1:1:n+1]; >> coeff = 2*(mod(iia,3)==1) coeff = 2 0 0 2 0 0 2 0 0 2 0 0 2 % 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 Mascaras sirven para “enmascarar” los elementos que no queremos que entren en efecto 78 mask, example: sqrt(a(b)) will take the square root of all elements for which the logical array b is true. >> a=[4, 5, 6] a= 4 5 6 >> b= a > 5 b= 0 0 1 b is a logical array >> a(b)=sqrt(a(b)) a= 4.0000 5.0000 2.4495 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)) 79 mask, example: >> a=[1 2 3; 4 5 6; 7 8 9] a= 1 2 3 4 5 6 7 8 9 >> b=a>5 b= b is a 0 0 0 logical 0 0 1 array 1 1 1 >> a(b)=sqrt(a(b)) 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) a= 1.0000 2.0000 3.0000 4.0000 5.0000 2.4495 2.6458 2.8284 3.0000 To understand these instructions after defining a, and b=a>5, run sequentially sqrt(a(b)) and a(b)=sqrt(a(b)) 80 mask, example: >> a=[1 2 3; 4 5 6; 7 8 9] a= 1 2 3 4 5 6 7 8 9 >> b=a>5 b= 0 0 0 b is a 0 0 1 logical 1 1 1 To understand these instructions after defining a, and b=a>5, run sequentially sqrt(a(b)) and a(b)=sqrt(a(b)) array >> sqrt(a(b)) • ans = • • • • 2.6458 2.8284 2.4495 3.0000 81 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 end end 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. 82 masks: simpson rule example Produce: c=[1 4 2 4 2 4 2 … 4 1] 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 mask: simpson rule example Produce: c=[1 4 2 4 2 4 2 … 4 1] 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 mask: simpson rule example Produce: c=[1 4 2 4 2 4 2 … 4 1] 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 mask: simpson rule example Produce: c=[1 4 2 4 2 4 2 … 4 1] 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) SOLUTION-8: c(3:2:n-1)=2; c(2:2:n)=4 c(1)=1; c(n+1)=1; (4 lines) 86 Produce: c=[1 3 3 2 3 3 2… 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,…, 1000. 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,…, 1000. 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,000elements 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 We want to take the square root of any element in a twodimensional array “a” whose value is greater than 5 , and to square the remaining elements in the array. The code for this operation using loops and branches is shown in the following slide 1 3 • 𝑎= 7 8 5 2 4 7 2 3 9 6 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] Please don’t be confused this is not a method by for ii=1:1:3 logical arrays and masks. This just to show you for jj=1:1:4 how difficult it is without logical arrays. if a(ii,jj)>5 a(ii,jj)=sqrt(a(ii,jj)) else a(ii,jj)=a(ii,jj)^2 end end end 92 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