vectors, arrays and functions

34
<9/6/2007> Page 1 Physics 241 -- New Mexico Tech Vectors, Arrays and Functions Richard Sonnenfeld (with some material from W. Palm) n Vectors Vectors Physics definition Physics definition Use in Use in Matlab Matlab n Concept of an Array Concept of an Array n User Defined Functions User Defined Functions n Conditional statements Conditional statements

Upload: others

Post on 05-Jan-2022

9 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Vectors, Arrays and Functions

<9/6/2007> Page 1Physics 241 -- New Mexico Tech

Vectors, Arrays and FunctionsRichard Sonnenfeld

(with some material from W. Palm)

nn VectorsVectorsPhysics definitionPhysics definitionUse in Use in MatlabMatlab

nn Concept of an ArrayConcept of an Arraynn User Defined FunctionsUser Defined Functionsnn Conditional statementsConditional statements

Page 2: Vectors, Arrays and Functions

<9/6/2007> Page 2Physics 241 -- New Mexico Tech

Matlab can easily represent vectors as defined in the classical physics sense.

The vector r can be specified by three components: x, y, and z, and can be written as:

r = [x, y, z].

However, MATLAB can use vectors having more than three elements.

r

Page 3: Vectors, Arrays and Functions

<9/6/2007> Page 3Physics 241 -- New Mexico Tech

To create a row vector, separate the elements by commas. For example,

>>p = [3,7,9]p =

3 7 9

