R Equivalent to Matlab Spire Function

Matlab has a spy function that displays the structure of a sparse matrix. It creates a graph of matrix sizes, where each record that has a nonzero value is colored. Is there an equivalent function in R?

+5
source share
2 answers

image() from Matrix is one option.

 library(Matrix) # Example from ?Matrix:::sparseMatrix i <- c(1,3:8); j <- c(2,9,6:10); x <- 7 * (1:7) A <- sparseMatrix(i, j, x = x) print(A) ##8 x 10 sparse Matrix of class "dgCMatrix" ##[1,] . 7 . . . . . . . . ##[2,] . . . . . . . . . . ##[3,] . . . . . . . . 14 . ##[4,] . . . . . 21 . . . . ##[5,] . . . . . . 28 . . . ##[6,] . . . . . . . 35 . . ##[7,] . . . . . . . . 42 . ##[8,] . . . . . . . . . 49 image(A) 

enter image description here


To get the output of spy() in R, a bit more work is required.

In MATLAB (2011b):

 spy() h = gcf; axObj = get(h, 'Children'); datObj = get(axObj, 'Children'); xdata = get(datObj,'XData'); ydata = get(datObj,'YData'); spyMat = [xdata; ydata]; csvwrite('spydat.csv',spyMat); 

And in R:

 library(Matrix) spyData <- read.csv("spydat.csv") spyMat <- t(sparseMatrix(spyData[1,],spyData[2,])) image(spyMat) 

enter image description here

+8
source

A simple function that duplicates the spy () function of Matlab in R is based on the following ideas:

  library(Matrix) spy <- function(w){ # Get indices not equal to zero inds <- which(w != 0, arr.ind=TRUE ) # Create sparse matrix with ones where not zero A <- sparseMatrix(inds[,1], inds[,2], x = rep(1,nrow(inds))) # image(A)) } 

This may be useful for some applications.

0
source

All Articles