1 advanced matlab vectors and matrices fprintf cell arrays structures flow of control vectorization...

55
1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

Upload: arnold-berry

Post on 27-Dec-2015

240 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

1

Advanced MATLAB

Vectors and matrices

fprintf

Cell arrays

Structures

Flow of control

Vectorization

Functions

Page 2: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

2

Using an Index to Address Elements of an Array

In the C/C++ programming language, an index starts at 0 and elements of an array are addressed with square brackets [∙]:

8 2 -3 7 -1

x[0] x[1] x[2] x[3] x[4]

↑ ↑ ↑ ↑ ↑

In MATLAB, an index starts at 1 and elements of an array are addressed with parentheses (∙):

8 2 -3 7 -1

x(1) x(2) x(3) x(4) x(5)↑ ↑ ↑ ↑ ↑

Page 3: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

3

Columns, Rows, and Pagesfor a 2-Dimensional Array (Matrix)

x(m,n)

m is the row numbern is the column number

x(m,n) is the element of the matrix x that is:

in the mth rowin the nth column

Page 4: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

4

Columns, Rows, and Pagesfor a 3-Dimensional Array

x(m,n,p)

m is the row numbern is the column numberp is the page number

x(m,n,p) is the element of the 3-dimensional array x that is:

in the mth rowin the nth columnon the pth page

Page 5: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% scalars, vectors, matrices, 3-dimensional arrays

a1 = zeros(1,1); % scalardisp(['a1: ',num2str(size(a1))])a2 = zeros(1,4); % vectordisp(['a2: ',num2str(size(a2))])disp(a2)a3 = zeros(2,2); % matrixdisp(['a3: ',num2str(size(a3))])disp(a3)a4 = zeros(2,2,3); % 3-dimensional arraydisp(['a4: ',num2str(size(a4))])

a1: 1 1a2: 1 4 0 0 0 0

a3: 2 2 0 0 0 0

a4: 2 2 3

Page 6: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

6

Exercise

1. Create a row vector of length 5. Use any values you want for the elements.

2. Display the size of this vector.

3. Create a matrix of all 1s that has 3 rows and 4 columns. (Use the function ones.)

4. Display the size of this matrix.

Page 7: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% Editing arrays with parentheses ()

B = [1 2 3 4; 5 6 7 8];disp('before:')disp(B)b = [0 0]';B(:,4) = b;disp('after:')disp(B)

before: 1 2 3 4 5 6 7 8

after: 1 2 3 0 5 6 7 0

7

Page 8: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

8

Exercises

Create a matrix of zeros with 3 rows and 4 columns.

Create a matrix with 2 rows and 2 columns, with all elements equal to 5.

Insert the smaller matrix into the lower right-hand corner of the larger matrix.

Hints: zeros() 5*ones()

Page 9: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% array versus matrix multiplication

a = [1 2; 3 4];disp(a*a) % matrix multiplicationdisp(a.*a) % array multiplication

7 10 15 22

1 4 9 16

Page 10: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

10

% array multiplication, division, and power

x = [1 4; 9 8];y = [1 2; 3 4];disp(x.*y) % array multiplication: .*disp(x./y) % array division: ./disp(x.^2) % array power: .^

1 8 27 32

1 2 3 2

1 16 81 64

Page 11: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

11

Exercise

1. Create a row vector containing 4 elements. Use any values you want.

2. Create a second row vector of the same length, using any values you want.

3. Show the result of an array multiplication of these two vectors.

4. Show the result of doing an array division of one of these vectors by the other.

Page 12: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

12

fprintf Write data to text file

Syntax fprintf(fileID,formatSpec,A1,...,An)

My comments:

fileID not used when printing to Command WindowformatSpec enclosed in single quote marks: ‘string’A1,…,An are variables (or numbers) to be printed

MATLAB Documentation for fprintf

Page 13: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

13

% print pi to 7 decimal places

fprintf('%9.7f\n',pi)% f fixed-point number% a.b field width = a characters% b digits to the right of decimal point% \n newline

3.1415927

Page 14: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

14

% print a column of numbers

x = [1.34, -2.45, 0.91];fprintf('%5.2f\n',x) % There can be 2 characters on left.

1.34-2.45 0.91

Page 15: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

15

Exercise

Print as a fixed-point number to 12 decimal places.

Page 16: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

16

% print signed integers with field width 4

x = [198, -230, 3];fprintf('%4d\n',x)

198-230 3

Page 17: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

17

Exercise

Create a vector containing the (integer) elements: 0, -1, 2, -3.

