4

In wolfram Mathematica, I use Table[] function all the time.

Example of Table function

enter image description here

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?

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
GalZoidberg
  • 141
  • 3
  • The python module for symbolic algebra is `sympy`, it might have something similar. – Barmar Mar 27 '21 at 18:47
  • You can try `np.array(list(map(f, np.dstack(np.meshgrid(a, c)).reshape((len(a)*len(c), 2))))).reshape((len(c), len(a)))`, but you'll need to work on duplicating each inner array five times. `a, c` are the ranges corresponding to `i3, i1` respectively. You'll also need to update `f` a little bit. – tobias Mar 27 '21 at 19:59
  • If you don't care about the MatrixForm part (maybe you were just using it to display your answer) you can use: `list(map(lambda i1: list(map(lambda i3: i1**2 + (i3/2)**2, range(7*2,3*2-1, -1))), range(1, 9+1, 2)))`. – Well... Jan 06 '22 at 16:14

1 Answers1

0

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

userrandrand
  • 121
  • 5