array and matrix operations

Post on 17-Jan-2016

55 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

Array and Matrix Operations. Dr. Marco A. Arocha INGE3016-MATLAB Sep 11, 2007, Dic 7, 2012. Array Operations. Array Addition. With 1D arrays : >> A=[1 3 5 ]; >> B=[2 4 6]; >> A+B ans = 3 7 11. With 2D arrays : >> A=[1 3 5; 2 4 6] A = 1 3 5 - PowerPoint PPT Presentation

TRANSCRIPT

Array and Matrix OperationsDr. Marco A. ArochaINGE3016-MATLABSep 11, 2007, Dic 7, 2012

1

2

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

Array Operations

3

Assume the following arrays of length n:

]...[ 321 naaaaA ]...[ 321 nbbbbB

Addition of arrays of the same length is defined as:

],...,,[ 2211 nn bababaBA

Subtraction of arrays of the same length:

],...,,[ 2211 nn bababaBA

Multiplication of arrays of the same length: ‘.*’

]*,...,*,*[*. 2211 nn bababaBA

Division of arrays of the same length: ‘./’

]/,...,/,/[/. 2211 nn bababaBA

Exponentiation of arrays of the same length ‘ .^’ A.^B=[a1^b1, a2^b2, a3^b3,…,an^bn]

Array AdditionWith 1D arrays:

>> A=[1 3 5 ];>> B=[2 4 6];>> A+B

ans =

3 7 11

With 2D arrays:

>> A=[1 3 5; 2 4 6]A = 1 3 5 2 4 6

>> B=[-5 6 10; 2 0 9]B = -5 6 10 2 0 9>> A+Bans = -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.*Bans = 2 9 20 -2 -8 -18

5

Arrays must be of the same size

Array Division>> A=[2,4,6]A = 2 4 6>> B=[2,2,2]B = 2 2 2>> A./B % num/den Right divisionans = 1 2 3>> A.\B % den\num Left divisionans = 1.0000 0.5000 0.3333

6

Array Exponentiation

>> A=[2,4,6]A = 2 4 6>> B=[2,2,2]B = 2 2 2>> B.^Aans = 4 16 64

7

Special Cases: array <operator> scalarscalar<operator> array

>> A+2ans = 3 4 5

>> A-1ans = 0 1 2

8

>> A.*5ans = 5 10 15

>> A./2ans 0.5 1.0 1.5

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 <operator> scalarscalar<operator> array

>> a*2ans = 2 4 6>> a.*2ans = 2 4 6

>> a/2ans = 0.5000 1.0000 1.5000

>> a./2ans = 0.5000 1.0000 1.5000

9

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 = 2 4 6

>> A.*Bans =

10 20 3010

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

Rectangulararray

m, rows

n, columns

Square Matrix

• m=n

321

753

642

A

13

Square matrix of order three

Z=3*A(2,3)

Can reference individual elements

Main diagonal:[2,5,3], i.e, Ai,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-dimensioningUpon appending one more element to an array, MATLAB

automatically resizes the array to handle the new element

>> a=[2 3 4] % a contains 3 elementsa = 2 3 4>> a(4)=6 % now a contains 4 elementsa = 2 3 4 6>> a(5)=7 % now a contains 5 elementsa = 2 3 4 6 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 4 1 2 3 4>> c=[a; 2*b]c = 1 2 3 4 2 4 6 8 2 4 6 8

16

Self-dimensioning is aMATLAB 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

18

Deletes row-2, all column elements

Storage Mechanism for Arrays

19

Storage mechanism for arrays

A = 1 3 5 2 4 6 3 5 7

20

Two common ways of storage mechanism,depending on language:

• One row at a time: row-major order (*)1 3 5 2 4 6 3 5 7

• One column at a time: column-major order1 2 3 3 4 5 5 6 7

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 =

1 3 5 2 4 6 3 5 7

>> 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 =

1 3 5 2 4 6 3 5 7

In memory they are arranged as:

1 2 3 3 4 5 5 6 7

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 =

1 3 5 2 4 6 3 5 7

With one index & colon operator:>> A(1:2:9)ans = 1 3 4 5 7The 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)=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

Example

Add one unit to each element in A:

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'; endend

% 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.

A= F M M M MM F M M MM M F M MM M M F MM M M M F