Print these numbers in a column with right justification.

Page 18: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

18

Cell Arrays

A cell array can combine different data having different data types all in one array.

A cell within a cell array is referenced by an index.

A cell array is frequently an input argument of a function. This permits a collection of data (even of different data types) to be input to the function using a single argument.

Page 19: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% create a cell array using braces {}

y = {'scores',[73,38,81,55]};y{3} = 'success';celldisp(y)

y{1} = scores y{2} = 73 38 81 55

y{3} = success

19

Page 20: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% What is in the second cell of the cell array y?

disp(y(2))

[1x4 double]

20

Page 21: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% What values are in the second cell of the cell array y?

disp(y{2})

73 38 81 55

21

Page 22: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% print values in the cell array y

fprintf('%s: ',y{1})fprintf('%2d ',y{2})fprintf('\n')

scores: 73 38 81 55

22

Page 23: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% create a cell array using the function cell()

x = cell(1,2);x{1} = 'salary';x{2} = 45000;celldisp(x)

x{1} = salary x{2} = 45000

23

Page 24: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

24

Exercise

1. Create a cell array that contains three cells: A string containing your first name, An unsigned integer (uint8) containing your age, and A vector containing any two numbers between 0 and 1.

2. Use celldisp to display the contents of the cell array.

3. Extract the string in the first cell.

4. Extract your age.

5. Extract the first number in the vector.

Page 25: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

25

Structures

A structure can combine different data having different data types under one banner.

Each component of a structure is called a field.

A structure array is an array, each element of which is a structure, and all structures in the structure array have the same set of fields.

Page 26: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% simple structure

a.label = 'x';a.vect = 0:5;disp(a)

label: 'x' vect: [0 1 2 3 4 5]

26

Page 27: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

27

Exercise

1. Create a structure that contains two fields: a name (string) and a number. Place any values you want into these fields.

2. Use disp to display the fields of this structure.

Page 28: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% create structure array using function struct()

c = struct('label',{'x','y'},'vect',{0:5,0:10});disp(c)disp(c(1))disp(c(2))

1x2 struct array with fields: label vect

label: 'x' vect: [0 1 2 3 4 5]

label: 'y' vect: [0 1 2 3 4 5 6 7 8 9 10]

28

Page 29: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% create 1 x 2 structure array

c = struct('class',{71,72},'language',{'C','MATLAB'});for n = 1:2 fprintf('ECE %2d: %s\n',c(n).class,c(n).language)end

ECE 71: CECE 72: MATLAB

29

Page 30: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% structure array

b(1).label = 'x';b(2).label = 'y';b(1).vect = 0:5;b(2).vect = 0:10;disp(b)disp(b(1))disp(b(2))

1x2 struct array with fields: label vect

label: 'x' vect: [0 1 2 3 4 5]

label: 'y' vect: [0 1 2 3 4 5 6 7 8 9 10]

30

Page 31: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

31

Exercise

1. Create a 1x2 structure array that contains two fields: a string containing a first name, and a number containing an age (in years)Provide a value for each field of each structure in the structure array.

2. Use a loop and the fprintf function to print the data in the structure array.

Page 32: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

32

Flow of Control

Redirectionifelseelseif

Loopsfor

Page 33: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

33

Relational Operators

x == y equal to

x ~= y not equal to

x < y less than

x <= y less than or equal to

x > y greater than

x >= y greater than or equal to

Page 34: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

34

Logical Operators

&& (short-circuit) and

|| (short-circuit) or

Page 35: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% if

for k = 0:3 if k == 2 disp(k) endend

2

35

Page 36: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% if and else

for k = 0:3 if k >= 2 disp(k) else disp([num2str(k),' < 2']) endend

0 < 21 < 2 2

3

36

Page 37: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% elseif

for k = 0:3 if k < 2 disp([num2str(k),' < 2']) elseif k == 2 disp(k) else disp([num2str(k),' > 2']) endend

0 < 21 < 2 2

3 > 2

37

Page 38: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% or

for k = 0:4 if k < 2 || k > 3 disp(k) endend

0

1

4

38

Page 39: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% and (input number is 3)

x = input('number: ');if x >= 1 && x <= 5 disp('between 1 and 5')end

between 1 and 5

39

Page 40: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

40

Exercise

Create a script that does the following:

1. Get a number (x) from the user.2. If x is less than or equal to 3, set y to 3.3. If x is greater than or equal to 6, set y to 6.4. Otherwise, set y to x.5. Display y.

