%% Create Sparse Matrix with Nonzero Columns
% Use spalloc to initialize a 20-by-20 all-zero sparse matrix with space for 100 nonzero elements.

n = 20;
S = spalloc(n,n,5*n);

% Then use a for loop to fill in the columns of S one at a time with an average of at most five nonzero elements per column.

for j = 1:n
    S(:,j) = [zeros(n-5,1); round(rand(5,1))];
end

% Plot the sparsity pattern of matrix S. The dots represent the nonzero elements.

spy(S)

% Show the number of nonzero elements in the matrix.

n1 = nnz(S)

% Show the amount of storage allocated for nonzero matrix elements.

n2 = nzmax(S)

%
% Copyright 2020 The MathWorks, Inc.