简体   繁体   English

使用Numpy将MATLAB切片转换为Python

[英]Converting MATLAB Slicing into Python using Numpy

I am having trouble converting some MATLAB code into python. 我在将一些MATLAB代码转换为python时遇到问题。 I am trying to build a signal by adding in shifted copies of base signal into a much longer one. 我试图通过将基本信号的移位副本添加到更长的信号中来构建信号。 The code that works in MATLAB is 在MATLAB中工作的代码是

function [time, signal] = generateRandomSignal(pulse,data,samples,Tb)
N = length(data);
time = linspace(0,N*Tb,samples*N);
signal = zeros(1,length(time));
k = 1;
for n = 1:N
        window = k:k+samples-1;
        signal(window) = signal(window) + data(n)*pulse;
        k = k + samples;
end

In python using the variable to slice the larger array wasn't working so I changed that but now I got what I think should work but I keep getting errors about inconsistent array sizes even though when I inspect the sizes in a debugger it looks like it should work. 在使用变量切片的python中,较大的数组不起作用所以我改变了但是现在我得到了我认为应该工作的但是我不断得到关于不一致的数组大小的错误,即使我在调试器中检查大小时看起来像它应该管用。

from numpy import *
def generateRandomSignal(pulse,data,samples,Tb):
    N = data.size;
    time = linspace(0,N*Tb,samples*N);
    signal = zeros((1,time.size));
    k = 0;
    for n in range(0,N):
            signal[k:k+samples] = signal[k:k+samples].copy() + data[n]*pulse[:].copy();
            k = k + samples;
    return time, signal

What is the correct way to do this in Python? 在Python中执行此操作的正确方法是什么?

EDIT: Minimal expected input and output 编辑:最小的预期输入和输出

Input
  data = [1, -1, 0, 1, 1]
  pulse = [1, 1, 1]
  samples = 3. #length of pulse
  Tb = 0.1

Output
  signal = [1, 1, 1, -1, -1, -1, 0, 0, 0, 1, 1, 1, 1, 1, 1]
  time = vector of 15 points evenly spaced from 0 to 0.3.  (Not the problem)

EDIT2 Error EDIT2错误

ValueError: operands could not be broadcast together with shapes (1920,) (1,4410)

That is the actual error produced. 这就是产生的实际错误。 (1,4410) is the correct shape for the pulse array but I have no idea where the 1920 is coming from or what the empty comma means (1,4410)是脉冲阵列的正确形状,但我不知道1920来自哪里或空逗号是什么意思

Change your definition of signal to signal = zeros(time.size) . 改变你的清晰度signalsignal = zeros(time.size) Unlike Matlab, NumPy's 1D arrays have shape (N,) , not (N,1) . 与Matlab不同,NumPy的一维阵列具有形状(N,) ,而不是(N,1)

I can't see why you should have 0 index in signal: 我不明白为什么你应该在信号中有0个索引:

signal[0,k:k+samples] = signal[0,k:k+samples].copy() + data[n]*pulse[:].copy(); signal [0,k:k + samples] = signal [0,k:k + samples] .copy()+ data [n] * pulse [:]。copy();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM