c/c++ programming for engineers: matlab arraysi109/notes/03 - matlab arrays.pdf · 6/28/2018 2 3...

13
6/28/2018 1 C/C++ Programming for Engineers: Matlab Arrays John T. Bell Department of Computer Science University of Illinois, Chicago 2 Reading Review What row array does [5:2:10] create? A. [ 5, 2, 10 ] B. [ 5, 10 ] C. [ 2, 4, 6, 8, 10 ] D. [ 5, 7, 9, 11 ] E. [ 5, 7, 9 ]

Upload: others

Post on 31-Aug-2019

9 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C/C++ Programming for Engineers: Matlab Arraysi109/Notes/03 - Matlab Arrays.pdf · 6/28/2018 2 3 Reading Review Which Matlab function or tool will create an evenly-spaced sequence

6/28/2018

1

C/C++ Programming for Engineers:Matlab Arrays

John T. Bell

Department of Computer ScienceUniversity of Illinois, Chicago

2

Reading Review

What row array does [5:2:10] create?

A. [ 5, 2, 10 ]

B. [ 5, 10 ]

C. [ 2, 4, 6, 8, 10 ]

D. [ 5, 7, 9, 11 ]

E. [ 5, 7, 9 ]

Page 2: C/C++ Programming for Engineers: Matlab Arraysi109/Notes/03 - Matlab Arrays.pdf · 6/28/2018 2 3 Reading Review Which Matlab function or tool will create an evenly-spaced sequence

6/28/2018

2

3

Reading Review

Which Matlab function or tool will create an evenly-spaced sequence of numbers, given the end points and how many numbers are desired?

A. linspace( )

B. logspace( )

C. The colon operator, :

D. sequence( )

E. Either A or C would work.

4

Creating Matrices IDirect Data Entry

• Enclose values in square brackets

• Separate data on a row with commas or spaces

• Start a new row with a semicolon

• Examples:

– X = [ 3, 5, -7 ];

– Y = [ 11, 12, 13; 21, 22, 23 ];

3 5 -7

11 12 13

21 22 23

Page 3: C/C++ Programming for Engineers: Matlab Arraysi109/Notes/03 - Matlab Arrays.pdf · 6/28/2018 2 3 Reading Review Which Matlab function or tool will create an evenly-spaced sequence

6/28/2018

3

5

Creating Matrices IIThe colon operator

• Creates a range using a given increment, 1 by default

• x = 3:6;

• x = 4:2:10;

• x = pi : -pi/2 : -pi;

• x = 12 : 10 : 50;

3 4 5 6

4 6 8 10

3.14 1.57 0 -1.57 -3.14

12 22 32 42

6

Creating Matrices IIIHandy Matlab Functions

• zeros( N ) or zeros( M, N ) - M rows x N columns

• ones( N ) or ones( M, N )

• rand( N ) or rand( M, N ) - random range 0 to 1.0

• eye( N ) - Identity matrix, 1s on main diagonal

• linspace( x1, x2, N ) - N points spaced linearly

• logspace( x1, x2, N ) - N points spaced logarithmically

• magic( N ) - “Magic” squares

• peaks( N ) - A handy sample peaked surface

Page 4: C/C++ Programming for Engineers: Matlab Arraysi109/Notes/03 - Matlab Arrays.pdf · 6/28/2018 2 3 Reading Review Which Matlab function or tool will create an evenly-spaced sequence

6/28/2018

4

7

Creating Matrices IVConcatenating Arrays

• X = [ 1, 2, 3 ];

• Y = [ 10, 20, 30, 40 ];

• Z = [ 100, 200, 300; 150, 250, 350 ]

• H = [ X, Y ]; Requires same number of rows

• V = [ X; Z ]; Requires same number of columns

1 2 3 10 20 30 40

1 2 3

100 200 300

150 250 350

8

Creating Matrices VLoading data in from a file

• The “load” command will load in numbers from a plain ASCII text file.– “load (filename)” will create a variable named the

same as the name of the file.

– “var = load( filename ) will name the variable ‘var’

• load also works with Matlab-format data files, created earlier with “save”.

• Matlab also has tools for reading in other file formats, such as Excel, jpg, csv, etc.

Page 5: C/C++ Programming for Engineers: Matlab Arraysi109/Notes/03 - Matlab Arrays.pdf · 6/28/2018 2 3 Reading Review Which Matlab function or tool will create an evenly-spaced sequence

6/28/2018

5

9

