[英]How should I subtract two vectors or matrices from each other without NumPy?
[英]How to assign values from two matrices to each other in sequence?
根据示例,我尝试将第二个矩阵中的值分配给第一个润滑器中的值。 首先,我通过矩阵 b 中的最后一行 go 并逐渐将矩阵 d 中的值分配给它。 然后我在矩阵 b 中向上移动一行,在矩阵 d 中移动下一个 position 并且我也依次分配。 所以我继续到矩阵的末尾
例子
导入 numpy 作为 np
b=np.array([13,14,15,16,17],
[22,23,24,25,26],
[31,32,33,34,35])
d=np.array[100,200,300,400,500,600,700]
需要 output
31 100
32 200
33 300
34 400
35 500
22 200
23 300
24 400
25 500
26 600
13 300
14 400
15 500
16 600
17 700
谁能帮我这个?
**注意:我在语法上做了一些小修正。
-(负)索引将很有用。 您需要在 b 上迭代 -1,-2... 行。 -1 = 最后一行。 并使用行 id 在 d 中获取偏移量。
import numpy as np
b=np.array([[13,14,15,16,17],
[22,23,24,25,26],
[31,32,33,34,35]])
d=np.array([100,200,300,400,500,600,700])
for i in range(1, 1+len(b)):
for j in range(len(b[-i])):
print(b[-i][j], d[i+j-1])
为此,您可以重新排列b
的行并将它们按顺序水平堆叠。
然后通过将元素从 i 到 i + len(row(b)) 从数组d
中创建一个矩阵,其中 i 从 0 开始并在每个 epoch 后移位,然后按顺序水平堆叠行。
最后可以zip这两个arrays得到想要的结果
b=np.array([[13,14,15,16,17],
[22,23,24,25,26],
[31,32,33,34,35]])
d=np.array([100,200,300,400,500,600,700])
val1 = np.hstack(b[::-1])
val2 = np.hstack([d[i:i+b.shape[1]] for i in range(b.shape[0])])
res = zip(val1, val2)
for i, j in res:
print(i, j)
output:
31 100
32 200
33 300
34 400
35 500
22 200
23 300
24 400
25 500
26 600
13 300
14 400
15 500
16 600
17 700
如果您从d
数组中的索引a
数组预测,您可以尝试以下操作:
>>> order = b[::-1]
>>> idx = (order % 10) - 1
>>> np.stack([order.ravel(), d[idx].ravel()]).T
array([[ 31, 100],
[ 32, 200],
[ 33, 300],
[ 34, 400],
[ 35, 500],
[ 22, 200],
[ 23, 300],
[ 24, 400],
[ 25, 500],
[ 26, 600],
[ 13, 300],
[ 14, 400],
[ 15, 500],
[ 16, 600],
[ 17, 700]])
您可以将d
视为对应于翻转b
的矩阵:
v = np.lib.stride_tricks.as_strided(d, shape=b.shape, strides=d.strides * 2)
现在您可以将两者堆叠在一起:
result = np.ravel((b[::-1].ravel(), v.ravel()), axis=-1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.