%% Apply Exponential Function to Sparse Matrix
% Create a 4-by-4 sparse diagonal matrix.

S = diag(sparse(1:4))

% Apply the exponential function to the nonzero elements of S. The resulting matrix has the same sparsity pattern as S.

F = spfun(@exp,S)

% Because 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 S. The exp(S) function returns 1 for the elements of S that are 0s.

full(exp(S))

%
% Copyright 2020 The MathWorks, Inc.