gpt4 book ai didi

python - 如何在 axis=1 处追加一维数组

转载 作者:行者123 更新时间:2023-12-01 07:48:35 27 4
gpt4 key购买 nike

我正在获取维度 (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

但是,如果您的任务是将所有状态附加到轨迹中,那么您还需要更改两件事:

  1. 您需要将状态复制到轨迹。目前,您仅向其提供一个切片,因此修改轨迹也会修改状态

  2. 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

关于python - 如何在 axis=1 处追加一维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56339338/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com