简体   繁体   English

在MATLAB / Octave中交替使用spsolve和spdiag

[英]alternate of spsolve and spdiag in matlab/octave

I have a python code which I am trying to convert to Matlab code. 我有一个python代码,我正在尝试将其转换为Matlab代码。 The code is for baseline correction for a wave. 该代码用于波浪的基线校正。

def baseline_als(y, lam, p, niter=20):
    L = len(y)
    D = sparse.csc_matrix(np.diff(np.eye(L), 2))
    w = np.ones(L)
    for i in xrange(niter):
        W = sparse.spdiags(w, 0, L, L)
        Z = W + lam * D.dot(D.transpose())
        z = spsolve(Z, w*y)
        w = p * (y > z) + (1-p) * (y < z)
    return z

I have tried it converting like this. 我已经试过像这样转换。

function [z] = baseline_als(y, lam, p, niter=20)
    L = len(y)
    D = sparse.csc_matrix(diff(eye(L), 2))
    w = ones(L)
    for i = 1:niter
        W = sparse.spdiags(w, 0, L, L) %Not working
        Z = W + lam * dot(D,transpose(D))
        z = spsolve(Z, w*y) % Not working
        w = p * (y > z) + (1-p) * (y < z)
    end % End of For loop
end % End of function

However there are no functions named spsolve and spdiag in octave/matlab. 但是,在octave / matlab中没有名为spsolvespdiag函数。 Is there any alternate function that I can use? 我可以使用其他功能吗?

Its quite easy if you know what spsolve does . 如果您知道spsolve的作用,那就很容易 Lets focus on that, as spidiag seems easier to solve , doesn't it? 让我们专注于这一点, 因为spidiag似乎更容易解决 ,不是吗?

spsolve "Solve the sparse linear system Ax=b, where b may be a vector or a matrix." spsolve “解决稀疏线性系统Ax = b的,其中b可以是矢量或矩阵。”

This is exactly what MATLABs \\ or mldivide does, it solves a system of Ax=b, for x. 这正是MATLABs \\mldivide所做的,它解决了x的Ax = b的系统。 Happily for you, MATLAB can deal with both sparse and dense matrix with the same function, thus the change shoudl be as easy as: 对您来说,MATLAB可以处理具有相同功能的稀疏矩阵和稠密矩阵,因此,更改如下:

from: 从:

z = spsolve(Z, w*y)

to: 至:

z= Z\(w*y);

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

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