简体   繁体   中英

Python NumPy: How to fill a matrix using an equation

I wish to initialise a matrix A , using the equation A_i,j = f(i,j) for some f (It's not important what this is).

How can I do so concisely avoiding a situation where I have two for loops?

numpy.fromfunction fits the bill here.

Example from doc:

>>> import numpy as np
>>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
array([[0, 1, 2],
   [1, 2, 3],
   [2, 3, 4]])

One could also get the indexes of your array with numpy.indices and then apply the function f in a vectorized fashion,

import numpy as np

shape = 1000, 1000

Xi, Yj = np.indices(shape)

A = (2*Xi + 3*Yj).astype(np.int) # or any other function f(Xi, Yj)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM