
6/21/2018 C/C++ Programming for Engineers: Matlab Scripts and Functions John T. Bell Department of Computer Science University of Illinois, Chicago Reading Review Which of the following would multiply the cosine of X times the common logarithm of X, when X is given in degrees? A. cos( X ) * log( X ) B. cos( X ) * log10( X ) C. cosd( X ) * log( X ) D. cosd( X ) * log10( X ) E. cos( X degrees ) * commonLog( X degrees ) 2 1 6/21/2018 Matlab Script Files • Any command that can be run in Matlab can be placed in an ordinary text file ( with a .m extension ) and run as a Matlab script. • The easiest way to do this is to use Matlab’s built-in editor and drag commands from command history into the script, & then edit. • Run the script by typing the script name, or by pressing the “run” button in the script editor. 3 Special Characters in Scripts • The % percent sign is used to create comments, from the % to the end of the line. – %{ Large block comments in braces and % %} • The ; semi-colon at the end of the line suppresses the display of the command. • Three dots, … , at the end of a line … are used to continue … long lines onto the next line. 4 2 6/21/2018 Good Programming Style • EVERY well-written program should be begin with a multi-line comment, providing the author’s name, a description of the program, and when it was written. • Use descriptive variable names – “temperature”, not “T” or “temp”. • Ample spaces and indentation. Be consistent. • Generous comments. 5 Basic Input in Matlab • The input( ) command displays a prompt and receives an answer. For example: o speed = input( ‘Please enter a speed, in mph: ‘ ); • Use ‘s’ as a second argument when reading in character strings: o name = input( ‘What is your name?’, ‘s’ ); 6 3 6/21/2018 Preview What does the %g format specifier do in fprintf( ) ? A. It uses fixed-point format. B. It uses exponential notation. C. It uses engineering notation. ( Exponential in powers of 3, e.g. kilo, Mega, micro, etc. ) D. It uses either fixed-point or exponential notation, whichever “fits best” for the value being printed. E. It generates an error, since the % is for comments. 7 Simple Matlab Format Options • format long / short – Adjusts # of digits shown. • format compact / loose – single/double spacing. • format bank – Dollars and cents • format rat – Ratio of two integers • help format – Shows more options. 8 4 6/21/2018 Formatted Output in Matlab • The fprintf( ) command prints strings: – fprintf( ‘This program plots sine waves.’ ); • New lines start (only) when \n is printed: – fprintf( ‘This will print’ ); – fprintf( ‘ all on one line.\n’ ); • This will print all on one line. – fprintf( ‘This will print\n on\n three lines.\n’ ); • This will print • on • three lines. 9 Format Specifiers in fprintf( ) • Whenever a % is encountered in the output string, fprintf( ) prints a data value: – fprintf( ‘The result is %f mpg.\n’, mileage ); 10 5 6/21/2018 Format Specifiers in fprintf( ) Operator Prints Description %f fixed-point f is for fixed-point. d is for decimal integer. The use of 'd' is due to historical reasons, and is slightly misleading because a decimal number %d integer could have a fractional part. In MATLAB, %d means decimal integer which does not have a fraction. i is for integer. This operator is identical to %d when %i integer formatting output. %c character c is for character. %s string s is for string. 11 Special Characters Special character Description \n Prints a new line. Two single quotation marks print a single quotation mark. Note that '' a single quotation mark alone would instead indicate the end of the format string. Two percent characters print one percent character. Note that a %% single % character would instead indicate the start of a formatting operator like %f. Two backslash characters print one backslash character. Note that a \\ single backslash character would instead indicate the start of a special character sequence like \n. \t Prints a tab. 12 6 6/21/2018 Floating Point Formats Table 3.6.1: Floating-point number formatting operators. Operator Description %f Fixed-point notation, 109.42 Scientific notation with lowercase e, %e as in 6.02e+23, 3.141593e+00 %g Either %f or %e, whatever is shorter Scientific notation with capital E, as %E in 6.02E+23, 3.141593E+00 Either %G or %E, whichever is %G shorter, 6.02E+23, 3.141593 13 Preview What happens if a Matlab workspace contains a variable X, and then a script is run that creates a new variable X and gives it a value? A. There will now be two variables named X. B. The workspace X will be wiped out, and replaced with a new X. C. The X created in the script will only exist while the script runs, and will then disappear. D. The script X will be automatically given a different name. E. An error will occur, since two variables can’t have the same name. 14 7 6/21/2018 A Problem with Scripts • Commands executed from a script run in the same scope as the command window. – Script commands can clobber command-window variables with the same variable names. – Script variables can clutter up the workspace unnecessarily. – Solve this by writing functions instead of scripts. 15 Function Scope • Functions operate in their own space. • Variables defined within functions are totally independent of any variables defined in the command window, even if they happen to have the same name. • Because of this, values have to be passed in to functions, and the results passed back. 16 8 6/21/2018 Matlab Function Syntax • The first ( non-comment ) line of a Matlab function file MUST have the following format: function [out1, out2, …] = funcName( in1, in2,… ) • ‘function’ is a required key word. • ‘funcName’ must match the name of the file, e.g. ‘funcName.m’ • The ‘in’ and ‘out’ variables can have any names. See next slides for details. 17 Matlab Function Inputs • The variables in parentheses are called input parameters or arguments, used to “catch” the values passed in to the function. • Any changes made by a function to its input parmeters are local to the function, and do not affect the calling program. • If a function does not take any input arguments, the parentheses are still required. 18 9 6/21/2018 Matlab Function Outputs • The [ out1, out2, … ] = format is for functions that return multiple results. – If a function returns a single result, the [ ] square brackets are not required. – If a function does not return any results, then the equals sign should also be omitted. • The program that called the function gets its results through the output parameters. 19 Matlab Function Help Comments • Every Matlab function should contain a “help” comment, which is the first comment block after the “function” line. • The help comment is displayed whenever one types “help” for the function in question. ( The first line is displayed by lookfor. ) function [ finBalance, interest ] = BalanceWithInterestBoth( rate, initBalance ) % Calculates the final balance of an investment with compound interest. % Inputs: rate -- Interest rate, initBalance -- Initial balance. % Output: finBalance -- Final balance. 20 10 6/21/2018 Matlab Function Operation • The code within a Matlab function is basically the same as a Matlab script. • Sometime before the function returns, it must assign values to all the output parameters. • The ‘return;’ statement ceases execution of the function, and returns control back to the calling program. No function code is executed after a return statement. 21 Calling Matlab Functions • User-written Matlab functions are called by name, the same way that Matlab library functions are called. • Values or variables must be passed in to the function input parameters. • Variables must be provided to receive the output results. 22 11.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages11 Page
-
File Size-