Reputation: 4054
Coming to scipy/numpy from MATLAB, I regard the input syntax to numpy.array as overly parenthesis-heavy, e.g.
import numpy as np
import math
np.array([[1, 2], [math.sqrt(3), 4]])
The following MATLAB-like syntax therefore appeals to me:
np.array(np.mat("1, 2; math.sqrt(3), 4"))
However, this particular example apparently results in the array
array([[ 1. , 2. ],
[ 0.3, 4. ]])
It seems that numpy.mat() ignores some characters in its input string: in this case "math" and "sqrt". Furthermore, it seems that it is not possible to use variables in the input string. Why is that? And is there a way to use a MATLAB-like, paranthesis-thrifty input method that isn't "broken" in this way?
Upvotes: 0
Views: 203
Reputation: 97281
You can use eval()
and sys._getframe()
to write a function, here is an example:
import numpy as np
def m(s):
import sys
frame = sys._getframe(1)
return np.array([eval(item.strip(), frame.f_globals, frame.f_locals)
for item in s.split(";")])
def f():
a = 1
x = 3.14
print m("1,2,3;np.sin(a),np.sqrt(2),x")
f()
Upvotes: 3