lecture 2 matlab fundamentals variables, naming rules, arrays (numbers, scalars, vectors, matrices),...

34
Lecture 2 Lecture 2 MATLAB fundamentals MATLAB fundamentals Variables, Naming Rules, Variables, Naming Rules, Arrays (numbers, scalars, vectors, Arrays (numbers, scalars, vectors, matrices), matrices), Arithmetical Operations, Arithmetical Operations, Defining and manipulating arrays Defining and manipulating arrays © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.

Post on 22-Dec-2015

266 views

Category:

Documents


4 download

TRANSCRIPT

Lecture 2Lecture 2MATLAB fundamentalsMATLAB fundamentals

Variables, Naming Rules, Variables, Naming Rules,

Arrays (numbers, scalars, vectors, Arrays (numbers, scalars, vectors, matrices), matrices),

Arithmetical Operations,Arithmetical Operations,

Defining and manipulating arraysDefining and manipulating arrays

© 2007 Daniel Valentine. All rights reserved. Published by Elsevier.

Variables and ArraysVariables and Arrays What are variables?What are variables?

– Variables are Variables are arrays arrays of numbers.of numbers.– You name the You name the variablesvariables (as the (as the

programmer) and assign them numerical programmer) and assign them numerical values.values.

– You execute the assignment command to You execute the assignment command to place the variable in the workspace memory place the variable in the workspace memory (memory is part of hardware used for (memory is part of hardware used for storing information).storing information).

– You are allowed to use the variable in You are allowed to use the variable in algebraic expressions, etc. once it is algebraic expressions, etc. once it is assigned.assigned.

Variable Naming RulesVariable Naming Rules

Must begin with a LETTERMust begin with a LETTER May only contain letters, numbers and May only contain letters, numbers and

underscores ( _ )underscores ( _ ) No spaces or punctuation marks allowed!No spaces or punctuation marks allowed! Only the first 63 characters are Only the first 63 characters are

significant; beyond that the names are significant; beyond that the names are truncated.truncated.

Case sensitiveCase sensitive (e.g. the variables (e.g. the variables aa and and AA are are notnot the same the same))

Which variable names are Which variable names are valid?valid?

12oclockRock12oclockRock tertiarySectortertiarySector blue cowsblue cows Eiffel65Eiffel65 red_bananasred_bananas This_Variable_Name_Is_Quite_Possibly_TooThis_Variable_Name_Is_Quite_Possibly_Too

_Long_To_Be_Considered__Long_To_Be_Considered_Good_Practice_HGood_Practice_However_It_Will_Work % (the green part is owever_It_Will_Work % (the green part is not part of the recognized name)not part of the recognized name)

Variable Naming Variable Naming ConventionsConventions

There are different ways to name variables. The There are different ways to name variables. The following illustrate some of the conventions used:following illustrate some of the conventions used:– lowerCamelCaselowerCamelCase– UpperCamelCaseUpperCamelCase– underscore_conventionunderscore_convention

If a variable is a constant, some programmers use If a variable is a constant, some programmers use all caps:all caps:– CONSTANTCONSTANT

It does not matter which convention you choose It does not matter which convention you choose to work with; it is up to you.to work with; it is up to you.

In MATLAB, a In MATLAB, a variablevariable is stored as an array of is stored as an array of numbers. When appropriate, it is interpreted as a numbers. When appropriate, it is interpreted as a scalarscalar, , vectorvector or or matrixmatrix..

The size of an array is specified by the number of The size of an array is specified by the number of rows and the number of columns in the array, with rows and the number of columns in the array, with the number of rows indicated first.the number of rows indicated first.

Variables as ArraysVariables as Arrays

scalarscalar1 1 ×× 1 1

vectorvectorn n ×× 1 or 1 1 or 1 × × nn

matrixmatrixn n ×× m m

ScalarsScalars are 1×1 arrays. are 1×1 arrays. They contain a single value, for They contain a single value, for

