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 elements
idx = 0;
for i = 1:dimRow
    for j = 1:dimCol
        if a(i,j) ~= 0
            idx = idx + 1;
            d(idx) = a(i,j);
            ridx(idx) = i;
            cidx(idx) = j;
        end
    end
end
end
849 chars
35 lines

gistlibby LogSnag