17 - Script and Function Files and Managing Data

17 - Script and Function Files and Managing Data -...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Engineering 101 Quote of the Day By nature, we are nearly alike; by practice, we get to be wide apart. - Confucius Script/Function Files and Managing Data display_test.m Script Files A script file is created by typing your command line inputs into a file and saving it with a .m suffix (multi_plots.m) (multi_plots.m) Variables in a script file have global scope Variables in a function file have local scope Output display( ) is called when you don't include a semicolon after a MATLAB line where an assignment occurs disp( data ) will output only the data to the screen. Unlike display( ), disp( ) does not put a ), "data =" message before the output. disp() Example: x = [5 : 9]; disp(x); Output: 5 6 7 8 9 Output: Example: disp() name = `Xena'; name2 = `: Warrior Princess'; disp([`My name is ' name name2]); My name is Xena: Warrior Princess 1 Which will output the following 3 rows of text? 00000000011111111112222222 12345678901234567890123456 abcdefghijklmnopqrstuvwxyz Formatted output Sometimes you want to specify the output precisely. The fprintf( ) command allows you to specify a formatting string. fprintf(format_string, variables) will print the values in the variables as specified in the format_string. Places for numbers in the format string are specified like: %-12.5e %{+,%{+,-,0}{field width}.{precision}{conversion} +: include sign, -: left justify, 0: pad with zeros 1 2 S = char(X) converts the array X that contains nonnegative integers representing character codes into a MATLAB character array. 3 4 Formatted output Conversion characters: %c %d %e %E %f %s %u single character decimal number exponential notation (lowercase e) exponential notation (uppercase E) fixed point notation string decimal (unsigned) \t \n \\ \% Formatted output Special characters in the format string tab new line backslash percent fprintf() Example: num = 1234.56789; fprintf(`The number is %f !',num); Output: The number is 1234.56789 ! Output: Example: fprintf() num = 1234.56789; fprintf(`The number is %e !',num); The number is 1.2345678e+003 ! 2 fprintf() Example: num = 1234.56789; fprintf(`The number is %.1f !',num); Output: The number is 1234.6 ! Output: Example: fprintf() num = 1234.56789; fprintf(`The number is %08.1f !',num); The number is 001234.6 ! Which program, given a list of inventory item names (prod) and a list of the quantity and price, will print a list in the format: item hammer nails saw quantity 20 2000 5 price 12.50 0.10 25.00 %{+,%{+,-,0}{field width}.{precision}{conversion} - : left justify %d decimal number %f fixed point notation %s string \n new line Making Your Own MATLAB Functions You can use an M-File to create a new function MThe syntax for defining a MATLAB function is: function [outputs] = functionname (inputs) [outputs] (inputs) % H1 Line % Help text % Help text Body 1 2 3 C++ function and corresponding MATLAB function double multiply( double a, double b){ return a*b; } function c = multiply( a, b) c = a*b C++ function and corresponding MATLAB function void printthem( double a, double b){ cout << a << endl; cout << b << endl; return; } function printthem( a, b) a b 3 C++ function and corresponding MATLAB function void means( double a, double b, double &c, double & d){ c = sqrt(a*b); d = 0.5*(a+b); return; } function [c, d] = means( a, b) c = sqrt(a*b); d = 0.5*(a+b); Exercise Which is the MATLAB equivalent of the C++ function? void process (vector <double> list, double & g, vector <double> & h) { for(int x=0; x<list.size(); x++){ h[x] = list[x]*3.0; if (x==0 or g < h[x]) g= h[x]; } } 1- 2- 3- Subfunctions You can actually have more than one function defined in your function .m file The first defined function is the primary function and should represent the name of the file Each subsequent function is called a subfunction and can be typed in any order Subfunctions Each subfunction has its own scope and local variables Each subfunction can call the primary and other subfunctions from within the current function file Other function/script files can only call the primary function Example: Subfunctions function [a, b] = findStuff (A) a = countThis(A); b = countThat(A); function count = countThis(A) count = 0; for i = 1:length(A) if ~(mod(A(i), 3)) count = count + 1; end end function count = countThat(A) count = 0; for i = 1:length(A) if mod(A(i), 3) count = count + 1; end end MATLAB Functions There are a large number of predefined mathematical functions in MATLAB. If you apply a function defined for a scalar value to a vector or matrix, the function is applied to each value. x = [ 0 0.5*pi pi 1.5*pi 2.0*pi ]; y = sin(x); % y == [ 0 1 0 1 0 ] 4 Trigonometric Functions sin(x) cos(x) tan(x) asin(x) acos(x) atan(x) atan2(y,x) sine, x in radians cosine, x in radians tangent, x in radians Arcsine in radians Arccos in radians Arctan in radians Arctan(y/x) over all quadrants Other Mathematical Functions abs(x) angle(x) exp(x) log(x) mod(x,y) sqrt(x) absolute value the phase angle of a complex number ex natural log of x modulo function (remainder) square root Rounding Functions ceil(x) fix(x) floor(x) round(x) Ceiling (rounds up) Rounds toward zero Rounds down Rounds to nearest integer char(x) String Conversions Converts numbers to characters using ASCII Converts characters to numbers Converts an integer number into a character string Converts a real number into a character string with a decimal Converts a string into a number double(x) int2str(x) num2str(x) str2num(s) Exercise Convert from MATLAB function to C++ procedure function [x, y] = splitstring(a) splitstring(a) s = floor(length(a)/2) ; x = a(1 :s) ; y = a(s+1:(length(a)-s)); a(s+1:(length(a)- Writing and Debugging Programs in MATLAB Suppose we want to write a program in MATLAB that prompts the user for the initial height and velocity of a ball at time zero and a duration. The program then plots the height and velocity of the ball over the duration. v = g * t + v0 h = g * t2/2 + v0 * t + h0 1 2 3 5 Writing and Debugging Programs in MATLAB It is important to start by commenting your program % gravity.m % This file computes the % trajectory of a ball % Writing and Debugging Programs in MATLAB It is important to start by commenting your program The comments should include a glossary of your identifiers % gravity.m % This file computes the % trajectory of a ball % % g = gravitational accel % x = positions of ball % x0 = initial position % v = velocities of ball % v0 = initial velocity % t = time % tmax = duration Writing and Debugging Programs in MATLAB Comment individual segments of code % gravity.m % This file computes the % trajectory of a ball % % g = gravitational accel % x = positions of ball % x0 = initial position % v = velocities of ball % v0 = initial velocity % t = time % tmax = duration % set the gravitational accel g = -9.8; Writing and Debugging Programs in MATLAB Comment individual segments of code Get input from the user % v0 = initial velocity % t = time % tmax = duration % set the gravitational accel g = -9.8; % get input from user x0 = input(`Initial height:'); v0 = input(`Initial velocity:'); tmax = input(`Duration:'); Writing and Debugging Programs in MATLAB Comment individual segments of code Get input from the user Make time array % v0 = initial velocity % t = time % tmax = duration % set the gravitational accel g = -9.8; % get input from user x0 = input(`Initial height:'); v0 = input(`Initial velocity:'); tmax = input(`Duration:'); % set up time t = 0:tmax/100:tmax; Writing and Debugging Programs in MATLAB Comment individual segments of code Get input from the user Make time array Calculate velocity and position % get input from user x0 = input(`Initial height:'); v0 = input(`Initial velocity:'); tmax = input(`Duration:'); % set up time t = 0:tmax/100:tmax; %calculate velocity v = v0 + g * t; % calculate position x = x0 v0 .* t + 0.5.* g .* t .^ 2; 6 Writing and Debugging Programs in MATLAB Now graph the results % set up time t = 0:tmax/100:tmax; %calculate velocity v = v0 + g * t; % calculate position x = x0 v0 .* t + 0.5.* g .* t .^ 2; % plot position and velocity plot(t, x, `r-', t, v, `b:'); xlabel(`time (s) '); ylabel(`h(m) /v(m/s)'); legend(`height', 'velocity'); grid on; gravity.m Writing and Debugging Programs in MATLAB % set up time t = 0:tmax/100:tmax; %calculate velocity v = v0 + g * t; % calculate position x = x0 v0 .* t + 0.5.* g .* t .^ 2; % plot position and velocity plot(t, x, `r-', t, v, `b:'); xlabel(`time (s) '); ylabel(`h(m) /v(m/s)'); legend(`height', 'velocity'); grid on; If you make a typo MATLAB will try to provide information to help you debug. Save/Load Sometimes during a MATLAB session or in the course of executing an M-File program there are one or more Mmatrices that have data you would like to save to use later possibly in a different context. save can be called with or without parentheses. If it is called with parentheses then each argument is a string. Examples save save save( ) What it does Save all workspace variables in a file called matlab.mat save Examples save mydata.mat save(`mydata.mat') What it does Save all workspace variables in a file called mydata.mat Examples save save mydata.mat X Y save(`mydata.mat', `X', `Y') What it does Save the data in X and Y in a file called mydata.mat 7 save Examples save mydata.txt X Y -ascii save(`mydata.txt', `X', `Y', `-ascii') `What it does Save the data in X and Y in a file called mydata.txt in ASCII format. The default is a binary format that is not easily readable outside of MATLAB. Examples save save mydata.txt X* -ascii save(`mydata.txt', `X*', `-ascii') `What it does Save the data in any matrix starting with an X in mydata.txt in ASCII format. save Examples save mydata.txt X* -ascii -double save(`mydata.txt', `X*', `-ascii -double') `What it does Save the data in any matrix starting with an X in mydata.txt in 16 digit ASCII format. The default is 8 digits. save CAVEATS Data must be 2D character or data array Imaginary part of complex numbers is lost If using load to read data all items must have the same number of columns All data is written as floating point numbers; there is no record of which were characters and which were floating points. Saving as ASCII loses all data names load Examples load load( ) What it does Load all workspace variables from a file called matlab.mat Examples load load mydata.mat load(`mydata.mat') What it does Load all workspace variables from a file called mydata.mat (Matlab assumes binary format) 8 load Examples load mydata.ext load(`mydata.ext') What it does Load all workspace variables from a file called mydata.ext (If file suffix is anything but .mat, then Matlab assumes ASCII format) Examples load load mydata.ext -mat load(`mydata.ext', `-mat') `What it does Load all workspace variables from a file called mydata.ext that is in binary format. load Examples load mydata.mat -ascii load(`mydata.mat', `-ascii') `What it does Load all workspace variables in a file called mydata.mat that is in ASCII format. load Examples load mydata.mat X load(`mydata.mat', `X') What it does Load the matrix X from a file called mydata.mat load Examples load mydata.mat X Y load(`mydata.mat', `X', `Y') What it does Load the matrices X and Y from a file called mydata.mat Examples load load mydata.mat X* load(`mydata.mat', `X*') What it does Load the matrices that start with an X from a file called mydata.mat 9 General File I/O There are also several commands provided to write to files on disk. To open a file: fid = fopen( filename, permission ); fid = fopen(`Myfile.txt', `r'); To close a file: close(fid) `r' `w' `a' `r+' `w+' `a+' Permissions read only write to new file append to new or existing file read and write read and overwrite read and append fprintf with files You can use fprintf to output to files fid = fopen(`Myfile.txt', `w'); fprintf(fid, `It is %.2f meters long', num); fscanf There is an analogous command called fscanf to get data fid = fopen(`Myfile.txt', `r'); decnum = fscanf(fid, `%d'); Next Lecture MATLAB Programming I 10 ...
View Full Document

This note was uploaded on 05/04/2010 for the course ENGIN 101 taught by Professor Jeffringenberg during the Spring '07 term at University of Michigan.

Ask a homework question - tutors are online