This is an old revision of the document!
====== 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> ===== 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 matlab> 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.