example:example:r = 6r = 6

width = 9.07width = 9.07height = 5.3height = 5.3

ScalarsScalars

VectorsVectors

A A vectorvector is a list of numbers expressed as a 1 is a list of numbers expressed as a 1 dimensional array.dimensional array.

A vector can be n×1 or 1×n.A vector can be n×1 or 1×n. Columns are separated by Columns are separated by commas (or spaces)commas (or spaces)::

Rows are separated by Rows are separated by semicolonssemicolons::

v = [1; 2; 3]v = [1; 2; 3]

h = [1, 2, 3]h = [1, 2, 3]

m = [3.0, 1.8, 3.6; 4.6, m = [3.0, 1.8, 3.6; 4.6, --2.0, 21.3; 0.0, 2.0, 21.3; 0.0, --6.1, 12.8; 2.3, 0.3, 6.1, 12.8; 2.3, 0.3, --6.1]6.1]

MatricesMatrices

A A matrixmatrix is a two is a two dimensional array dimensional array of numbers.of numbers.

For example, this is For example, this is a 4×3 matrix:a 4×3 matrix:

11 22 33

11 3.03.0 1.81.8 3.63.6

22 4.64.6 -2.0-2.0 21.21.33

33 0.00.0 -6.1-6.1 12.12.88

44 2.32.3 0.30.3 -6.1-6.1

ColumnsColumns

Row

sR

ow

s

m(2,3)m(2,3)

Indexed-location of numbers in Indexed-location of numbers in an arrayan array

Each item in an Each item in an array is located in array is located in the the (row, column)(row, column). .

11 22 33

11 3.03.0 1.81.8 3.63.6

22 4.64.6 -2.0-2.0 21.21.33

33 0.00.0 -6.1-6.1 12.12.88

44 2.32.3 0.30.3 -6.1-6.1

ColumnsColumns

Row

sR

ow

s

 

ans =ans = 21.300021.3000

Enter the following into MATLAB:Enter the following into MATLAB:– Scalar:Scalar:

– Vectors:Vectors:

– Matrix:Matrix:d = [5, 4, 3; 0, 2, 8]d = [5, 4, 3; 0, 2, 8]

b = [1, 0, 2]b = [1, 0, 2]

c = [1 0 2]c = [1 0 2]

a = 1a = 1

Hands-onHands-on

Hands-onHands-on

Enter (input) the following matrix into MATLAB:Enter (input) the following matrix into MATLAB:

-7-7 2121 66

22 3232 00

-5-5 00--

18.518.5

whiteRabbit =whiteRabbit =

Scalar OperationsScalar Operations

OperationOperation Algebraic Algebraic SyntaxSyntax

MATLAB MATLAB SyntaxSyntax

AdditionAddition a + ba + b a + ba + b

SubtractionSubtraction a - ba - b a – ba – b

MultiplicationMultiplication a × ba × b a .* ba .* b

DivisionDivision a ÷ ba ÷ b a ./ ba ./ b

ExponentiationExponentiation aabb a .^ ba .^ b

Array OperationsArray Operations Arrays of numbers in MATLAB can be interpreted as Arrays of numbers in MATLAB can be interpreted as

vectors and matrices if vector or matrix algebra is to vectors and matrices if vector or matrix algebra is to be applied. Recall that matrices are mathematical be applied. Recall that matrices are mathematical objects that can be multiplied by the rules of objects that can be multiplied by the rules of matrices. To do matrix multiplication, you need to use matrices. To do matrix multiplication, you need to use the standard the standard **, , //,, and and ^ ^ operators [without the operators [without the preceding preceding .. (dot)]. They are (dot)]. They are notnot for for array array multiplication, division and exponentiationmultiplication, division and exponentiation..

To deal with arrays on an To deal with arrays on an element-by-elementelement-by-element level level we need to use the following we need to use the following arrayarray or or dot-operatorsdot-operators::

.* .* ,, ./ ./ andand .^.^