Matrix Math IScalars Are Easy for +, -, *, /

• If M is a matrix of any dimension, and S is a scalar, then “M op S” or “S op M” work just as expected, where “op” is one of +, -, *, /

➢[ 1, 2, 3 ] * 2.1 [ 2.1, 4.2, 6.3 ]

➢5 / [ 1, 2, 4 ] [ 5, 2.5, 1.25 ]

➢[ 1, 2, 4 ] + pi [ 4.14, 5.14, 7.14 ]

10

Matrix Math IITwo Matrices With + or -

• Addition or Subtraction of two matrices requires that both matrices have the same number of rows and the same number of columns. Then the elements are added or subtracted element by element:

➢[ 1, 2, 3; 11, 22,33 ] + [ 5, 10, 15; 100, 200, 300 ];

6 12 18

111 222 333

Page 6: C/C++ Programming for Engineers: Matlab Arraysi109/Notes/03 - Matlab Arrays.pdf · 6/28/2018 2 3 Reading Review Which Matlab function or tool will create an evenly-spaced sequence

6/28/2018

6

11

Matrix Math IIIElementwise multiplication & division

• The elements within an array may be multiplied or divided on an element by element basis, using special operators, .* & ./

• The two matrices must be the same size.

• X = [ 1, 2, 3; 4, 5, 6 ];

