Sparse Function for any matrix - Programmers Heaven

#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

#### Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

# Sparse Function for any matrix

Posts: 1Member
edited October 2013 in Matlab

I am trying to write a sparse function code for any matrix size. For example if i have a matrix:

A = [ 0   0   0   5
0   2   0   0
1   3   0   0
0   0   4   0];
a=size(A);
b=size(A);
c=0;
position=0;
for i=1:a for j=1:b if A(i,j) ~=0
c=c+1;
position=position+1;
S(c,:)=[position,i,j,A(i,j)];
end
end
end
S

S --> is the storage matrix for all the non zero elements for A matrix. In addition to this information(Index,Row Number, Column Number, Value) how do I include two more columns in the matrix which shows the next element in row & the next element in column.

Tagged: