Assignment 2 requires you to vectorize and
plot the values of a rational function
that computes exp(x), for 10,000,000 equally
spaced x values between 0 and 1.
The first plot show the results of the given
code for a serialized calculation of y=exp(x).
A loop is used and y is not pre-allocated (and
so at each iteration of the loop it increases
y by 1 element). To guarantee y has not been
pre-allocated and saved in the workspace by a
previous run of your program, it is set to a
single value (0 in this case) before the
'calculation is done. This should be the worst
calculation from a computational time cost.
Use tic and toc to do the timing, as shown on
the assignment handout.
The second plot comes from the JIT compiled
code. The code is the same as the serial code '
but y is now pre-allocated using y=zeros(1,n,'double'),
Thus, dynamic allocation of y is not needed in the loop
and MatLab compiles the code for you. Much faster!
The third plot comes from the vectorized solution.
No loops can be used and indices are not needed
and should not be used. This is the MAIN part of
this assignment. Consider the following
serialized code and its vectorized code. The loop:
for i=1:n
z(i)=(x(i)^2)/(y(i)^3);
end
can be vectorized using:
z=(x.^2)./(y.^3);
This code should be even faster!
The fourth plot should show the plot of x versus
y=exp(x). Again the computational cost can be
computed using tic/toc. You will probably observed
that the vectorized solution and the direct exp(x)
solution require about the same time. Maybe the
vectorized solution is a bit faster? It is unknown
how MatLab does the exp(x) calculation (maybe
vectorization or parallel GPU processing).
Make the 2nd to 4th plots with the colours on the
assignment handout using the same plotting commands
shown in the serial solution.