python - 如何在axis = 1处附加一维数组
问题描述
我正在获取尺寸(2,1)的样本。我正在尝试将它们堆叠成列。
我尝试了以下方法:
# My initial state
state=np.array([2,3])
trajectory =state
# the following generate the next samples
class Buck:
""" The following code simulates a Buck converter """
def __init__(self,state,control):
self.control=control
self.state=state
def Next_State(self):
L, C = 1.0, 1.0
R, G = 1.0, 1.0
delta = 0.001
Q = np.array([[-1.0/L,0.0],[0.0,1.0/C]])
A = Q*np.matmul(Q,np.array([[R,1.0],[1.0,-G]]))
next_state = state + delta*np.matmul(A,state)
return next_state
# Here I am appending the new samples to trajectory
for i in range(100000):
state=Buck.Next_State(state)
np.append(trajectory,state,axis=1)
就是说我不能将 (2,) 维数组转换为 (2,2) 维数组。
解决方案
state
需要是乘法工作的列向量。它目前只是一个一维数组。您可以添加单个维度,也可以制作state
单行的二维数组并转置:
state=np.array([2,3])[:,None]
或者
state=np.array([[2,3]]).T
但是,如果您的任务是将所有状态附加到轨迹中,那么您需要再更改两件事:
您需要制作 to 的新
state
副本trajectory
。现在,您只为其提供一个切片,因此修改trajectory
也会修改state
.np.append
输出新附加的数组。您没有捕获该方法的输出,因此您实际上没有附加任何内容。
所以:
# My initial state
import numpy as np
state=np.array([2,3])[:,None] # Change
trajectory =state.copy() # Change
# the following generate the next samples
class Buck:
""" The following code simulates a Buck converter """
def __init__(self,state,control):
self.control=control
self.state=state
def Next_State(self):
L, C = 1.0, 1.0
R, G = 1.0, 1.0
delta = 0.001
Q = np.array([[-1.0/L,0.0],[0.0,1.0/C]])
A = Q*np.matmul(Q,np.array([[R,1.0],[1.0,-G]]))
next_state = state + delta*np.matmul(A,state)
return next_state
# Here I am appending the new samples to trajectory
for i in range(100000):
state=Buck.Next_State(state)
trajectory = np.append(trajectory,state,axis=1) # Change
推荐阅读
- html - 固定页脚粘在底部向右移动
- dataweave - 在dataweave 2.0中的字符串中插入字符
- python - 接收邮件,并根据条件重新发送到另一个电子邮件服务器
- css - 当按钮是图片时,文本也有规定的大小和间距。如何通过CSS让文字出现在图片中间?
- json - 如何更新数组中单个项目的现有 jsonb 数组属性
- kubernetes - 系统设计 - 如何为应用程序选择 CPU、内存
- node.js - 使用 NodeJS、MongoDB 和 Mongoose 时将 mongoose 查询数组更改为字符串
- apache - htaccess 保留 url 而不重定向
- vb.net - “System.Reflection.TargetException:对象与目标类型不匹配”尝试使用 property.setvalue 调用时抛出异常
- c++ - 为堆栈和堆分配的窗口对象正确实现 CWindowImpl::OnFinalMessage