Starting from:
$35

$29

Homework 2 Solution

In this homework, you will review some of the topics discussed in class this week, including approx-imating derivatives and integrals and di erent 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 di erences 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 di erence between the resulting vectors and the derivative vectors and computing the magnitudes of the max di erences 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:
2
1
6 2
Use reshape to create the 10x10 matrix A = 6 . 6 .. 4
10

Flip A upside down.

Flip the 3rd row left to right.


    11 :::

    12 :::
...   ...
    20 :::

3
91
    92 7
.. 7.
7
. 5
100

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 prod ).

Delete the 6th row.

3. Create a 300x500 matrix B where Bij  = i3+j3 . Do this, and time how long each one takes

i+j+2
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).





1

More products