Array operations & dot-Array operations & dot-operatorsoperators

Because scalars are equivalent to a 1×1 Because scalars are equivalent to a 1×1 array, you can either use the standard or array, you can either use the standard or the the dot-operatorsdot-operators when doing when doing multiplication, division and multiplication, division and exponentiation of scalars (i.e., of single exponentiation of scalars (i.e., of single numbers).numbers).

It is okay for you to always use the dot-It is okay for you to always use the dot-operators, unless you intend to perform operators, unless you intend to perform vector or matrix multiplication or vector or matrix multiplication or division.division.

.*.* ,, ./ ./ andand .^.^

Example:Example:

z = x .* yz = x .* y results in [10, 6; 21, 32]; this is results in [10, 6; 21, 32]; this is array array multiplicationmultiplicationz = x * yz = x * yresults in [17, 20; 43, 50]; this is results in [17, 20; 43, 50]; this is matrix matrix multiplicationmultiplication

So, do NOT forget the dot when doing array So, do NOT forget the dot when doing array operations! (.* ./ .^)operations! (.* ./ .^)

x = [2, 1; 3, 4]x = [2, 1; 3, 4]

y = [5, 6; 7, 8]y = [5, 6; 7, 8]

Array vs. Matrix OperationsArray vs. Matrix Operations

Hierarchy of OperationsHierarchy of Operations

Just like in mathematics the operations are done in Just like in mathematics the operations are done in the following order: the following order: Left to rightLeft to right doing what is in doing what is in

PParentheses & arentheses & EExponents first, followed byxponents first, followed by

MMultiplication & ultiplication & DDivision, and thenivision, and then

AAddition & ddition & SSubtraction last. ubtraction last. An example:An example:

c = 2+3^2+1/c = 2+3^2+1/((1+21+2)) 11stst c = 2+3^2+1/c = 2+3^2+1/33

c = 2+c = 2+33^̂22+1/(1+2)+1/(1+2) 22ndnd c = 2+c = 2+99+1/3+1/3

c = 2+3^2+c = 2+3^2+11//(1+2)(1+2) 33rdrd c = 2+9+c = 2+9+0.333330.33333

c = c = 22++3^23^2+1/(1+2)+1/(1+2) 44thth c = c = 1111+0.33333+0.33333

c = c = 2+3^22+3^2++1/(1+2)1/(1+2) 55thth c = c = 11.3333311.33333

Hands-onHands-on

Enter these two arrays into MATLAB:Enter these two arrays into MATLAB:

Multiply, element-by-element, a × b.Multiply, element-by-element, a × b.– Since this is an array operation, the Since this is an array operation, the .*.*

multiplication operation is implied by multiplication operation is implied by the request. the request.

a =a = 10 5 510 5 5 2 9 02 9 0 6 8 86 8 8

b =b = 1 0 21 0 2 0 0 00 0 0 1 1 01 1 0

Defining & manipulating arraysDefining & manipulating arrays

All variables in MATLAB are arrays!All variables in MATLAB are arrays!– Single number array & scalar: 1 × 1Single number array & scalar: 1 × 1– Row array & row vector:Row array & row vector: 1 × 1 ×

nn– Column array & column vector: n x 1Column array & column vector: n x 1– Array of n rows x m columns & Matrix: n × mArray of n rows x m columns & Matrix: n × m– Naming rulesNaming rules– Indexed by (row, column) Indexed by (row, column)

Remark:Remark: vectors and matrices are special vectors and matrices are special mathematical objects, arrays are lists or mathematical objects, arrays are lists or tables of numbers.tables of numbers.

The equal sign assignsThe equal sign assigns

Consider the command lines:Consider the command lines:>> >> ax = 5;ax = 5;>> >> bx = [1 2];bx = [1 2];>> >> by = [3 4];by = [3 4];>> >> b = bx + by;b = bx + by;