• Y = [ 10, 20, 30; 40, 50, 60

• prod = X .* Y;

• ratio = X ./ Y10 40 90

160 250 360

12

Matrix Math IVElementwise Exponentiation

• Two matrices of the same size may have their elements raised to a power on an elementwise basis, with .^ just like .* and ./

• The elements of a matrix may also be raised to a scalar power or vice versa using .^➢X .^ Y; - Two matrices, elementwise

➢M .^ S; - Matrix elements raised to a scalar power

➢S .^ M; - Scalar raised to the powers of matrix elements. 2 .^ [ 1, 2, 5, 10 ] [ 2, 4, 32, 1024 ]

Page 7: C/C++ Programming for Engineers: Matlab Arraysi109/Notes/03 - Matlab Arrays.pdf · 6/28/2018 2 3 Reading Review Which Matlab function or tool will create an evenly-spaced sequence

6/28/2018

7

13

Matrix Math VTrue Matrix Multiplication

• To truly multiply one matrix by another, the number of columns of the first matrix must match the number of rows of the second. ( The “inner” dimensions must match. )

• This is covered in linear algebra, and will not be addressed in CS 109. ( At this time. )

14

Matlab Functions Act On Arrays

• X = -pi : pi / 10 : pi;

• S = sin( X ); % Calculates sine of each element of X

• disp( ‘ X sine( X )’ );

• disp( [ X’, S’ ] ); % apostrophe yields transposeX sine( X )

-3.1416 -0.0000

-2.8274 -0.3090

-2.5133 -0.5878

. . .

2.8274 0.3090

3.1416 0.0000

Page 8: C/C++ Programming for Engineers: Matlab Arraysi109/Notes/03 - Matlab Arrays.pdf · 6/28/2018 2 3 Reading Review Which Matlab function or tool will create an evenly-spaced sequence

6/28/2018

8

15

Parallelizing Math Calculations

• Consider the function:

𝑓 𝑥 =𝑥3 + sin 𝑥

𝑒42𝑥 + ln 𝑥

• If X = pi : pi/100 : 3 * pi, then:

• f = ( x .^3 + sqrt( sin( x ) ) ) ./ ( exp( 42 * x ) …+ log( x ) );

• Performs calculations for 200 values at once.

16

Review

• Which of the following correctly implements this equation, for x a vector:

𝑆 =1 + sin( 𝑥 )

cos2 𝑥 + 1A. S = sin( x ) + 1 / 1 + cos(x) * cos( x )B. S = ( 1 + sin( x ) ) / ( 1 + cos2( x ) )C. S = ( 1 + sin( x ) ) ./ ( 1 + cos ( x ).^2 )D. S = ( 1 + sin( x ) ) / ( 1 + cos^2 ( x ) )E. S = 1 + sin(x) / cos(x)^2 + 1

Page 9: C/C++ Programming for Engineers: Matlab Arraysi109/Notes/03 - Matlab Arrays.pdf · 6/28/2018 2 3 Reading Review Which Matlab function or tool will create an evenly-spaced sequence

6/28/2018

9

17

Think – Pair - Share

1. On a piece of paper, write down a function involving things like sine, cosine, powers, exponentials, logarithms, square roots, etc.

2. Swap papers with a neighbor, and write the Matlab code to implement the function.

3. Swap again with someone else, and verify the Matlab code implements the function.

4. Share with the class as a whole.

18

Accessing Matrix Elements

• Use an integer index in ( parentheses ), from 1 up to the size of the array. E.g. X( 42 )

• Separate indices for multi-dimension arrays with commas. E.g. Y( 4, 2 ) accesses 4th row, 2nd column

• Groups of integers ( including variables ) can be used as well. Z( 5:10 ), nums( [ 4, n, j, 17 ] )

• Colon, :, accesses an entire row or column.– D( 3, : ) gets all of row 3; D( :, 4:6) all columns 4 to 6

• “end” references the last row or column. P( 2:end )

Page 10: C/C++ Programming for Engineers: Matlab Arraysi109/Notes/03 - Matlab Arrays.pdf · 6/28/2018 2 3 Reading Review Which Matlab function or tool will create an evenly-spaced sequence

6/28/2018

10

19

Relational Operators

• The following operators evaluate a relationship, and yield “true” or “false”:

• Note: Do not confuse = with ==

Operator Example Result

> A > B True if A is greater than B, false otherwise

< A < B True if A is less than B, false otherwise

>= A >= B True if A is greater than or equal to B, false otherwise

<= A <= B True if A is less than or equal to B, false otherwise

== A == B True if A is equal to B, false otherwise

~= A ~= B True if A is not equal to B, false otherwise

20

Relational Operations on Arrays

• True and False are often represented by 1 and 0

• Relational operators applied to arrays generate arrays of 1s and 0s, termed logical arrays.

• If X = [ 42, 0, -7, 109 ], then X > 0 is [ 1, 0, 0, 1 ]

• Logical arrays can be used as indices:

X( X > 0 ) = -100 turns X into [ -100, 0, -7, -100 ]

Page 11: C/C++ Programming for Engineers: Matlab Arraysi109/Notes/03 - Matlab Arrays.pdf · 6/28/2018 2 3 Reading Review Which Matlab function or tool will create an evenly-spaced sequence

6/28/2018

11

21

Logical Operators

• The following operators combine logic values:

• Note: && and || also exist, but are only appropriate for use on scalars, not on arrays.

Operator Example

Equivalent Function

Result

A & B and( A, B ) True if both A and B are true. False otherwise.

A | B or( A, B ) True if either A or B or both are true. False otherwise.

~ A not( A ) True if A is false. False otherwise.

xor( A, B ) True if either A or B is true and the other false.I.e. true if A and B are different. False otherwise.

22

Plotting Made Easy

1. Right-click the variable(s) in the workspace you want to plot.

2. Select a plot type from the pull-down menu.

3. Read doc on resulting plot command. Copy command and modify as needed.

4. Enhance with title, xlabel, ylabel, colorbar, …

5. Export plot as jpg, etc. for use in other programs, e.g. for inclusion in documents.

Page 12: C/C++ Programming for Engineers: Matlab Arraysi109/Notes/03 - Matlab Arrays.pdf · 6/28/2018 2 3 Reading Review Which Matlab function or tool will create an evenly-spaced sequence

6/28/2018

12

23

Review

Which Matlab operator tests to see whether or not two operands are equal, and only yields “true” when they are?

A. =

B. ==

C. ~=

D. !=

E. +=

24

Functions that return dimensional properties of an array

MATLAB function Description

nLargest = length(inArray) length returns the number of elements along the largest dimension of inArray. Often used to find length of a 1D array.

nDim = ndims(inArray) ndims returns the number of array dimensions.

nArrElement = numel(inArray) numel returns the number of array elements.

[nRow,nCol] = size(inArray)

size returns the number of rows and number of columns (nRow, nCol) of the array inArray. If only the row dimension is needed, then the programmer should use size(inArray,1). If only the column dimension is needed, then the programmer should use size(inArray,2).

Page 13: C/C++ Programming for Engineers: Matlab Arraysi109/Notes/03 - Matlab Arrays.pdf · 6/28/2018 2 3 Reading Review Which Matlab function or tool will create an evenly-spaced sequence

6/28/2018

13

25

Review

What Matlab command will produce an Identity matrix? ( A matrix with ones on the main diagonal and zeros everywhere else. )

A. diag( )

B. eye( )

C. identity( )

D. ones( )

E. zeros( )