本文介绍了将Matlab代码转换为python(scipy)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将此matlab代码转换为python:
I' trying to translate this matlab code to python:
T = length(z);
lambda = 10;
I = speye(T)
D2 = spdiags(ones(T-2,1)*[1 -2 1],[0:2],T-2,T);
z_stat = (I-inv(I + lambda^2*D2'*D2))*z;
我现在得到的是:
T = len(signal)
lam = 10;
I = np.identity(T)
D2 = scipy.sparse.spdiags(np.ones((T-2,1),dtype=np.int)*[1,-2,1],(range(0,3)),T-2,T);
此刻我收到此错误
查看文档时,matlab函数和python函数非常相似.虽然可能有一个我缺少的差异.现在的问题是:我在做什么错了?
When looking at the documentation, the matlab function and the python function are very similar. Though there is probably a difference which I am missing. My question is now: What am I doing wrong ?
编辑:z是一个长度为300的数组
edit: z is an array with length 300
推荐答案
如果将过滤器数据转置为spdiags,则在两个程序包中都得到相同尺寸的答案:
If you transpose the filter data to spdiags then you get an answer of the same dimensions in both packages:
# numpy/scipy
filt = [1,-2,1]* np.ones((1,T-2),dtype=np.int).T
D2 = scipy.sparse.spdiags(data.T, (range(0,3)),T-2,T)
np.shape(D2)
>>> (298, 300)
% matlab check
D2 = spdiags(ones(T-2,1)*[1 -2 1],[0:2],T-2,T)
size(D2)
ans =
298 300
这篇关于将Matlab代码转换为python(scipy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!