The equal sign (The equal sign (==) commands that ) commands that the number computed on the right of the number computed on the right of it is input to the variable named on it is input to the variable named on the left; thus, it is an assignment the left; thus, it is an assignment operation. operation.

An An arrayarray can be defined by typing in a list of can be defined by typing in a list of numbers enclosed in numbers enclosed in square bracketssquare brackets::

– CommasCommas or or spacesspaces separate numbers. separate numbers.

– SemicolonsSemicolons indicate a new row. indicate a new row.

A = [12, 18, A = [12, 18, --3] 3] oror A = [12 18 A = [12 18 --3]3]

B = [2, 5, 2; 1 , 1, 2; 0, B = [2, 5, 2; 1 , 1, 2; 0, --2, 6]2, 6]

Defining (or assigning) Defining (or assigning) arraysarrays

A =A = 12 18 -312 18 -3

B =B = 2 5 2 2 5 2 1 1 21 1 2 0 -2 60 -2 6

D =D =

12 18 -312 18 -3 12 18 -312 18 -3

2 5 22 5 2 2 5 22 5 2

1 1 21 1 2 1 1 21 1 2

0 -2 60 -2 6 0 -2 60 -2 6

C = [A; B]C = [A; B]

D = [C, C]D = [C, C]

Defining arrays continuedDefining arrays continued You can define an array in terms of another array:You can define an array in terms of another array:

C =C =

12 18 -312 18 -3

2 5 22 5 2

1 1 21 1 2

0 -2 60 -2 6

Create an array of zeros:Create an array of zeros:

Create an array of ones:Create an array of ones:

Note: Placing a single number inside either function will return an Note: Placing a single number inside either function will return an nn × × nn array. e.g. array. e.g. ones(4)ones(4) will return a 4 × 4 array filled with ones. will return a 4 × 4 array filled with ones.

E = zeros(3,5)E = zeros(3,5)

F = ones(2,3)F = ones(2,3)

Creating Zeros & Ones Creating Zeros & Ones arraysarrays

E =E = 0 0 0 0 00 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 00 0 0 0 0

F =F = 1 1 11 1 1 1 1 11 1 1

Index Index – a number used to identify elements in an – a number used to identify elements in an arrayarray– Retrieving a value from an array:Retrieving a value from an array:

G(3,2)G(3,2)G(2,1)G(2,1)

G = [1, 2, 3; 4, 5, 6; 7, 8, 9]G = [1, 2, 3; 4, 5, 6; 7, 8, 9]

Retrieving Values in an Retrieving Values in an ArrayArray

ans = ans = 44 ans = ans = 88

G =G = 1 2 31 2 3 44 5 6 5 6 7 7 88 9 9

You can change a value in an element in an array with indexing:You can change a value in an element in an array with indexing:

You can extend an array by defining a new element:You can extend an array by defining a new element:

– Notice how undefined values of the array are filled with zerosNotice how undefined values of the array are filled with zeros

A(2) = 5A(2) = 5

A(6) = 8A(6) = 8

Changing Values in an Changing Values in an ArrayArray

A =A = 12 12 55 -3 -3

A =A = 12 5 -3 12 5 -3 0 00 0 88

Colon notationColon notation can be used to define evenly spaced vectors in the can be used to define evenly spaced vectors in the form:form:

first : lastfirst : last

The default spacing is 1, so to use a different increment, use the The default spacing is 1, so to use a different increment, use the form:form:

first : increment : lastfirst : increment : last

– The numbers now increment by 2The numbers now increment by 2

I = 1:2:11I = 1:2:11

H = 1:6H = 1:6

Colon OperatorColon Operator

H =H = 11 2 3 4 5 2 3 4 5 66

I =I = 1 3 5 7 9 111 3 5 7 9 11

G(2,:)G(2,:)G(:,1)G(:,1) G(:,3) G(:,3)

Extracting Data with the Colon Extracting Data with the Colon OperatorOperator

The colon represents an entire row or column The colon represents an entire row or column when used in as an array index in place of a when used in as an array index in place of a particular number.particular number.G =G =

