Homework: Vectors and matrices¶
Submit this homework via Dropbox. For the deadline please consult the schedule posted on Blackboard.
Python-scripts are submitted in one file called:
homework3.py
Please do NOT change the name of this script file.
This homework requires you to manipulate vectors and matrices. It makes
extensive use of the numpy
(Numerical Python) library. Don’t forget to
import it first.
Exercise 1¶
Define the following matrices as A
and B
Multiply A and B element by element.
Add A and B element by element.
Transpose matrix A to A’.
Extract the second row of matrix A, that is
1 0 1
and print it.Use matrix slicing to define vector
a
as the last column of matrix A and vectorb
as the last row of matrix B. Do not simply hard code the numbers of these vectors but use slicing, like you did in the previous question. Then add upa
andb
and print the result.
Exercise 2¶
The aim is to fill two vector arrays xv
and yv
with x
and f(x)
values, respectively, where
\(f(x) = \frac{1}{\sigma \sqrt{2 \pi}} e^{- \frac{1}{2} \left( \frac{x- \mu}{\sigma} \right) ^2}\)
is the density of the standard normal distribution, that is a normal density
with mean \(\mu=0\) and standard deviation \(\sigma = 1\). Let the xv
values be
uniformly spaced in xv = [-4, 4]
with 100 grid points.
Write a loop to fill in the values for \(xv\) and \(yv=f(xv)\).
So at the end you should have a vector xv
with the X-values and a vector
yv
with the function values \(f(x)\).
Hint: The constant pi
, the square root function \(\sqrt{x}\)
(sqrt()
) and the natural exponential function \(e\) (exp()
)
are all coded in the numpy
library. No need to use the math
library for these.
Bonus points: Plot yv
against xv
using the plot
command.
Exercise 3¶
Create a vector array wv
with values 0, 0.1, 0.2, …, 3 without using a
loop.
Write print statements to print w[:]
, w[:-2]
, w[::5]
, w[2:-2:6]
.
Explain which elements of the array are printed using these commands!
Exercise 4¶
Create a \(3 \times 3\) matrix with the value \(1\) in the main
diagonal and call this matrix A
. Then create a \(5 \times 3\) matrix filled with the value
\(1\) and call it B
.
When I say create I don’t mean to simply type these matrices by hand. Use some
built in numpy
functions that generate these specific types of matrices
automatically. Read the book carefully, the answer is right there!
Then create a third matrix C
that stacks the two earlier matrices
on top of each other so that the result looks like this:
Exercise 5¶
Use the matrix from Exercise 4 and run a loop that extracts all the elements from the second column and prints them one by one.
Use the matrix from Exercise 4 and run a loop that extracts all the elements from the third row and prints them one by one.
Exercise 6¶
Create the following matrix A
by hand (just type it into the script file).
Write a loop (or a nested loop) that extracts the diagonal elements 2,3,4,6,7,8 and prints them one by one.