Presentation is loading. Please wait.

Presentation is loading. Please wait.

MATLAB Programming fprintf Cell arrays Structures Flow of control Vectorization Functions 1.

Similar presentations


Presentation on theme: "MATLAB Programming fprintf Cell arrays Structures Flow of control Vectorization Functions 1."— Presentation transcript:

1 MATLAB Programming fprintf Cell arrays Structures Flow of control Vectorization Functions 1

2 fprintf Write data to text file Syntax fprintf(fileID,formatSpec,A1,...,An) My comments: fileID not used when printing to Command Window formatSpec enclosed in single quote marks: ‘string’ A1,…,An are variables (or numbers) to be printed MATLAB Documentation for fprintf 2

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

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

5 Exercise 5

6 % print signed integers with field width 4 x = [198, -230, 3]; fprintf('%4d\n',x) 198 -230 3 6

7 Exercise Create a vector containing the (integer) elements: 0, -1, 2, -3. Print these numbers in a column with right justification. 7

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

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

10 % What is in the second cell of the cell array y? disp(y(2)) [1x4 double] 10

11 % What values are in the second cell of the cell array y? disp(y{2}) 73 38 81 55 11

12 % print values in the cell array y fprintf('%s: ',y{1}) fprintf('%2d ',y{2}) fprintf('\n') scores: 73 38 81 55 12

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

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

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

16 % simple structure a.label = 'x'; a.vect = 0:5; disp(a) label: 'x' vect: [0 1 2 3 4 5] 16

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

18 % 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] 18

19 % 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: C ECE 72: MATLAB 19

20 % 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] 20

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

22 Flow of Control Redirection if else elseif Loops for 22

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

24 Logical Operators && (short-circuit) and || (short-circuit) or 24

25 % if for k = 0:3 if k == 2 disp(k) end 2 25

26 % if and else for k = 0:3 if k >= 2 disp(k) else disp([num2str(k),' < 2']) end 0 < 2 1 < 2 2 3 26

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

28 % or for k = 0:4 if k 3 disp(k) end 0 1 4 28

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

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

31 % Compare 2 methods of printing a vector tic for k = 0:9 % within this loop, k is a scalar fprintf('%1d ',k) end fprintf('\n') toc tic m = 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. 31

32 % Add all even integers 0 through 100 x = 0; for m = 2:2:100 % even integers, 2 through 100 x = x + m; end fprintf('%4d\n',x) 2550 32

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

34 Vectorization Preallocation of memory Vectorizing Loops 34

35 % Preallocation of memory N = 1000000; tic % frequent lengthening of x x(1) = 1; x(2) = 2; for n = 3:N x(n) = x(n-1)*x(n-2); end toc tic % FASTER: preallocation of memory for x y = ones(1,N); y(2) = 2; for n = 3:N y(n) = y(n-1)*y(n-2); end toc Elapsed time is 5.386562 seconds. Elapsed time is 2.242842 seconds. 35

36 % Vectorizing a loop: linspace tic % slow phi = 0; dphi = 2*pi/100; g = zeros(1,1001); for n = 1:1001 g(n) = sin(phi); phi = phi + dphi; end toc tic % fast phi = linspace(0,20*pi,1001); h = sin(phi); toc Elapsed time is 0.002522 seconds. Elapsed time is 0.000136 seconds. 36

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

38 38 Functions Function m-file Local variables Functions with multiple inputs/outputs

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

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

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

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

43 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 axis radius = sqrt(x.^2 + y.^2); angle = atan2(y,x); end % rect2polar 43

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

45 Exercise 1. 2.Make sure to include some comment lines, including an H1 line. 3.Create a script m-file that calls your function m-file. 45


Download ppt "MATLAB Programming fprintf Cell arrays Structures Flow of control Vectorization Functions 1."

Similar presentations


Ads by Google