Main Content

spfun

Apply function to nonzero sparse matrix elements

Description

example

F= spfun(func,S)applies the functionfuncto the nonzero elements of a sparse matrixS. The input argumentfuncis a function handle to a function that takes one input argument.

This operation preserves the sparsity of the original matrixSunless the functionfuncreturns zero for some nonzero elements ofS.

Examples

collapse all

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 ofS. The resulting matrix has the same sparsity pattern asS.

F = spfun(@exp,S)
F = (1,1) 2.7183 (2,2) 7.3891 (3,3) 20.0855 (4,4) 54.5982

Becausespfunonly applies to nonzero elements ofS, the value ofF(i)is zero wheneverS(i)is zero. This is different from applying the function to all elements ofS. For example, compare the result to applying the exponential function to all elements ofS. Theexp(S)function returns1for the elements ofSthat are0s.

full(exp(S))
ans =4×42.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 random50-by-50sparse matrix with density0.02, where the matrix has50nonzero elements. Plot the sparsity pattern of the matrixS.

rngdefault; S = sprand(50,50,0.02); spy(S)

Figure contains an axes object. The axes object contains an object of type line.

Evaluate the quadratic function x 2 + x + 1 to the nonzero elements ofS. The evaluated function usingspfunhas the same sparsity pattern as the matrixS.

fun = @(x) x.^2 + x + 1; F = spfun(fun,S); spy(F)

Figure contains an axes object. The axes object contains an object of type line.

Input Arguments

collapse all

Input matrix. This matrix is typically (but not necessarily) sparse.

IfSis a full matrix, thenF = spfun(func,S)applies the functionfuncto the nonzero elements ofSand returnsFas a sparse matrix.

Data Types:double|logical
Complex Number Support:Yes

Function to apply to the elements of the input array, specified as a function handle. The function should operate onSelement-wise. For more information about function handles, seeCreate Function Handle.

Example:@(n) n+1

Tips

  • Iffuncreturns zero for inputs that are zero, you can usefunc(S)to return the same results as callingspfunon a sparse matrixS.

Extended Capabilities

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

Version History

Introduced before R2006a