File Exchange Pick of the Week

Spy with color

Posted by Jiro Doke,

Jiro's pick this week is cspy by Hugo Gualdron.

spy allows you to visualize sparse matrices:

spy(bucky)

(Anyone know how to get the Easter egg for the spy function?)

spy is meant for displaying the positions of the nonzero elements in the sparse matrix. But if the sparse matrix contains multiple values (levels), it would be nice to visualize those levels as well. That's where cspy comes in. Take the following example:

BW = logical ([...
    0     0     0     0     0     0     0     0
    0     0     0     0     1     1     0     0
    0     0     0     0     1     0     0     0
    0     1     1     0     0     0     1     0
    0     1     1     1     0     0     1     0
    0     1     1     0     0     0     1     0
    0     1     0     0     0     1     1     0
    0     0     0     0     0     0     0     0]);
imshow(BW,'InitialMagnification','fit')

In the above black and white image, we can say that there are 3 white blobs. We can use the bwlabel function from the Image Processing Toolbox to identify the 3 regions and mark them with unique identifiers.

L = bwlabel(BW)
L =
     0     0     0     0     0     0     0     0
     0     0     0     0     2     2     0     0
     0     0     0     0     2     0     0     0
     0     1     1     0     0     0     3     0
     0     1     1     1     0     0     3     0
     0     1     1     0     0     0     3     0
     0     1     0     0     0     3     3     0
     0     0     0     0     0     0     0     0

You could imagine that this matrix L can be a highly sparse matrix with far more zeros than non-zero elements. Let's store this as a sparse matrix.

Ls = sparse(L)
Ls =
   (4,2)        1
   (5,2)        1
   (6,2)        1
   (7,2)        1
   (4,3)        1
   (5,3)        1
   (6,3)        1
   (5,4)        1
   (2,5)        2
   (3,5)        2
   (2,6)        2
   (7,6)        3
   (4,7)        3
   (5,7)        3
   (6,7)        3
   (7,7)        3

Even for this small example, you can see some memory savings.

whos L Ls
  Name      Size            Bytes  Class     Attributes

  L         8x8               512  double              
  Ls        8x8               328  double    sparse    

Now, we can use cspy to visualize Ls with different colors for the different values.

figure
cspy(Ls)

Wonderful!

In addition to this useful functionality, I really like the great help that's included. The function has a number of optional parameters to customize the plot, and Hugo explains each syntax in detail. He also includes a number of examples.

Comments

Do you work with sparse matrices? Do you have any custom visualizations for them? Let us know about them here. Or give cspy a try and leave a comment for Hugo.


Get the MATLAB code

Published with MATLAB® R2014a

Add A Comment

What is 6 + 10?

Preview: hide

These postings are the author's and don't necessarily represent the opinions of MathWorks.