Videos
I solved the following problem on HackerRank:
https://www.hackerrank.com/challenges/np-dot-and-cross/problem
Here's my solution
import numpy as np n = int(input()) arr_a = np.array([input().split() for _ in range(n)], int) arr_b = np.array([input().split() for _ in range(n)], int) print(np.matmul(arr_a, arr_b))
I used the matmul module but I feel this defeats the purpose of the question which I feel is to use cross and dot products.
How can I do this using dot and cross products?
Hi. I'm just learning python coming from matlab, and need to do some linear algebra for a program I'm writing. Naturally I am using numpy, but I'm very confused by how it handles matrix multiplication. The normal rules say that for an M by N matrix, multiplication is only defined if you right-multiply by an N by P matrix. yet I'm finding that it seems to want to do M by N with P by N.
e.g:
import numpy as np
a = np.asarray([0, 1, 2])
b = np.asarray([3, 4, 5])
print(np.matmul(a,b))
>>> 14
this seems wrong. This should be undefined since the # rows on the right don't match the # columns on the left. Is there an implicit transposition going on here? If this is truly how this is supposed to operate this way, it seems like it is flirting with disaster since it is will not produce the result that convention dictates it should, and for square matrices will make it very hard to track down where in your code your matrix multiplication got screwed up, since no error will get thrown. Am I missing something here?
This might be a relatively recent feature, but I like:
A.dot(B).dot(C)
or if you had a long chain you could do:
reduce(numpy.dot, [A1, A2, ..., An])
Update:
There is more info about reduce here. Here is an example that might help.
>>> A = [np.random.random((5, 5)) for i in xrange(4)]
>>> product1 = A[0].dot(A[1]).dot(A[2]).dot(A[3])
>>> product2 = reduce(numpy.dot, A)
>>> numpy.all(product1 == product2)
True
Update 2016:
As of python 3.5, there is a new matrix_multiply symbol, @:
R = A @ B @ C
Resurrecting an old question with an update:
As of November 13, 2014 there is now a np.linalg.multi_dot function which does exactly what you want. It also has the benefit of optimizing call order, though that isn't necessary in your case.
Note that this available starting with numpy version 1.10.