简体   繁体   English

填充二维数组(矩阵)

[英]Filling a 2D Array (a Matrix)

Consider, for instance, the following formula:例如,考虑以下公式:

$$f_{nm}(x) = \sin(n \ m \ x^2/\pi)$$ $$f_{nm}(x) = \sin(n \ m \ x^2/\pi)$$

where $n$ and $m$ both are integers $\in [1,4]$ .其中$n$$m$都是整数$\in [1,4]$ Forming a matrix with this information would result in:使用此信息形成矩阵将导致:

$$\mathbf{F} = \begin{pmatrix}\ f_{11} & f_{12} & f_{13} & f_{14} \\ f_{21} & f_{22} & f_{23} & f_{24} \\ f_{31} & f_{32} & f_{33} & f_{34} \\ f_{41} &f_{42}&f_{43}&f_{44}\end{pmatrix}$$ $$\mathbf{F} = \begin{pmatrix}\ f_{11} & f_{12} & f_{13} & f_{14} \\ f_{21} & f_{22} & f_{23} & f_{24} \\ f_{31} & f_{32} & f_{33} & f_{34} \\ f_{41} &f_{42}&f_{43}&f_{44}\end{pmatrix}$$

How to create such a $4\times4$ matrix in Python and fill it with the provided formula for a given $x$ please.如何在Python中创建这样一个$4\times4$矩阵,并用给定的$x$提供的公式填充它。 I know this question may be off-topic here, but the $LaTeX$ style of the equations did not work for me in the StackOverflow, that is why posted it here.我知道这个问题在这里可能是题外话,但是方程的$LaTeX$样式在 StackOverflow 中对我不起作用,这就是为什么在这里发布它。

For a fixed $x$ you should be able to do this对于固定的$x$你应该能够做到这一点

import numpy as np

f = np.zeros((4,4))
for n in range(4):
    for m in range(4):
        f[n][m] = np.sin(n*m*(x**2)/np.pi)

A faster implementation avoiding Python loops (if I understood your question correctly) that assumes that also x is an array from 0 to 1 and exploits Numpy Broadcasting一个更快的实现避免 Python 循环(如果我正确理解你的问题)假设x也是一个从 0 到 1 的数组并利用Numpy 广播

import numpy as np

n = np.arange(1, 5)
m = n.reshape(4, 1)
x = np.linspace(0, 1, 100).reshape(100, 1, 1)

result = np.sin(n * m * x**2 / np.pi)

print(result.shape)

This gives a result array of dimensions:这给出了一个维度的结果数组:

(100, 4, 4)

where the first dimensions indexes the x value.其中第一个维度索引x值。 That is:那是:

result[0, ...]

is the 4x4 matrix corresponding to x = x[0] = 0是对应于x = x[0] = 0的 4x4 矩阵

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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