This notebook walks you through how to implement simple functions that set the diagonal elements of a square matrix to the components of a given vector.
We will use some functions that are part of our laff library (of which this function will become a part) as well as some routines from the FLAME API (Application Programming Interface) that allows us to write code that closely resembles how we typeset algorithms using the FLAME notation. These functions are imported with the "import laff as laff" and "import flame" statements.
Set_to_diagonal_matrix_unb_var1( d, A )
This routine sets the diagonal elements of $ A $ to the components of vector $ d$, and sets the off-diagonal elements to zero.
The specific laff functions we will use are
laff.zerov
which, when given a row or column vector (stored as a 1 x n or n x 1 matrix) will zero that vector. laff.copy
which copies a vector to a vector. We will use it to copy a scalar to a scalar. Use the Spark webpage .
# insert code here
Let's quickly test the routine by creating a 5 x 5 matrix and vector of size 5 and then setting the matrix to the diagonal matrix with the components of the vector on its diagonal
from numpy import random
from numpy import matrix
A = matrix( random.rand( 5,5 ) )
d = matrix( random.rand( 5,1 ) )
print( 'A before =' )
print( A )
print( 'd before =' )
print( d )
Set_to_diagonal_matrix_unb_var1( d, A )
print( 'A after =' )
print( A )
Bingo, it seems to work!
Now, one could alternatively sets the matrix to the diagonal matrix by rows.
Use the Spark webpage to generate the function Set_to_diagonal_matrix_unb_var2( d, A ) that overwrites A one row at a time.
# insert code here
Test your routine with the following
from numpy import random
from numpy import matrix
A = matrix( random.rand( 5,5 ) )
d = matrix( random.rand( 5,1 ) )
print( 'A before =' )
print( A )
print( 'd before =' )
print( d )
Set_to_diagonal_matrix_unb_var2( d, A )
print( 'A after =' )
print( A )
Copy and paste the code into PictureFLAME , a webpage where you can watch your routine in action. Just cut and paste into the box.
Disclaimer: we implemented a VERY simple interpreter. If you do something wrong, we cannot guarantee the results. But if you do it right, you are in for a treat.
If you want to reset the problem, just click in the box into which you pasted the code and hit "next" again.