This is the solution to Quiz 4: Problems - MATLAB loops.

The following figure illustrates the grade distribution for this quiz.

Maximum possible points is 1.

This quiz is about for loops, while loops and vectorization in MATLAB.





1.  Write a function that takes an input integer, and computes its factorial,

in the following ways:

(a) Write this function using while-loop. Name it getFacWhile(n).

(b) Write this function using for-loop. Name it getFacFor(n).

(c) Write this function using the vectorization concept. Name it getFacVec(n). (Hint: for the vectorized version of this function, you will have to first create a vector of integers from 1 to n, using MATLAB vector construction notation (This is very simple and easy if you recall from lecture notes). Then use MATLAB’s built-in prod() function to accomplish the task of computing $n!$ as given by the above equation.)

Answer:
Here are the functions: getFacWhile.m, getFacFor.m, getFacVec.m.


2.  Write a MATLAB script, timeFacFuncs.m that times the performance of the three functions you wrote in the previous problem, so that when you run this script, you get an output like the following,

>> timeFacFuncs
average runtime for getFacWhile(1700000): 0.0054129 seconds
average runtime for getFacFor(1700000): 0.0080964 seconds
average runtime for getFacVec(1700000): 0.005283 seconds


Answer:
Here is the script timeFacFuncs.m.


3.  Extra Credit Modify your answer to problem 1.(c) above in such a way that instead of using prod(), you get the factorial using sum() and some other elementary mathematical MATLAB functions. (Hint: for this problem, you will need to transform the numbers involved in calculations using some appropriate MATLAB mathematical function and revert the result at the end.)

Answer:
You can do so, using log() transformation of the numbers in factorial,

Therefore, a possible implementation using sum() could be this function: getFacVecSum.m.



Comments