Topics fprintf: formatted print function, and using fprintf in a factorial function.
% Some examples of fprintf usage. First set a few variables to be printed. x = 3; y = 7; % fprintf substitutes the values of the listed variables into the % format string in places marked with %'s. %d is code for decimal (integer). fprintf('The values of x is %d and the value of y is %d\n', x, y); The values of x is 3 and the value of y is 7 % If you want to print a number as a floating-point number, use %f or %e fprintf('The values of x is %f and the value of y is %d\n', x, y); The values of x is 3.000000 and the value of y is 7 % An example of fprintf with a string, using %s in the format string % By the way, notice the \n in the examples. That's a newline character. name = 'John'; fprintf('My name is %s\n', name); My name is John
Now let's do a programming task: write a function that computes the factorial of n. The mathematical definition of the factorial is
To compute the factorial, we have to multiply the numbers n through 1 together. We can do that with a for-loop. Here's a basic implementation as a function in Matlab.
function p = fact(n); % p = fact(n): compute factorial of n p = 1; % set p to 1 for k=1:n % loop over numbers 1 through n p = p*k; % multiply p by k and assign result into p end end
Does it work? Let's check with some examples
fact(2) ans = 2 % correct fact(3) ans = 6 % correct fact1(4) ans = 24 % correct fact(5) ans = 120 % correct fact1(7) ans = 5040 % correct
Now let's add some fprintf statements to clarify how the function works. Print values of p, k, and p*k at each step in the loop. Also, let's change the loop order so that the multiplication proceeds from n to (n-1) to (n-2) down to 2 to 1, just to be closer to the familiar formula.
function p = fact(n); % p = fact(n): compute factorial of n p = 1; % set p to 1 for k=n:-1:1 % loop over numbers n through 1, in steps of -1 fprintf('multiply %d by %d, product is %d\n', p, k, p*k); p = p*k; end end
Now you can see how the function operates
fact(7) multiply 1 by 7, product is 7 multiply 7 by 6, product is 42 multiply 42 by 5, product is 210 multiply 210 by 4, product is 840 multiply 840 by 3, product is 2520 multiply 2520 by 2, product is 5040 multiply 5040 by 1, product is 5040 ans = 5040
You'll notice the first and last multiplications are unneccessary. We can eliminate them by starting p at value n, and changing the loop indices to start at n-1 and got down to 2.x
function p = fact(n); % p = fact(n): compute factorial of n p = n; % set p to n for k=n-1:-1:2 % loop over numbers n-1 through 2, in steps of -1 fprintf('multiply %d by %d, product is %d\n', p, k, p*k); p = p*k; end end
Now the function works with fewer multiplications
fact(7) multiply 7 by 6, product is 42 multiply 42 by 5, product is 210 multiply 210 by 4, product is 840 multiply 840 by 3, product is 2520 multiply 2520 by 2, product is 5040 ans = 5040