Friday, November 9, 2012

Handling Sparse matrices in Matlab

Matlab has its own memory limits due to which we have to define very large matrices
as sparse and use them. But we can not use them exactly the same way as normal matrice
due to difference in the way of storage. In my case, I have to define neighborhodd of 
pixels in an image which is usually of large size(307200 for a 640x480 image!!!). So,
the nbrhood matrix (lets call it adj) is now of size 307200x307200, which is huge.
I posted this in stackoverflow and had a beautiful discussion over the forum.
>>nNodes = 50400;
>>adj = sparse(nNodes,nNodes); %adj is a large sparse matrix with all values as zero.
I want to insert a 1 to adj(i,j) if pixel i and j are adjacent.
>>adj(sub2ind([nNodes nNodes], ind, ind + 1)) = 1; %ind is a vector of indices
??? Maximum variable size allowed by the program is exceeded.
Therefore, it is better to define adj in the following way, where definition
and updation take place in one shot. 
>>adj = sparse(ind, ind + 1, ones(size(ind)), nNodes, nNodes, length(ind));
Now, how do we access sparse matrix elements?
In a general matrix, we can access and modify the elements, 
either by using 2-dimensional indexing  or linear indexing.
for example,
>> a = [ 1 2 3; 4 5 6]
a =
     1     2     3
     4     5     6

>> a(1,2)
ans =

>> a(3)
ans =

>> i = find(a == 2)
i =
>> [i,j] = find(a == 2)
i =
j =

But we do not have the luxury to access using linear index 
for sparse matrices.
If I want to access non-zero elements of sparse matrix, I have to 
access the following way:
>> [i,j] = find(adj); 

The elements with higher indices must be accessed with 
2-dimensional indexing:

>> adj(nNodes, nNodes)
ans =

>> adj(nNodes * nNodes)
??? Maximum variable size allowed by the program is exceeded.
That's it with sparse matrices for the time being. :)

No comments:

Post a Comment