CS 211 Lesson 3
Creating MATLAB Programs
Quote:
I don't measure a man's success by how high he climbs but by how high he bounces when he hits bottom. General George S. Patton
Lesson Objectives:
Be able to use the disp() function to display values
Be able to use the fprintf() function to display values
Be able to initialize a variable using the input() function
Be able to create, save, and run a simple MATLAB program
Understand the importance of program comments
Know the requirements for CS211 MATLAB programs
Lesson:
I. MATLAB Concepts
A. Displaying output on the screen
Use either the disp() function or the fprintf() function to display output to the screen.
The disp() function is very easy to use but provides limited control of output formatting.
The disp() function displays exactly one value/variable to the screen.
The disp() function always uses one or more lines of output -- i.e., it always generates a carriage return at the end of its output.
The disp() function is particularly convenient for displaying vectors, matrices, and complex numbers because it displays the entire array with a single function call.
Some simple examples:
disp(5)
disp(pi)
disp(3.1415926)
disp(1 + 5i)
myArray = [1 2; 3 4]; disp(myArray)
disp('hi there')
You can create a single string from multiple strings using string concatenation. The MATLAB function num2str() will take a number and convert it into a string. Notice that the brackets [ ] create the single string and are required. For example:
disp( ['pi = ' num2str(pi)] )
disp( ['It is ' num2str(Distance) ' miles to the river.'] )
In general, use disp() when you do not care about the exact format of the output
The fprintf() function is more complicated to use but it allows you precise control over the output formatting.
The fprintf() function receives one or more arguments
the first argument must be a format string
subsequent arguments are values to be inserted into the format string, each corresponding to a format specifier in the format string
The fprintf() function displays the format string to the screen exactly as it is specified, and replaces each format specifier with a value from the fprintf() function's parameter list. (See examples below.)
Special escape sequences, beginning with the backslash '\' character, are used to represent "non-printable" characters. The most commonly used escape sequences are:
\n a "carriage return" -- it starts a new line of output (or ends the current line of output) \t a "tab" -- spaces over to the next tab stop A format specifier begins with the % character and is followed by other characters that precisely describe how the corresponding output value will be formatted. A format specifier always contains a single letter (format Descriptor) that describes the data type of the output value. The most commonly used data types are:
%d display the value as an integer (no fractional part) %e display the value in exponential format (3.23e5) %f display the value in floating point format (3.451) %g display the value showing only significant digits -- use this most of the time %s display the value as a string - a series of ASCII characters %c display the value as a single ASCII character A format specifier is defined exactly as follows, where the modifier, fieldWidth, and precision values are all optional:
% modifier fieldWidth . precision formatDescriptor
Modifiers Description - left-justifies output in its field (no minus sign means right-justify) + always print a plus or minus sign with the output value 0 pad the field with leading zeros fieldWidth - an integer that specifies how many spaces to use for the value. If the field is too small, the fprintf() function will expand the field to make it large enough to display the entire value.
precision - only applies to floating point numbers. It specifies how many digits to display after the decimal point.
Some simple examples of fprintf() follow:
fprintf('This is a string with no data values.')
fprintf('This is a string followed by a new line character.\n')
Age = 20; fprintf('I am %d years old.\n', Age)
fprintf('pi to 2 decimal places = %0.2f.\n', pi)
fprintf('pi to 10 decimal places = %0.10f.\n', pi)
Name = 'Fred'; fprintf('My name is %s and I am %d years old.\n', Name, Age)
Within a program you should suppress output of intermediate values by ending all assignment statements with a semicolon. For example:
Age = 18;
Age = input('Enter your age: ');
Matrix = zeros(10);
B. Getting input from the user
A program may use the input() function to get a value from the user.
The input() function will always be on the right-hand-side of an assignment statement.
The argument of the input() function is a prompt string.
A prompt string is text displayed to the user requesting input.
Prompt strings should be descriptive to help the user know what input is expected.
By default, the input() function expects the user to enter a numeric value.
To get a string value using the input function, you must include a second argument, 's'.
Some examples of using input() follow:
Age = input('Please enter your age: ');
Height = input('Please enter your height in inches: ');
First_name = input('Please enter your first name: ', 's');
C. Creating a MATLAB program
In CS211, a MATLAB program is a user-defined MATLAB function stored in an m-file.
In CS211, we will not use script files, which are m-files without function headers (more details on this later).
A basic MATLAB program will consist of:
a function heading
a program header comment block
MATLAB code and comments
The file hello.m contains an example of a very simple MATLAB program and is shown below.
A program function's name should be the same as the m-file name in which it is stored. For example, a program/function named lab1 should be saved in the file lab1.m.
A function's name should be descriptive of what the function does (or follow CS211 requirements, e.g., using names like lab1).
Include the parentheses after the function's name to distinguish it from a variable name (even though the parentheses are not required).
The MATLAB help function will display the program comment header block (comment lines immediately following the function header)
There are several ways to run a program:
Type its name at the command line prompt (the program must be saved in a file that is stored in a folder in your MATLAB search path).
Click on the run icon while in the MATLAB editor.
Press the F5 key while in the MATLAB editor.
A violation of the rules of the MATLAB programming language results in a syntax error in a program.
The command interpreter will catch and, as best as it can, identify syntax errors when you attempt to run your program.
If an error message looks like a "hyper-link", you can click on the error message to "jump" directly to the location in your program where the error was recognized.
In summary, the basic steps to create and execute a new MATLAB program are as follows:
Open a new m-file (File --> New --> M-File).
Copy the program header template into your new m-file.
Enter a function name on the first line (e.g., lab3a).
Save your file as a m-file (e.g., lab3a.m).
Update the comment header block with the appropriate information.
Add code and comments below the comment header block.
Re-save your m-file.
Run and test your program.
Correct any errors you find.
Re-save your m-file.
Repeat the last three steps as necessary.
II. Good Programming Practices
For output:
Typically use fprintf() for all output statements in your program that produce problem specific output.
Typically use disp() only when you are debugging for "quick and dirty" output to help find errors.
When you are not sure what precision a computed value will
have, display it with the %g format
descriptor.
For input:
Always use a very descriptive prompt with the
input() function.
When creating programs:
Always include a fully descriptive program header comment block under the function heading.
Comments included in an m-file are as important as the MATLAB code!
Comments are essential for making a program maintainable (the greatest cost for real programs).
Comments should document who wrote a program, when it was written, what it does, and how to use it.
Comments assume that the reader of the comments is an experienced programmer who knows MATLAB -- comments should not explain MATLAB concepts
Comments should allow a maintenance programmer (someone who will potentially modify the program at a future date) do to the following:
Identify the original author of a program -- so they can go ask questions.
Provide an organization to the code so that blocks of code are easily found and identified.
Explain complex or out of the ordinary algorithms used in the code.
For CS211, you must use the Program Header Comment Block shown above. (Copy and paste the header block from the hello.m file and save it to a "HeaderCommentsTemplate.m" file. Do not re-type the comment block for each new file.)
The number of comments required in the body of a program is a judgment call - ask your instructor for guidance. Good variable names can sometimes make comments unnecessary.
Make the code of a program as easy to read and understand as possible by:
Grouping statements that work together into blocks of code (no blank lines between them).
Separating blocks of code with a blank line.
Using descriptive and self-documenting variable names.
Including appropriate in-line comments.
III. Algorithms
(None for this lesson)
Lab Work: Lab 3
References: Chapman Textbook: sections 2.2, 2.6, 8.6