spfun
Applies a function to the nonzero elements of a sparse matrix.
Category: Mathematics > Sparse Matrices
Syntax
F = spfun(fun, S)
Evaluates fun on the nonzero entries of S and returns the results in the same positions.
Description
Zeros in S are never passed to fun. Compare exp(S), which turns every zero into 1 and gives a full matrix, with spfun(@exp, S), which leaves the zeros as zeros and keeps the result sparse. This is useful for functions where f(0) is not zero but the absent entries should stay absent.
Input arguments
fun- Function handle that works elementwise on a vector.
S- Sparse matrix.
Output arguments
F- Sparse matrix with the same size and pattern as
S.
Example
Applying exp to the nonzeros only
S = sparse([0 1; 2 0]);
F = spfun(@exp, S);
full(F)
nnz(F)
nnz(exp(S))
Output
ans = 2×2
0 2.7183
7.3891 0
ans = 2
ans = 4