Page 41: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% Compare 2 methods of printing a vector

ticfor k = 0:9 % within this loop, k is a scalar fprintf('%1d ',k)endfprintf('\n')toc

ticm = 0:9;fprintf('%1d ',m) % This is preferred. It is faster.fprintf('\n')toc

0 1 2 3 4 5 6 7 8 9 Elapsed time is 0.000264 seconds.0 1 2 3 4 5 6 7 8 9 Elapsed time is 0.000077 seconds.

41

Page 42: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% Add all even integers 0 through 100

x = 0;for m = 2:2:100 % even integers, 2 through 100 x = x + m;endfprintf('%4d\n',x)

2550

42

Page 43: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

43

Exercise

Calculate the sum of all odd integers from 1 through 101.

Page 44: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

44

Vectorization

Preallocation of memory

Vectorizing Loops

Page 45: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% Preallocation of memory

tic % SLOW: frequent lengthening of xx(1) = 1;x(2) = 1;for n = 3:100000 x(n) = x(n-1)*x(n-2);endtoc

tic % FAST: preallocation of memory for xy = ones(1,100000);for n = 3:10000 y(n) = y(n-1)*y(n-2);endtoc

Elapsed time is 0.526046 seconds.Elapsed time is 0.021451 seconds.

45

Page 46: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% Vectorizing a loop: linspace

tic % slowphi = 0;dphi = 2*pi/100;g = zeros(1,1001);for n = 1:1001 g(n) = sin(phi); phi = phi + dphi;endtoc

tic % fastphi = linspace(0,20*pi,1001);h = sin(phi);toc

Elapsed time is 0.002522 seconds.Elapsed time is 0.000136 seconds.

46

Page 47: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

47

Exercise

Here is one way to generate samples of a sinewave:

for n = 1:8 x(n) = sin(pi*(n-1)/4);end

Enter the above code and display the results. Then vectorize this code and verify that your vectorized code gives the same results.

Page 48: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

48

Functions

Function m-file

Local variables

Functions with multiple inputs/outputs

Page 49: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

function v = sphereVol(r)% calculates the volume of a sphere% input r = radius% output v = volumec = 4/3;v = c*pi*(r^3);end % sphereVol

49

Page 50: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

50

Local Variables

Variables appearing in a function are local. These local variables do not appear in the MATLAB workspace and are not visible outside of the function in which they occur. For example, a variable c in the MATLAB workspace will be unaffected by a (local) variable c that appears within a function. Within the function, the local c is recognized and the workspace c is not. When the function returns, the local c is forgotten and the workspace c is again recognized.

The input arguments of a function have local names. When the function returns, these local names are forgotten.

The output variables of a function have local names. The values of these output variables are returned to the caller; however, the local names of these output variables are forgotten.

Page 51: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% Script that calls the function sphereVol

c = 2;radius = 1;vol = sphereVol(radius);fprintf('c = %3.1f, vol = %5.2f\n',c,vol)whos

c = 2.0, vol = 4.19 Name Size Bytes Class Attributes

c 1x1 8 double radius 1x1 8 double vol 1x1 8 double

51

Page 52: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

52

Exercise

1. Create a function m-file that computes the surface area of a sphere. There will be one input, the radius, and one output, the surface area.

2. Create a script m-file that calls your function m-file.

Page 53: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

function [radius, angle] = rect2polar(x, y)% converts the (x,y) coordinates to polar coordinates% inputs: rectangular coordinates x and y% outputs:% radius = distance from origin% angle = angle (rad) measured counterclockwise from x axisradius = sqrt(x.^2 + y.^2);angle = atan2(y,x);end % rect2polar

53

Page 54: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

% Rectangular to polar coordinate conversions

x = linspace(1,0,5);y = linspace(0,1,5);[r,theta] = rect2polar(x,y);table = [x; y; r; theta];fprintf(' x y r theta\n')fprintf('%5.2f %5.2f %5.3f %5.3f\n',table)

x y r theta 1.00 0.00 1.000 0.000 0.75 0.25 0.791 0.322 0.50 0.50 0.707 0.785 0.25 0.75 0.791 1.249 0.00 1.00 1.000 1.571

54

Page 55: 1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions

55

Exercise

1. Create a function m-file that takes two inputs and produces two outputs, where the inputs are the polar coordinates ( and ) of a point in 2-dimensional space and the outputs are the rectangular coordinates ( and ).

2. Make sure to include some comment lines, including an H1 line.

3. Create a script m-file that calls your function m-file.