11 2 2 33 44 55 66 77 8 8 99

ans =ans =

11

44

77

ans =ans =

33

66

99

ans = ans =

4 5 64 5 6

G(1,2:3) G(1,2:3) G(2:3,:)G(2:3,:)

Extracting Data with the Colon Extracting Data with the Colon Operator ContinuedOperator Continued

The colon operator can also be used to extract a The colon operator can also be used to extract a range of rows or columns:range of rows or columns:

G =G = 1 1 2 32 3 4 5 64 5 6 7 8 97 8 9

ans =ans = 2 32 3

G =G = 4 5 6 4 5 6 7 8 97 8 9

J'J'J = [1 , 3, 7]J = [1 , 3, 7]

Manipulating ArraysManipulating Arrays

The The transpose operatortranspose operator, an , an apostropheapostrophe, changes all of an array’s , changes all of an array’s rows to columns and columns to rows to columns and columns to rows.rows.

J =J = 1 3 71 3 7

ans =ans =

11 33 77

Manipulating Matrices Manipulating Matrices Continued Continued

The functions The functions fliplr()fliplr() and and flipud()flipud() flip flip a matrix left-to-right and top-to-a matrix left-to-right and top-to-bottom, respectively.bottom, respectively.– Experiment with these functions to see Experiment with these functions to see

how they work.how they work.

W = [1:5; 10:2:18; 6:W = [1:5; 10:2:18; 6:--1:2]1:2]

Hands-on exercise:Hands-on exercise: Create the following matrix using colon notation:Create the following matrix using colon notation:

W =W = 1 2 3 4 51 2 3 4 5 10 12 14 16 1810 12 14 16 18 6 5 4 3 26 5 4 3 2

All three rows are evenly spacedAll three rows are evenly spaced– The first row ranges from 1 to 5 in increments of 1The first row ranges from 1 to 5 in increments of 1

1:51:5– The second row ranges from 10 to 18 in increments of 2The second row ranges from 10 to 18 in increments of 2

10:2:1810:2:18– The third row ranges from 6 to 2 in increments of -1The third row ranges from 6 to 2 in increments of -1

6:-1:26:-1:2– All together:All together:

Hands-on continuedHands-on continued Create the following matrix using colon notation:Create the following matrix using colon notation:

X =X =

1.2 2.3 3.4 4.5 5.61.2 2.3 3.4 4.5 5.6

1.9 3.8 5.7 7.6 9.51.9 3.8 5.7 7.6 9.5

0 -3 -6 -9 -120 -3 -6 -9 -12

Transpose this matrix and assign it to variable Transpose this matrix and assign it to variable YY..

>> >> Y = x’Y = x’ Extract the 2nd row from Y and assign it to Extract the 2nd row from Y and assign it to

variable variable ZZ..

>> >> Z = Y(2,:)Z = Y(2,:)

Summary (1 of 2)Summary (1 of 2)

Naming a variable: Start with letter Naming a variable: Start with letter followed by any combination of letters, followed by any combination of letters, numbers and underscores (up to 63 of numbers and underscores (up to 63 of these objects are recognized).these objects are recognized).

Arrays are rows and columns of Arrays are rows and columns of numbers.numbers.

Array operations (element-by-element Array operations (element-by-element operations with the dot-operators) operations with the dot-operators)

Hierarchy of arithmetic operations.Hierarchy of arithmetic operations.

Summary (2 of 2)Summary (2 of 2)

Command lines that assign variables Command lines that assign variables numerical values start with the numerical values start with the variable name followed by = and then variable name followed by = and then the defining expressionthe defining expression

An array of numbers is the structure of An array of numbers is the structure of variables in MATLAB. Within one variables in MATLAB. Within one variable name, a set of numbers can variable name, a set of numbers can be stored. be stored.

Array, vector and matrix operations are Array, vector and matrix operations are efficient MATLAB computational tools.efficient MATLAB computational tools.