You can create a column vector by using the transpose notation (').Or by separating the elements by semicolons. For example,

>>p = [3,7,9]'p =

379

>>g = [3;7;9]g =

379

Page 4: Vectors, Arrays and Functions

<9/6/2007> Page 4Physics 241 -- New Mexico Tech

You can create vectors by ''appending'' one vector to another.

For example, if

>> r = [2,4,20] and >> w = [9,-6,3], Then>> u = [r,w]. The result is the vector u = [2,4,20,9,-6,3].You can also create a subset of a vector.Assume we wanted to use the 2nd, 3rd, and 4th elements of u. How could this be done?

Page 5: Vectors, Arrays and Functions

<9/6/2007> Page 5Physics 241 -- New Mexico Tech

The colon operator (:) easily generates a large vector of regularly spaced elements.

Typing

>>x = [m:q:n]

creates a vector x of values with a spacing q. The first value is m. The last value is n if m - n is an integer multiple of q. If not, the last value is less than n.

Page 6: Vectors, Arrays and Functions

<9/6/2007> Page 6Physics 241 -- New Mexico Tech

For example>> x = [0:2:8]x =

[0,2,4,6,8]

>> x = [0:2:7]x =

[0,2,4,6]

To create row vector z consisting of the values from 5 to 8 in steps of 0.1, type z = [5:0.1:8].

If the increment q is omitted, then q=1. y = [-3:2]y = [-3,-2,-1,0,1,2].

Page 7: Vectors, Arrays and Functions

<9/6/2007> Page 7Physics 241 -- New Mexico Tech

The linspace command also creates a linearly spaced row vector, but instead you specify the number of values rather than the increment.

The syntax is linspace(x1,x2,n), where x1 and x2are the lower and upper limits and n is the number of points.

For example, linspace(5,8,31) is equivalent to [5:0.1:8].

If n is omitted, the spacing is 1.

Example:t=linspace(0,5);x=3*t-4.9*t.^2;plot(t,x)

Page 8: Vectors, Arrays and Functions

<9/6/2007> Page 8Physics 241 -- New Mexico Tech

Matlab flexibly and cleverly handles row and column vectors and matrices of different sizes.

Most operations are defined on vectors or matrices of the same size. For example, adding a row vector to acolumn vector causes an error.

>> a=[0:10]; b=a’+7; c=a+b

??? Error using ==> +Matrix dimensions must agree.

Get used to looking for these – they are one of the most common causes of strange behavior.

Potential confusionPotential confusion

Page 9: Vectors, Arrays and Functions

<9/6/2007> Page 9Physics 241 -- New Mexico Tech

“Array” (noun) In programming languages, a name given to sequences of variables that have a relationship to eachother.

Examples:Successive points in a scientific data set. Adjacent values of a mathematical function.

Successive array elements are often allocated physically adjacent locations in computer memory.

In Matlab, arrays are referred to as “Vectors” or “Matrices”.

Programming concept called “Array”Programming concept called “Array”

Page 10: Vectors, Arrays and Functions

<9/6/2007> Page 10Physics 241 -- New Mexico Tech

The linspace command also creates a linearly spaced row vector, but instead you specify the number of values rather than the increment.

The syntax is linspace(x1,x2,n), where x1 and x2are the lower and upper limits and n is the number of points.

For example, linspace(5,8,31) is equivalent to [5:0.1:8].

If n is omitted, the spacing is 1.

Example:t=linspace(0,5);x=3*t-4.9*t.^2;plot(t,x)

Vectors and relative motionVectors and relative motion

Page 11: Vectors, Arrays and Functions

<9/6/2007> Page 11Physics 241 -- New Mexico Tech

Magnitude, Length, and Absolute Value of a Vector

In physics, length, magnitude and absolute value of a vector all mean the same thing. In Matlab, they do not.

Magnitude of a vector x having elements x1, x2, …, xn is a scalar, given by √(x1

2 + x22 + … + xn

2), and is the same as the physics definition of magnitude.

length command gives the number of elements in the vector.

The absolute value of a vector x is a vector whose elements are the absolute values of the elements of x.

Page 12: Vectors, Arrays and Functions

<9/6/2007> Page 12Physics 241 -- New Mexico Tech

For example:>> x = [2,-4,5]

• its length is 3 (length(x))

• its magnitude is √[22 + (–4)2 + 52] = 6.7082 (sqrt(x’*x))

• its absolute value is [2,4,5] (abs(x)).

Page 13: Vectors, Arrays and Functions

<9/6/2007> Page 13Physics 241 -- New Mexico Tech

Matrices

A matrix has multiple rows and columns. For example, the matrix

has four rows and three columns.

Vectors are special cases of matrices having one row or one column.

M =2 4 10

16 3 7 8 4 9 3 12 15

Page 14: Vectors, Arrays and Functions

<9/6/2007> Page 14Physics 241 -- New Mexico Tech

Creating Matrices from Vectors

Suppose a = [1,3,5] and b = [7,9,11] (row vectors). Note the difference between the results given by [a b] and [a;b] in the following session:

>>c = [a b];c =

1 3 5 7 9 11>> D = [[1,3,5];[7,9,11]]

alternatively>>D = [a;b]D =

1 3 57 9 11

Page 15: Vectors, Arrays and Functions

<9/6/2007> Page 15Physics 241 -- New Mexico Tech

Array Addressing

The colon operator selects individual elements, rows, columns, or ''subarrays'' of arrays.

Examples:n v(:) represents all the elements of the vector v.n v(2:5) represents the second through fifth

elements; that is v(2), v(3), v(4), v(5). n A(:,3) denotes all the elements in the third column

of the matrix A.n A(:,2:5) denotes all the elements in the second

through fifth columns of A.n A(3,:) denotes all the elements in the third row

Page 16: Vectors, Arrays and Functions

<9/6/2007> Page 16Physics 241 -- New Mexico Tech

You can use array indices to extract a smaller array from another array. For example, if you first create the array B

B =

C =16 3 7

8 4 9

2 4 10 1316 3 7 18 8 4 9 253 12 15 17

then type C = B(2:3,1:3), you can produce the following array:

Page 17: Vectors, Arrays and Functions

<9/6/2007> Page 17Physics 241 -- New Mexico Tech

size(A) Returns a row vector [m n]containing the sizes of them x n array A.

sort(A) Sorts each column of the array A in ascending order and returns an array the same size as A.

sum(A) Sums the elements in each column of the array A andreturns a row vector containing the sums.

max(A) ?

Additional Array Functions

Page 18: Vectors, Arrays and Functions

<9/6/2007> Page 18Physics 241 -- New Mexico Tech

The Workspace Browser

Page 19: Vectors, Arrays and Functions

<9/6/2007> Page 19Physics 241 -- New Mexico Tech

The Array Editor

Page 20: Vectors, Arrays and Functions

<9/6/2007> Page 20Physics 241 -- New Mexico Tech

Element-by-element operations: Table 2.3–1

Symbol

+

-

+

-

.*

./

.\

.^

Examples

[6,3]+2=[8,5]

[8,3]-5=[3,-2]

[6,5]+[4,8]=[10,13]

[6,5]-[4,8]=[2,-3]

[3,5].*[4,8]=[12,40]

[2,5]./[4,8]=[2/4,5/8]

[2,5].\[4,8]=[2\4,5\8]

[3,5].^2=[3^2,5^2]

2.^[3,5]=[2^3,2^5]

[3,5].^[2,4]=[3^2,5^4]

Operation

Scalar-array addition

Scalar-array subtraction

Array addition

Array subtraction

Array multiplication

Array right division

Array left division

Array exponentiation

Form

A + b

A – b

A + B

A – B

A.*B

A./B

A.\B

A.^B

Page 21: Vectors, Arrays and Functions

<9/6/2007> Page 21Physics 241 -- New Mexico Tech

User defined functionsRichard Sonnenfeld

Page 22: Vectors, Arrays and Functions

<9/6/2007> Page 22Physics 241 -- New Mexico Tech

Operations on Arrays

MATLAB will treat a variable as an array automatically. For example, to compute the square roots of 5, 7, and 15, type

>>x = [5,7,15];>>y = sqrt(x)y =

2.2361 2.6358 3.8730

Page 23: Vectors, Arrays and Functions

<9/6/2007> Page 23Physics 241 -- New Mexico Tech

User-Defined Functions

The first line in a function file must begin with a function definition line that has a list of inputs and outputs. This line distinguishes a function M-file from a script M-file. Its syntax is as follows:

function [output variables] = name(input variables)

Note that the output variables are enclosed in square brackets, while the input variables must be enclosed with parentheses. The function name (here, name) should be the same as the file name in which it is saved (with the .m extension).

Page 24: Vectors, Arrays and Functions

<9/6/2007> Page 24Physics 241 -- New Mexico Tech

User-Defined Functions: Example

function z = fun(x,y)u = 3*x;z = u + 6*y.^2;

Note the use of a semicolon at the end of the lines. This prevents the values of u and z from being displayed.

Note also the use of the array exponentiation operator (.^). This enables the function to accept y as an array.

Page 25: Vectors, Arrays and Functions

<9/6/2007> Page 25Physics 241 -- New Mexico Tech

User-Defined Functions: Example (continued)

Call this function with its output argument:

>>z = fun(3,7)z =

303

The function uses x = 3 and y = 7 to compute z.

Page 26: Vectors, Arrays and Functions

<9/6/2007> Page 26Physics 241 -- New Mexico Tech

User-Defined Functions: Example (continued)

Call this function without its output argument and try to access its value. You will see an error message.

>>fun(3,7)ans =

303>>z??? Undefined function or variable ’z’.

Page 27: Vectors, Arrays and Functions

<9/6/2007> Page 27Physics 241 -- New Mexico Tech

User-Defined Functions: Example (continued)

Assign the output argument to another variable:

>>q = fun(3,7)q =

303

You can suppress the output by putting a semicolon after the function call.

For example, if you type q = fun(3,7); the value of qwill be computed but not displayed (because of the semicolon).

Page 28: Vectors, Arrays and Functions

<9/6/2007> Page 28Physics 241 -- New Mexico Tech

The variables x and y are local to the function fun, so unless you pass their values by naming them x and y, their values will not be available in the workspaceoutside the function. The variable u is also local to the function. For example,

>>x = 3;y = 7;>>q = fun(x,y);>>xx =3

>>yy =7

>>u??? Undefined function or variable ’u’.

Page 29: Vectors, Arrays and Functions

<9/6/2007> Page 29Physics 241 -- New Mexico Tech

Only the order of the arguments is important, not the names of the arguments:

>>x = 7;y = 3;>>z = fun(y,x) z =

303

The second line is equivalent to z = fun(3,7).

Page 30: Vectors, Arrays and Functions

<9/6/2007> Page 30Physics 241 -- New Mexico Tech

You can use arrays as input arguments:

>>r = fun([2:4],[7:9])r =

300 393 498

Page 31: Vectors, Arrays and Functions

<9/6/2007> Page 31Physics 241 -- New Mexico Tech

A function may have more than one output. These are enclosed in square brackets.

For example, the function circle computes the area A and circumference C of a circle, given its radius as an input argument.

function [A, C] = circle(r)A = pi*r.^2;C = 2*pi*r;

Page 32: Vectors, Arrays and Functions

<9/6/2007> Page 32Physics 241 -- New Mexico Tech

The function is called as follows, if the radius is 4.

>>[A, C] = circle(4)A =50.2655

C =25.1327

Page 33: Vectors, Arrays and Functions

<9/6/2007> Page 33Physics 241 -- New Mexico Tech

A function may have no input arguments and no output list.

For example, the function show_date computes and stores the date in the variable today, and displays the value of today.

function show_datetoday = date

Page 34: Vectors, Arrays and Functions

<9/6/2007> Page 34Physics 241 -- New Mexico Tech

1. One input, one output:

function [area_square] = square(side)

2. Brackets are optional for one input, one output:

function area_square = square(side)

3. Three inputs, one output:

function [volume_box] = box(height,width,length)

4. One input, two outputs:

function [area_circle,circumf] = circle(radius)

5. No output: function sqplot(side)

Examples of Function Definition Lines