In a Matlab script create a standard non-sparse matrix with size 500 × 3 (500 rows, 3 columns). All entries in columns 1 and 3 should be −1 and all entries in column 2 should have the value 2.
Use the spdiags function to create a 500 × 500 sparse tri-diagonal matrix, A. The diagonal and 2 off-diagonals should be the columns of the 500 × 3 matrix. Next create a non-sparse version of A (using the `full’ function) and call it B. Use the `whos’ command to compare the sizes (in computer memory) of the 2 matrices. Using the `tic’ and `toc’ functions compare how long it takes to calculate A^2 and B^2 . Is there much of a difference?
Expert Answer
%non-sparse matrix
A = zeros(500,3)
for k=1:500
A(k,1) = -1;
A(k,2) = 2;
A(k,3) = -1;
end
%creating spatse matrix
S = sparse(A);
%executing whos command
whos A
whos S
%not calculating A2 and B2
tic
A1 = A.*A
toc
S1 = S.*S
toc
OUTPUT
Non-sparse takes
Elapsed time is 0.037461 seconds.
Sparse matrix takes
Elapsed time is 0.075629 seconds.
So finally there is time difference observed in both multiplication of sparse and non-sparse matrices.