Reputation: 151
In wolfram Mathematica, I use Table[]
function all the time.
Example of Table function
i1^2 + i3^3
could be any function of parameters (i1
,i3
).
and
{i1, 1, 9, 2},
5,
{i3, 7, 3, -.5}
is the space of parameters.
For more details see the documentation: https://reference.wolfram.com/language/ref/Table.html
I can do this with a series of for loops in python like this:
import numpy as np
def f(i1,i3):
return(i1**2+i3**3)
arr=np.array([[[
f(i1,i3)
for i3 in np.arange(7,2.5,-.5)]
for i2 in np.arange(5)]
for i1 in np.arange(1,11,2)]
)
print(arr)
Is there a shorter, more compact way of doing it?
Upvotes: 4
Views: 1184
Reputation: 171
I recently started python and this is is one of the things I miss from Mathematica. Below I give a function that answers the question but it only works when the output is a numerical table not a symbolic one. If the reader would like a symbolic table then FunctionMatrix in the python package sympy might help.
code:
import itertools
import numpy as np
def table(f,*arg) :
return np.array([f(*a) for a in itertools.product(*arg)]).reshape(*map(len,arg))
Examples:
input: table(lambda a,b : a+b, np.arange(1,3),np.arange(1,5))
output: array([[2, 3, 4, 5],[3, 4, 5, 6]])
input: table(lambda a,b,c : a**2+b**3+c**4, np.arange(2,4),np.arange(1,5),np.arange(1,3))
output:
array([[[ 6, 21],
[13, 28],
[32, 47],
[69, 84]],
[[11, 26],
[18, 33],
[37, 52],
[74, 89]]])
OP's example in the image is obtained with
table(lambda a,b,c : a**3+c**3,np.arange(1,11,2), np.arange(5), np.arange(7,2.5,-.5))
I was not able (did not really try that much) to translate what OP's code with for loops would be in mathematica and I did not know what arrays to use with the above table function
Upvotes: 0