如何将Matlab函数转换为Python

时间:2019-05-09 18:14:44

标签: python-2.7 matlab-figure translate

我正在尝试将曲线平滑功能从Matlab转换为python。我从Internet上获得了matlab脚本,并且对matlab本身不太熟悉,因此我不确定如何翻译所有元素。我不想使用编译器或调用我想直接转换功能的MATLAB文件!

MATLAB函数

function SmoothY=tsmooth(Y,smoothwidth,ends)
% The argument "ends" controls how the "ends" of the signal 
% (the first w/2 points and the last w/2 points) are handled.
%   If ends=0, the ends are zero.  (In this mode the elapsed 
%     time is independent of the smooth width). The fastest.
%   If ends=1, the ends are smoothed with progressively 
%     smaller smooths the closer to the end. (In this mode the  
%     elapsed time increases with increasing smooth widths).
w=round(smoothwidth);
SumPoints=sum(Y(1:w));
s=zeros(size(Y));
halfw=round(w/2);
L=length(Y);
for k=1:L-w,
   s(k+halfw-1)=SumPoints;
   SumPoints=SumPoints-Y(k);
   SumPoints=SumPoints+Y(k+w);
end
s(k+halfw)=sum(Y(L-w+1:L));
SmoothY=s./w;
% Taper the ends of the signal if ends=1.
  if ends==1,
  startpoint=(smoothwidth + 1)/2;
  SmoothY(1)=(Y(1)+Y(2))./2;
  for k=2:startpoint,
     SmoothY(k)=mean(Y(1:(2*k-1)));
     SmoothY(L-k+1)=mean(Y(L-2*k+2:L));
  end
  SmoothY(L)=(Y(L)+Y(L-1))./2;
  end

尝试的PYTHON功能:


def tsmooth(Y,smoothwidth, ends):
    w=smoothwidth
    SumPoints = np.sum(Y[1:w])
    s=np.zeros(np.shape(Y))
    halfw = int(w/2)
    L=len(Y)
    for k in range(1,L-w):
        s[k+halfw-1]=SumPoints
        SumPoints = SumPoints-Y[k]
        SumPoints = SumPoints+Y[k+w]
    if ends==1:
        s[k+halfw]=np.sum(Y[L-w+1:L])
        SmoothY=s/w
        startpoint=int((smoothwidth+1)/2)
        SmoothY[0]=(Y[0]+Y[1])/2;
        for k in range(2,startpoint):
            SmoothY[k]=np.mean(Y[1:(2*k-1)])
            SmoothY[L-k+1]=np.mean(Y[(L-2*k+2):L])
    SmoothY[L-1]=(Y[L-1]+Y[L-2])/2

如果将此功能应用于嘈杂的信号,则应使其平滑。预先感谢!

0 个答案:

没有答案