There is a simple function, which intends to accept a scalar parameter, but also works for a numpy matrix. Why does the function fun
works for a matrix?
>>> import numpy as np
>>> def fun(a):
return 1.0 / a
>>> b = 2
>>> c = np.mat([1,2,3])
>>> c
matrix([[1, 2, 3]])
>>> fun(b)
0.5
>>> fun(c)
matrix([[ 1. , 0.5 , 0.33333333]])
>>> v_fun = np.vectorize(fun)
>>> v_fun(b)
array(0.5)
>>> v_fun(c)
matrix([[ 1. , 0.5 , 0.33333333]])
It seems like fun
is vectorized somehow, because the explictly vectorized function v_fun
behaves same on matrix c
. But their get different outputs on scalar b
. Could anybody explain it? Thanks.