raptor96 - 1 year ago 213
Python Question

# alternate of spsolve and spdiag in matlab/octave

I have a python code which I am trying to convert to Matlab code. 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. Is there any alternate function that I can use?

Its quite easy if you know what spsolve does. Lets focus on that, as `spidiag` seems easier to solve, doesn't it?

`spsolve` "Solve the sparse linear system Ax=b, where b may be a vector or a matrix."

This is exactly what MATLABs`\` or `mldivide` does, it solves a system of Ax=b, for x. Happily for you, MATLAB can deal with both sparse and dense matrix with the same function, thus the change shoudl be as easy as:

from:

``````z = spsolve(Z, w*y)
``````

to:

``````z= Z\(w*y);
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download