Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用python创建矩阵的特殊情况_Python_Numpy_Matrix - Fatal编程技术网

用python创建矩阵的特殊情况

用python创建矩阵的特殊情况,python,numpy,matrix,Python,Numpy,Matrix,我需要用python创建一个名为m ofExE的矩阵,其E=256。这种情况是,当我打印m(I,j)时,输出必须是j。 这就是我迄今为止所尝试的: >>>M = np.random.randint(0,255, size=(256,256)) >>>print(M) 您可以使用 测试用例 M[10,2], M[3,5], M[120,230] Oot: (2, 5, 230) 除了使用np.tile,您还可以使用列表理解来实现这一点: 将numpy导入为

我需要用python创建一个名为m of
ExE
的矩阵,其
E=256
。这种情况是,当我打印
m(I,j)
时,输出必须是
j
。 这就是我迄今为止所尝试的:

>>>M = np.random.randint(0,255, size=(256,256)) 
>>>print(M)
您可以使用

测试用例

M[10,2], M[3,5], M[120,230]
Oot: (2, 5, 230)

除了使用
np.tile
,您还可以使用列表理解来实现这一点:

将numpy导入为np
n=6#您的NxN矩阵由以下命令决定
s=[i代表范围(n)内的i]
s=[s]*n
mat=np.数组

列表理解使满足此类用例变得非常容易,但在这种特殊情况下,
np.tile
已经满足了您的用例。

我测试了大量不同方法的计时,发现
np.lib.stride\u技巧。as\u stride
是最快的:

r = np.arange(256)
s = r.shape[0]
%timeit np.tile(r, (s,1))
%timeit np.lib.stride_tricks.as_strided(r, shape = (s, s), strides = (0, r.itemsize))
%timeit np.zeros(r.shape[0])[:, None] + r
%timeit (np.arange(s * s)%s).reshape((s, s))
%timeit np.array([[i for i in range(256)]]*256)
输出:
你能分享一些你面临问题的代码吗?请在提问时展示您的尝试。我只能用随机数创建矩阵,如M=np.random.randint(0255,size=(256256))print(M)我有一个问题,我无法创建这种情况,我需要一些帮助来创建这种矩阵
r = np.arange(256)
s = r.shape[0]
%timeit np.tile(r, (s,1))
%timeit np.lib.stride_tricks.as_strided(r, shape = (s, s), strides = (0, r.itemsize))
%timeit np.zeros(r.shape[0])[:, None] + r
%timeit (np.arange(s * s)%s).reshape((s, s))
%timeit np.array([[i for i in range(256)]]*256)
23.4 µs ± 658 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
10.5 µs ± 106 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
91 µs ± 3.15 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
313 µs ± 23.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
5.45 ms ± 307 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)