Accessing Elements of an Array

>> A=[1 3 5; 2 4 6; 3 5 7]

A =

1 3 5 2 4 6 3 5 7

>> A(2,:) ans = 2 4 6

(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 =

1 3 5 2 4 6 3 5 7

>> A(2:3, 1:2)

ans = 2 4 3 5Means:

rows from 2 to 3, andcolumns 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 Ferrari30

VectorizationOperations 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

VectorizationOperations 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

VectorizationOperations 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

VectorizationOperations executed one by one:

% 10th Fibonacci number (n=10)

f(1)=0;f(2)=1;

for k = 3:1:nf(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

VectorizationOperations 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 OperationsFollows 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*Bans = -22

39

~ 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

m

kkjikij bapAB

1 pnpmmn x)x(*)x (

40

A B A*B

No commutative: AB≠BA

Matrix MultiplicationMath Syntax: ABMATLAB Syntax: A*B (NO DOT)

>> A=[1 3 5; 2 4 6]A = 1 3 5 2 4 6

41

Sample calculation:The dot product of row one of A and column one of B:(1*-2)+(3*3)+(5*12)=67

>> A*Bans =

67 18 80 28

>> B=[-2 4; 3 8; 12 -2]B = -2 4 3 8 12 -2

Transpose

42Columns become rows

Transpose

963

852

741

987

654

321

TA

A

MATLAB:>> A=[1,2,3;4,5,6;7,8,9]

A =

1 2 3 4 5 6 7 8 9

>> A'

ans =

1 4 7 2 5 8 3 6 9

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:

122122112221

1211det aaaaaa

aa

45

>> A=[2,3;6,4]A = 2 3 6 4

>> det(A)ans = -10

MATLAB instructions

Matrix Exponentiation

• A must be square:A2=AA (matrix multiplication)A3=AAA

MATLAB>> A=[1,2;3,4]A = 1 2 3 4>> A^2ans = 7 10 15 22>> A^3ans = 37 54 81 118

46

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 (<), 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 GeneratorsTo cop with arrays that are used very frequently

51

Zero Matrix

>> A=zeros(2)

A =

0 0 0 0

>> A=zeros(2,4)

A =

0 0 0 0 0 0 0 0

52

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 =

1 1 1 1 1 1 1 1 1

>> A=ones(3,2)

A =

1 1 1 1 1 1

53Same syntax as zeros matrix

row

column

Quiz

n=10;ones(1,n+1)

outputans =

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 0 0 1

>> eye(4)ans =

1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1

>> eye(2,3)ans =

1 0 0 0 1 0

>> eye(4,3)ans =

1 0 0 0 1 0 0 0 1 0 0 0

56

Useful Array FunctionsBetter knowing their existance

57

Number of dimensions>> A=[1,2;3,4;5,6]A =

1 2 3 4 5 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

SizeReturns the length of each

dimensions of its argument

>> A=[1,2;3,4;5,6]A =

1 2 3 4 5 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 = 2n = 3s = 2t = 4

59

DiagonalReturns 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 3 5 2 4 6 0 2 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 3 2 4 0 2

>> length(A)ans =

361

SortIf 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>> A=[4 6 5; 8 7 9; 1 3 2]A =

4 6 5 8 7 9 1 3 2

>> sort(A,1)ans =

1 3 2 4 6 5 8 7 9

>> sort(A,2)ans =

4 5 6 7 8 9 1 2 3

63

sort by column

sort by row

Linear Systems of Equations

Matrix DivisionMatrix Inverse

64

Two ways

65

BAX2

1

2

1

22

222

212

11

121

111

...

...

...

...

mnmn

nn

nn

mm b

b

b

xa

xa

xa

xa

xa

xa

xa

xa

xa

mn

n

n

mm a

a

a

a

a

a

a

a

a

A 2

1

2

22

12

1

21

11

...

...

...

...

nx

x

x

X...

2

1

mb

b

b

B...

2

1

In general a system of m equations in n unknowns can be written as:

In matrix form:

66

BAX2

1

2

1

22

222

212

11

121

111

...

mnmn

nn

nn

mm b

b

b

xa

xa

xa

xa

xa

xa

xa

xa

xa

mn

n

n

mm a

a

a

a

a

a

a

a

a

2

1

2

22

12

1

21

11

...

nx

x

x

...2

1

mb

b

b

...2

1

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

5105

321

123

3

2

1

x

x

x

0

13

5

Example:

BAX

xxx

xxx

xxx

0

13

5

5105

32

23

321

321

321

A X B

X=A\B, the MATLAB solution>> A=[3 2 1; 1 2 3; -5 -10 -5]A =

3 2 1 1 2 3 -5 -10 -5

>> B=[5;13;0]B =

5 13 0

>> X=A\BX = 2.5000 -4.5000 6.5000

68

Verify the answer:

>> B= A*X <E>

B = 5 13 0

Matrix Inverse

• A is the coefficient matrix• X is the solution vector• m = n, A is square matrixi.e., number of rows equal the number of columns

• det A is non-zero,

69

IFThen

A-1 exist

Inverse

100

010

001

I

• 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

70

• If A is order 3, the identity matrix is also order 3:

ExampleA system of 2 equations and 2 unknowns:2x1- x2 = 2

x1+ x2 = 5

71

>> A=[2 -1; 1 1]A = 2 -1 1 1>> B=[2;5]B = 2 5>> X=inv(A)*BX = 2.3333 2.6667

72

Logical Arrays and MasksSection 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)==0c= 0 1 0 1 0 1 0 1 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

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);

