2
votes

For example, I have an equation for projection matrix which works for 1 dimensional vectors:

enter image description here

where P is projection matrix and T is transpose.

We know that we can't simplify this fraction more (by cancelling terms) since denominator is a dot product (thus 0 dimensional scalar, number) and numerator is a matrix (column multiplied by row is a matrix).

I'm not sure how could I define function for this equation in numpy, considering that the current function that I'm using does not differentiate between these terms, multiplication is treated as it has commutative property. I'm using numpy.multiply method:

>>> import numpy as np
>>> a = np.array(a)
>>> a*a.T
array([1, 4, 9])
>>> a.T*a  
array([1, 4, 9])

As you see, both of them output vectors.

I've also tried using numpy.matmul method:

>>> np.matmul(a, a.T)
14
>>> np.matmul(a.T, a)
14

which gives dot product for both of the function calls.

I also did try numpy.dot but it obviously doesn't work for numerator terms.

From my understanding, the first function call should output matrix (since column is multiplied by row) and the second function call should output a scalar in a proper case.

Am I mistaken? Is there any method that differentiates between a multiplied by a transpose and a transpose multiplied by a?

Thank you!

2
the * operator is not the dot product - talonmies
@talonmies Yes, which function can be used to differentiate between a^Ta and aa^T? Is there any "universal" multiplication function? Thanks! - ShellRox
@Chrispresso Tried dot product method as well, but it doesn't work for terms in numerator. - ShellRox

2 Answers

3
votes

Note that 1-dimensional numpy arrays are not column vectors (and operations such as transposition do not make sense). If you want to obtain a column vector you should define your array as a 2-dimensional array (with the second dimension size equal to 1).

However, you don't need to define a column vector, as numpy offers functions to do what you want by manipulating an 1D array as follows

P = np.outer(a,a)/np.inner(a,a)

2
votes

Stelios' answer is the best, no doubt but for completeness you can use the @ operator with 2-d arrays:

a = np.array([1,4,9])[np.newaxis]

P = (a.T @ a) / (a @ a.T)