Apply function to nonzero sparse matrix elements
This operation preserves the sparsity of the original matrix
func returns zero for some nonzero elements of
Create a 4-by-4 sparse diagonal matrix.
S = diag(sparse(1:4))
S = (1,1) 1 (2,2) 2 (3,3) 3 (4,4) 4
Apply the exponential function to the nonzero elements of
S. The resulting matrix has the same sparsity pattern as
F = spfun(@exp,S)
F = (1,1) 2.7183 (2,2) 7.3891 (3,3) 20.0855 (4,4) 54.5982
spfun only applies to nonzero elements of
S, the value of
F(i) is zero whenever
S(i) is zero. This is different from applying the function to all elements of
S. For example, compare the result to applying the exponential function to all elements of
exp(S) function returns
1 for the elements of
S that are
ans = 4×4 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
Create a random
50 sparse matrix with density
0.02, where the matrix has
50 nonzero elements. Plot the sparsity pattern of the matrix
rng default; S = sprand(50,50,0.02); spy(S)
Evaluate the quadratic function to the nonzero elements of
S. The evaluated function using
spfun has the same sparsity pattern as the matrix
fun = @(x) x.^2 + x + 1; F = spfun(fun,S); spy(F)
S— Input matrix
Input matrix. This matrix is typically (but not necessarily) sparse.
S is a full matrix, then
F = spfun(func,S)
applies the function
func to the nonzero elements of
S and returns
F as a sparse matrix.
Complex Number Support: Yes
func— Function to apply
Function to apply to the elements of the input array, specified as a function
handle. The function should operate on
S element-wise. For more
information about function handles, see Create Function Handle.
func returns zero for inputs that are zero, you can use
func(S) to return the same results as calling
spfun on a sparse matrix
backgroundPoolor accelerate code with Parallel Computing Toolbox™
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
This function fully supports GPU arrays. For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).
Usage notes and limitations:
On each worker,
fun receives as input only the nonzero elements
S that are local to the worker. Therefore, functions that operate
element-wise are the most appropriate for use with
For more information, see Run MATLAB Functions with Distributed Arrays (Parallel Computing Toolbox).