User Tools

Site Tools


gibson:teaching:spring-2016:math445:lecture:forloop

This is an old revision of the document!


A PCRE internal error occured. This might be caused by a faulty plugin

====== Math 445 lecture 7: the "for" loop, fprintf ====== ===== Formatted printing with fprintf ===== **fprintf** is Matlab's **formatted print function**. It's used for printing variables to the screen (or files) in a format that you specify. The basic syntax is <code matlab> fprintf('format-string', variable, variable, variable, ...) </code> but it is really best illustrated by example. <code matlab> >> w = 'perambulate'; >> n = length(w); >> fprintf('The word %s has %d letters.\n', w, n) The word perambulate has 11 letters. </code> The format string contains two //slots// ''%s'' and ''%w''. The percent sign is a special marker that signals a slot, and the character following it specifies the type of variable that goes in the slot, ''%s'' for string and ''%d'' for decimal. The values of the variables $w$ and $n$ are placed in those slots when the fprintf function is executed. The ''\n'' is a special //control character// for "new line." The most important slot types are * ''%d'' decimal (integer), e.g. 5 * ''%f'' floating-point, e.g. 2.75 * ''%s'' string (a sequence of characters), e.g. '' 'banana'''. * ''%c'' character, e.g. '' 'q' '' ===== for loops ===== **for** loops are used to repeat a sequence of commands a specified number of times. A **for** loop has an index variable (often $n$ or $i$) whose value changes over every iteration of the loop. For example, this Matlab **for** loop <code matlab> for n=1:4 fprintf('The value of n is %d.\n',n); end </code> produces the output <code> The value of n is 1. The value of n is 2. The value of n is 3. The value of n is 4. </code> Note how the //body// of the loop (the fprintf) statement is executed four times, once for each value of $n$ from 1 to 4. ===== functions ===== The Matlab **function** command lets you define your own functions. For example, <code quadratic.m matlab> function y = quadratic(x) y = x^2 + 3*x -7; end </code> defines a function named ''quadratic'' that computes the polynomial $y(x) = x^2 +3x -7$. The filename must match the name of the function, e.g. filename ''quadratic.m'' matches function name ''quadratic''. If the ''quadratic.m'' function is placed in Matlab's current working directory, you'll be able to execute the function just like a regular matlab built-in function, for example <code> >> quadratic(0) ans = -7 >> quadratic(1) ans = -3 >> quadratic(12.74) ans = 193.5276 </code>

gibson/teaching/spring-2016/math445/lecture/forloop.1455648822.txt.gz · Last modified: 2016/02/16 10:53 by gibson