Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R equivalent of the Matlab spy function

In Matlab, there is a function named spy, which displays the structure of a sparse matrix. It creates a plot of the matrix' dimensions where each entry that has a nonzero value is colored. Is there an equivalent function in R?

like image 660
nojka_kruva Avatar asked Apr 15 '15 15:04

nojka_kruva


1 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, it takes a little bit more work.

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

like image 143
alexforrence Avatar answered Nov 03 '22 07:11

alexforrence