the function mat2coord should take an n × n array representing a matrix a ∈ r n×n and return the sparse coordinate representation encoded by the three arrays, d, ridx, and cidx in matlab
main.m
function[d, ridx, cidx] = mat2coord(a)%{
This function takes a n × n array representing a matrix a ∈ Rⁿⁿ
and returns the sparse coordinate representation encoded by
the three arrays, d, ridx, and cidx in MATLAB.
Args:
a: n x n matrix
Returns:
d: array containing values of non-zero entries of a
ridx: array showing the row coordinate values of non-zero entries of a
cidx: array showing the column coordinate values of non-zero entries of a
%}
% Preallocate the array sizes[dimRow, dimCol] = size(a);
d = zeros(1, nnz(a));
ridx = zeros(1, nnz(a));
cidx = zeros(1, nnz(a));
% Loop through sparse matrix capturing the non-zero elementsidx = 0;
fori = 1:dimRow
forj = 1:dimCol
if a(i,j) ~= 0 idx = idx + 1;
d(idx) = a(i,j);
ridx(idx) = i;
cidx(idx) = j;
endendendend