This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.


Apply function to nonzero sparse matrix elements


f = spfun(fun,S)


The spfun function selectively applies a function to only the nonzero elements of a sparse matrix S, preserving the sparsity pattern of the original matrix (except for underflow or if fun returns zero for some nonzero elements of S).

f = spfun(fun,S) evaluates fun(S) on the elements of S that are nonzero. fun is a function handle.

Parameterizing Functions explains how to provide additional parameters to the function fun, if necessary.


Given the 4-by-4 sparse diagonal matrix

S = spdiags([1:4]',0,4,4)

S = 
   (1,1)        1
   (2,2)        2
   (3,3)        3
   (4,4)        4

Because fun returns nonzero values for all nonzero element of S, f = spfun(@exp,S) has the same sparsity pattern as S.

f =
   (1,1)       2.7183
   (2,2)       7.3891
   (3,3)      20.0855
   (4,4)      54.5982

whereas exp(S) has 1s where S has 0s.


ans =
    2.7183    1.0000    1.0000    1.0000
    1.0000    7.3891    1.0000    1.0000
    1.0000    1.0000   20.0855    1.0000
    1.0000    1.0000    1.0000   54.5982


Functions that operate element-by-element, like those in the elfun directory, are the most appropriate functions to use with spfun.

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

Introduced before R2006a