Learning Objectives
At the end of this class you should be able to
- Use
fprintfto display text messages in the command window - Use
fprintffor display formatted values of numeric variables in the command window - Write a
forloop to traverse a vector - Recognize an
if-endconstruct (more practice later)
Reading
- Chapter 2, pp. 57 - 76
- Chapter 8, pp. 179 - 182
For a gentle introduction to fprintf, try this
screencast by Robert Talbert.
Lecture Slides
Download
- Notes on Using
fprintf - Large size image of Figure 1 in the "Using
fprintf" notes. - Slides on the
fprintfcommand - Slides on
forloops - Slides on the
ifconstructs
Comments on lecture content
We more carefully discuss the fprintf statement for displaying structured output
to the command window. You have seen fprintf in some of the sample codes
and now it's time to learn how to use it.
It is strange and surprising that the textbook does not mention fprintf and
focuses instead on disp. The fprintf command is much more versatile than
the disp command. The syntax of the fprintf command also takes some
practice to master. However, the pay-off is great for creating flexible and
well-formated output.
The for loop structure is used to repeat a sequence of calculations.
We will use for loops whenever we can't write vectorized expressions.
What are vectorized expressions? Here is an example of a vectorized
expression on the left, and a for loop on the right.
% -- Vectorized % -- Explicit loop
x = linspace(0,2*pi); x = zeros(1,100); % preallocate for efficiency
y = sin(x); y = zeros(1,100);
dx = 2*pi/(length(x)-1);
for i = 1:length(x)
x(i) = (i-1)*dx;
y(i) = sin(x(i));
end
Clearly the vectorized version is more compact and easy to grasp. That
doesn't mean for loops are bad.
The if-end, if-else-end and if-elseif - else - end
structures are used to take actions depending on conditions that are
determined while the code is running. Both for loops and if
structures are essential tools in writing MATLAB code to do numerical analysis.