76Only f’s with coefficients equal to 1 survive

)dx

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

78

Mascaras sirven para “enmascarar” los elementos que no queremos que entren en efecto

mask, example:>> a=[4, 5, 6]a = 4 5 6

>> b= a > 5b = 0 0 1

>> a(b)=sqrt(a(b))a = 4.0000 5.0000 2.4495

79

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 alogicalarray

mask, example:>> a=[1 2 3; 4 5 6; 7 8 9]a = 1 2 3 4 5 6 7 8 9>> b=a>5b = 0 0 0 0 0 1 1 1 1

>> a(b)=sqrt(a(b))

a =

1.0000 2.0000 3.0000 4.0000 5.0000 2.4495 2.6458 2.8284 3.0000

80

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 alogicalarray

mask, example:>> a=[1 2 3; 4 5 6; 7 8 9]a = 1 2 3 4 5 6 7 8 9>> b=a>5b = 0 0 0 0 0 1 1 1 1

>> sqrt(a(b))

• ans =

• 2.6458• 2.8284• 2.4495• 3.0000

81

To understand these instructions after defining a,and b=a>5, run sequentially sqrt(a(b))and a(b)=sqrt(a(b))

b is alogicalarray

With loops and if statement

for ii=1:1:3for jj=1:1:3

if a(ii,jj)>5a(ii,jj)= sqrt(a(ii,jj));

endend

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-1c=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-2c=ones(1,n+1);ii=[1:1:n+1];b=mod(ii,2)==0c(b)=4*c(b);c(~b)=2*c(~b); c(1)=1;c(n+1)=1;(7 lines)

83

Produce: c=[1 4 2 4 2 4 2 … 4 1]

mask: simpson rule example

SOLUTION-3c=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-4c=ones(1,n+1);b=mod(1:1:n+1,2)==0c(b)=4*c(b);c(~b)=2*c(~b); c(1)=1;c(n+1)=1;(6 lines)

84

Produce: c=[1 4 2 4 2 4 2 … 4 1]

mask: simpson rule example

SOLUTION-5c=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-6c=ones(1,n+1);b=mod(1:1:n+1,2)==0c(b)=4;c(~b)=2; c(1)=1;c(n+1)=1;(6 lines)

85

Produce: c=[1 4 2 4 2 4 2 … 4 1]

mask: simpson rule example

SOLUTION-7:

c=2*ones(1,n+1);b=mod(1:1:n+1,2)==0c(b)=4;c(1)=1;c(n+1)=1;(5 lines)

86

Produce: c=[1 4 2 4 2 4 2 … 4 1]

SOLUTION-8:

c(3:2:n-1)=2;c(2:2:n)=4c(1)=1;c(n+1)=1;(4 lines)

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 3ii=[1:1:n+1];b=mod(ii,3)==1; % also b=mod(1:1:n+1,3)==1c(b)=(2/3)*c(b); % also c(b)=2/3c(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,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

Solutionii=[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 two-dimensional 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

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 endend 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

top related