X-Git-Url: https://gitweb.michael.orlitzky.com/?a=blobdiff_plain;f=src%2Fdunshire%2Fmatrices.py;h=52ba2a34c0352ac9d16744c64abc5ac195a50d7e;hb=591601df2ef73b192f3ed491f1f168fa71ed5302;hp=5acc7a876e417beafd259d416f59fc283c1c5f67;hpb=f9c11a761f23f781495171c2b3136a92388a18a1;p=dunshire.git diff --git a/src/dunshire/matrices.py b/src/dunshire/matrices.py index 5acc7a8..52ba2a3 100644 --- a/src/dunshire/matrices.py +++ b/src/dunshire/matrices.py @@ -55,9 +55,9 @@ def eigenvalues(real_matrix): """ domain_dim = real_matrix.size[0] # Assume ``real_matrix`` is square. - W = matrix(0, (domain_dim, 1), tc='d') - syev(real_matrix, W) - return list(W) + eigs = matrix(0, (domain_dim, 1), tc='d') + syev(real_matrix, eigs) + return list(eigs) def identity(domain_dim): @@ -83,6 +83,37 @@ def identity(domain_dim): return matrix(entries, (domain_dim, domain_dim)) +def inner_product(vec1, vec2): + """ + Compute the (Euclidean) inner product of the two vectors ``vec1`` + and ``vec2``. + + EXAMPLES: + + >>> x = [1,2,3] + >>> y = [3,4,1] + >>> inner_product(x,y) + 14 + + >>> x = matrix([1,1,1]) + >>> y = matrix([2,3,4], (1,3)) + >>> inner_product(x,y) + 9 + + >>> x = [1,2,3] + >>> y = [1,1] + >>> inner_product(x,y) + Traceback (most recent call last): + ... + TypeError: the lengths of vec1 and vec2 must match + + """ + if not len(vec1) == len(vec2): + raise TypeError('the lengths of vec1 and vec2 must match') + + return sum([x*y for (x,y) in zip(vec1,vec2)]) + + def norm(matrix_or_vector): """ Return the Frobenius norm of ``matrix_or_vector``, which is the same @@ -100,4 +131,43 @@ def norm(matrix_or_vector): 2.0 """ - return sqrt(sum([x**2 for x in matrix_or_vector])) + return sqrt(inner_product(matrix_or_vector,matrix_or_vector)) + + +def vec(real_matrix): + """ + Create a long vector in column-major order from ``real_matrix``. + + EXAMPLES: + + >>> A = matrix([[1,2],[3,4]]) + >>> print(A) + [ 1 3] + [ 2 4] + + + >>> print(vec(A)) + [ 1] + [ 2] + [ 3] + [ 4] + + + Note that if ``real_matrix`` is a vector, this function is a no-op: + + >>> v = matrix([1,2,3,4], (4,1)) + >>> print(v) + [ 1] + [ 2] + [ 3] + [ 4] + + >>> print(vec(v)) + [ 1] + [ 2] + [ 3] + [ 4] + + + """ + return matrix(real_matrix, (len(real_matrix), 1))