首页 > 解决方案 > 如何在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) 维数组。

标签: pythonnumpy

解决方案


state需要是乘法工作的列向量。它目前只是一个一维数组。您可以添加单个维度,也可以制作state单行的二维数组并转置:

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

或者

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

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

  1. 您需要制作 to 的新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

推荐阅读