Home>

I want to describe the relevant part written in the comment of the following program without using for.
Please tell me how to write something else that doesn't seem to be slow!

import numpy as np
def test (value):
    return value + 1, value + 2, value + 3, value + 4
A = np.random.rand (300, 900)
B = np.zeros ((300,900,4))
# I want you to teach me another way to write the following without using a for statement!
for i in range (A.shape [0]):
    for j in range (A.shape [1]):
        B [i] [j] = test (A [i] [j])
  • Answer # 1

    If you use numpy, it's easier to sum the arrays
    The n iterations of a random array a with shape (x, y) are A
    The (x, y) iteration of array b from 1 to n is B
    The result adds it.

    import numpy as np
    n = 4 # Maximum number to add to value in test
    x = 2 # Originally 300
    y = 3 # Originally 900
    a = np.random.rand (y, x)
    A = np.tile (a, (n, 1, 1)). T
    b = np.array ([i + 1 for i in range (n)])
    B = np.tile (b, (x, y, 1))
    print (A + B)
    # [[[1.75150523 2.75150523 3.75150523 4.75150523]
    # [1.21935891 2.21935891 3.21935891 4.21935891]
    # [1.16490574 2.16490574 3.16490574 4.16490574]]
    # [[1.73834419 2.73834419 3.73834419 4.73834419]
    # [1.58224169 2.58224169 3.58224169 4.58224169]
    # [1.48666611 2.48666611 3.48666611 4.48666611]]]

  • Answer # 2

    If you want to use a function called test:

    import numpy as np
    def test (value):
        return value + 1, value + 2, value + 3, value + 4
    A = np.random.rand (300, 900)
    B = np.zeros ((300,900,4))
    B [:,:, 0], B [:,:, 1], B [:, :, 2], B [:, :, 3] = test (A)