pythonarraysnumpyfor-looplinspace

input numpy array to linspace and for loop range problem


I am having trouble trying to use multiple values to test since linspace and range in for loop is not accepting array as an input.

Here is an example of what I am trying to do:

gp_input = np.array([31,61])

def var_gp(gp):
   for i in gp:
      x_l = np.linspace(0,3,gp)
      ...
   for i in range(gp):
      ...

What the error tells me:

Traceback (most recent call last):

File "variable gp.py", line 306, in var_gp(gp_input)

File "variable gp.py", line 18, in var_gp
    x_l = np.linspace(0,3,gp)
  File "<__array_function__ internals>", line 5, in linspace
  File "/home/rjomega/anaconda3/lib/python3.8/site-packages/numpy/core/function_base.py", line 120, in linspace
    num = operator.index(num)
TypeError: only integer scalar arrays can be converted to a scalar index

It feels like it would become a bad habit if I'll just manually change the value of gp and hoping I can just insert as much values to try. Thank you.

link to complete code

it works fine if I will just manually change the value of gp and not using def function

Solution I have found if you also experienced this kind of problem:

for i in gp:
       gp = i
          x_l = np.linspace(0,3,gp)
          ...
       for i in range(gp):
          ...

adding gp = i seems to bypass the problem


Solution

  • For a gp that's an array or list, iterate like this:

    In [471]: gp = np.array([3,6])
    In [472]: for i in gp:
         ...:     print(i)
         ...:     xi = np.linspace(0,3,i)
         ...:     print(xi)
         ...: 
    3
    [0.  1.5 3. ]
    6
    [0.  0.6 1.2 1.8 2.4 3. ]
    

    Note that I use i when calling linspace, not gp.

    When we pass the array to linspace we get your error:

    In [473]: np.linspace(0,3,gp)
    Traceback (most recent call last):
      File "<ipython-input-473-7032efa38f7c>", line 1, in <module>
        np.linspace(0,3,gp)
      File "<__array_function__ internals>", line 5, in linspace
      File "/usr/local/lib/python3.8/dist-packages/numpy/core/function_base.py", line 120, in linspace
        num = operator.index(num)
    TypeError: only integer scalar arrays can be converted to a scalar index
    

    In general in a for i in gp: expression, don't use gp with the body. You want to use i, the iteration variable. The whole point to using a for loop is to work with the elements of gp, not with the whole thing.

    We can't use the array in range either. It has to be number elements, one at a time:

    In [477]: range(gp)
    Traceback (most recent call last):
      File "<ipython-input-477-4e92b04fe1fc>", line 1, in <module>
        range(gp)
    TypeError: only integer scalar arrays can be converted to a scalar index
    
    In [478]: for i in gp:
         ...:     print(list(range(i)))
         ...: 
    [0, 1, 2]
    [0, 1, 2, 3, 4, 5]