Multiplying Two matrices (2x1) and (2x2( [duplicate] - python

This question already has an answer here:
numpy matrix vector multiplication [duplicate]
(1 answer)
Closed 4 years ago.
Hi for my code I have to multiply a point/vector (1,0) by matrix [1.00583, -0.087156], [0.087156, 1.00583]. The result should give me a new point (x,y)
This is what I have so far:
import matplotlib.pyplot as plt
import numpy as np
A = np.array([[1],[0]])
B = np.array([[1.00583, -0.087156], [0.087156, 1.00583]])
test =np.multiply(A, B)
print (test)
The result still gives me a (2x2) matrix instead of a (2x1) that i can use as a point. Is there another function or a better way of going about this?

First thing, if you want to do matrix multiplication use numpy.matmul or the # operator, e.g. B#A.
Also, when you define A like
A = np.array([[1],[0]])
this creates a 2x1 vector (not 1x2). So if you want to multiply the vector A with the matrix B (2x2) this should be C = B*A, where C will be a 2x1 vector
C = B#A
Otherwise if you want to multiply A*B and B is still the 2x2 matrix you should define A as a 1x2 vector:
A = np.array([1,0])
and get a 1x2 result with
C = A#B

test =np.matmul(B,A)
This should do the trick.

Related

is there any way to calculate L2 norm of multiple 2d matrices at once, in python?

for example, I have a matrix of dimensions (a,b,c,d). I want to calculate L2 norm of all d matrices of dimensions (a,b,c). Is there any way to use numpy.linalg.norm with out any looping structure?
I mean, the resultant array should be 1 x d
How about this?
import numpy as np
mat = np.arange(2*3*4*5).reshape(2,3,4,5) # create 4d array
mat2 = np.moveaxis(mat,-1,0) # bring last axis to the front
*outarr, = map(np.linalg.norm,mat2) # use map

How most efficiently compute the diagonal of a matrix product [duplicate]

This question already has answers here:
Using numpy einsum to compute inner product of column-vectors of a matrix
(2 answers)
Closed 2 years ago.
I want to compute the following:
import numpy as np
n= 3
m = 2
x = np.random.randn(n,m)
#Method 1
y = np.zeros(m)
for i in range(m):
y[i] = x[:,i] # x[:,i]
#Method 2
y2 = np.diag(x.T # x)
The first method has the problem that it uses a for loop, which can't be very effecient (I need to do this in pytorch on a GPU millions of times)
The second method computes the full matrix product, when I only need the diagonal entries, so that can't be very efficient either.
I'm wondering whether there exist any clever way of doing this?
Use a manually constructed sum-product. You want the sums of the squares of the individual columns:
y = (x * x).sum(axis=0)
As Divakar suggests, np.einsum will likely offer a less memory-intensive option, since it does not require the temporary array x * x:
y = np.einsum('ij,ij->j', x, x)

Numpy inner product of 2 column vectors

How can I take an inner product of 2 column vectors in python's numpy
Below code does not work
import numpy as np
x = np.array([[1], [2]])
np.inner(x, x)
It returned
array([[1, 2],
[2, 4]])`
instead of 5
The inner product of a vector with dimensions 2x1 (2 rows, 1 column) with another vector of dimension 2x1 (2 rows, 1 column) is a matrix with dimensions 2x2 (2 rows, 2 columns). When you take the inner product of any tensor the inner most dimensions must match (which is 1 in this case) and the result is a tensor with the dimensions matching the outter, i.e.; a 2x1 * 1x2 = 2x2.
What you want to do is transpose both such that when you multiply the dimensions are 1x2 * 2x1 = 1x1.
More generally, multiplying anything with dimensions NxM by something with dimensionsMxK, yields something with dimensions NxK. Note the inner dimensions must both be M. For more, review your matrix multiplication rules
The np.inner function will automatically transpose the second argument, thus when you pass in two 2x1, you get a 2x2, but if you pass in two 1x2 you will get a 1x1.
Try this:
import numpy as np
x = np.array([[1], [2]])
np.inner(np.transpose(x), np.transpose(x))
or simply define your x as row vectors initially.
import numpy as np
x = np.array([1,2])
np.inner(x, x)
i think you mean to have:
x= np.array([1,2])
in order to get 5 as output, your vector needs to be 1xN not Nx1 if you want to apply np.inner on it
Try the following it will work
np.dot(np.transpose(a),a))
make sure col_vector has shape (N,1) where N is the number of elements
then simply sum one to one multiplication result
np.sum(col_vector*col_vector)

Numpy two matrices, pairwise dot product of rows [duplicate]

This question already has answers here:
Vectorized way of calculating row-wise dot product two matrices with Scipy
(5 answers)
Closed 6 years ago.
We are currently working on a python project and have to vectorize a lot due to performance constraints. We end up with the following calculation: We have two numpy arrays of shape (20,6) and want to calculate the pairwise dot product of the rows, i.e. we should obtain a (20,1) matrix in the end, where each row is the scalar obtained by the respective vector dot multiplication.
You can multiply the two arrays element wise and then do sum by rows, and then you have an array where each element is a dot product from rows of the two original arrays:
a = np.array([[1,2], [3,4]])
b = np.array([[3,4], [2,1]])
(a * b).sum(axis=1)
# array([11, 10])

Left Matrix Division and Numpy Solve

I am trying to convert code that contains the \ operator from Matlab (Octave) to Python. Sample code
B = [2;4]
b = [4;4]
B \ b
This works and produces 1.2 as an answer. Using this web page
http://mathesaurus.sourceforge.net/matlab-numpy.html
I translated that as:
import numpy as np
import numpy.linalg as lin
B = np.array([[2],[4]])
b = np.array([[4],[4]])
print lin.solve(B,b)
This gave me an error:
numpy.linalg.linalg.LinAlgError: Array must be square
How come Matlab \ works with non square matrix for B?
Any solutions for this?
From MathWorks documentation for left matrix division:
If A is an m-by-n matrix with m ~= n and B is a column vector with m
components, or a matrix with several such columns, then X = A\B is the
solution in the least squares sense to the under- or overdetermined
system of equations AX = B. In other words, X minimizes norm(A*X - B),
the length of the vector AX - B.
The equivalent in numpy is np.linalg.lstsq:
In [15]: B = np.array([[2],[4]])
In [16]: b = np.array([[4],[4]])
In [18]: x,resid,rank,s = np.linalg.lstsq(B,b)
In [19]: x
Out[19]: array([[ 1.2]])
Matlab will actually do a number of different operations when the \ operator is used, depending on the shape of the matrices involved (see here for more details). In you example, Matlab is returning a least squares solution, rather than solving the linear equation directly, as would happen with a square matrix. To get the same behaviour in numpy, do this:
import numpy as np
import numpy.linalg as lin
B = np.array([[2],[4]])
b = np.array([[4],[4]])
print np.linalg.lstsq(B,b)[0]
which should give you the same solution as Matlab.
You can form the left inverse:
import numpy as np
import numpy.linalg as lin
B = np.array([[2],[4]])
b = np.array([[4],[4]])
B_linv = lin.solve(B.T.dot(B), B.T)
c = B_linv.dot(b)
print('c\n', c)
Result:
c
[[ 1.2]]
Actually, we can simply run the solver once, without forming an inverse, like this:
c = lin.solve(B.T.dot(B), B.T.dot(b))
print('c\n', c)
Result:
c
[[ 1.2]]
.... as before
Why? Because:
We have:
Multiply through by B.T, gives us:
Now, B.T.dot(B) is square, full rank, does have an inverse. And therefore we can multiply through by the inverse of B.T.dot(B), or use a solver, as above, to get c.

Categories