Homework 2- approximating derivatives


5/5 - (2 votes)

ECE-210B Homework 2
In this homework, you will review some of the topics discussed in class this week, including approximating derivatives and integrals and different matrix operations. You will also see that for loops
are usually not the best idea in MATLAB…
1. Here you will be approximating derivatives and integrals on the sine function.
• Create two vectors with entries evenly spaced between 0 and pi. One vector should be
of length 100 and the other should be of length 1000. Then apply these vectors to the
function sin(2x).
• Approximate the derivative of this function by taking differences of adjacent elements
and dividing by the space between them. Do this for both vectors.
• What function should this be? (I hope you know this…) Check this by applying the
original evenly-spaced vectors to this function, taking the elementwise difference between
the resulting vectors and the derivative vectors and computing the magnitudes of the
max differences between them. Which length produces better results?
• Now use cumsum and cumtrapz to approximate the integral of sin(2x). Do this for
both lengths as before.
• Subtract 0.5 from every element of each integral vector to center their graphs at 0. Then
compare the computed vectors with the analytic antiderivative as before. Return the
magnitude of the max error for each of the four cases.
• Plot the best approximation for the integral. Add a title to the plot.
2. Perform the following matrix operations:
• Use reshape to create the 10×10 matrix A =

1 11 … 91
2 12 … 92
10 20 … 100

• Flip A upside down.
• Flip the 3rd row left to right.
• Create a row vector which is the column wise sum of the entries of A.
• Create a column vector which is the row wise product of the entries of A (Check out
• Delete the 6th row.
3. Create a 300×500 matrix B where Bij =
i+j+2 . Do this, and time how long each one takes
with tic toc, using three methods:
• Using a for loop without preallocation.
• Using a for loop with preallocation.
• Using only elementwise matrix operations (meshgrid may be useful here).

PlaceholderHomework 2- approximating derivatives
Open chat
Need help?
Can we help?