sachinruk
sachinruk

Reputation: 9869

matrix multiplication error in numpy

I have the following two numpy arrays:

np.random.seed(1)
y2=np.random.standard_normal((50,1))
lambda_=np.zeros((100,2));
lambda_[0]=np.random.gamma(1,1,2);

but when I try to do

np.dot(y2,lambda_[0])

or its transposed version:

np.dot(y2,lambda_[0].T)

I get the error ValueError: matrices are not aligned

Now I understand that I can circumvent this error by using numpy matrices but isn't converting to np.matrix going to be inefficient? I am new to python so maybe I am wrong. Just trying to write the fastest code possible.

Upvotes: 1

Views: 2582

Answers (2)

Dhiraj
Dhiraj

Reputation: 106

Though with numpy it is too easy. You can do with python as below.

def array_mult(A, B):
    if len(B) != len(A[0]) and len(A) != len(B[0]):
        return 'Invalid'

    result = [[0 for x in range(len(B[0]))] for y in range(len(A))]
    for i in range(len(A)):
        for j in range(len(B[0])):
            for k in range(len(B)):
                result[i][j] += A[i][k] * B[k][j]
    return result

Upvotes: 1

fjarri
fjarri

Reputation: 9726

y2 has the shape (50, 1), and lambda_[0] has the shape (2,), so dot() treats it as a matrix-vector multiplication and, consequently, throws an error. If you want the second argument to be treated as a (1,2) matrix, you need to reshape it:

np.dot(y2,lambda_[0].reshape(1,2))

or, alternatively, use a 2D view of lambda_ instead of a 1D one:

np.dot(y2,lambda_[0:1])

Upvotes: 2

Related Questions