如何在轴= 1处附加一维数组

时间:2019-05-28 09:44:38

标签: python numpy

我正在获取尺寸(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)维数组。

1 个答案:

答案 0 :(得分:1)

state必须是列向量,乘法才能起作用。目前它只是一维数组。您可以添加一个单例维度,也可以将state做成一个单行的2D数组并转置:

state=np.array([2,3])[:,None] 

OR

state=np.array([[2,3]]).T

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

  1. 您需要将state复制到trajectory。现在,您只为其提供了一个切片,因此修改trajectory也会修改state

  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