user142756
user142756

Reputation: 1

Putting a matrix in to sparse form in linear time using matlab

I'm trying to put a matrix in sparse form, and so far I'm looping through the rows and columns checking every element to see if it's non zero. However, this seems to be order n^2, where n is the number of non zero elements in the matrix. Is there a way to do this order n?

Here is my code

function a = inputMatrix(X)




[m,n] = size(X);


k=1;
for i=1:m


   for j=1:n


       if X(i,j)~=0
           X(i,j);




           a(1,k) = struct('row',i,'column',j,'data',X(i,j));




           k = k+1;




       end




   end


end

Here is my time testing

ri = zeros(250,250);
rj = zeros(250,250);
rk = zeros(100,100);








for i=1:10000
    ri(i) = randi([-10000,10000],1,1);
end
tic;
inputMatrix(ri);
time(1) = toc;




for i=1:5000
    rj(i) = randi([-10000,10000],1,1);
end


tic;
inputMatrix(rj);
time(2) = toc;








for i=1:1000
    rk(i) = randi([-10000,10000],1,1);
end


tic;
inputMatrix(rj);
time(3) = toc;

Results:

time = 1.8009 0.5619 0.5545 no. non zero entires = 10 000, 5000, 1000

The results suggest there is a non linear relationship, and not order N

Upvotes: 0

Views: 63

Answers (1)

Daniel
Daniel

Reputation: 36710

find gives you the indices of nonzero elements and sparse converts the matrix directly to a sparse matrix.

Upvotes: 2

Related Questions