Since you didn't specify the problem very clearly, I made some assumptions in the sample code below. Given a list of matrices, it saves them to a .bin
file and creates an .idx
file with offsets. You can then load them back in again given an index. The 2-byte size you mentioned isn't used - it saves the matrix data as 8-byte doubles or 4-byte integers (but you could change that).
Here's how it's used:
mtx <- list(matrix(1:12,4), matrix(sin(1:12),4))
saveMatrixList("c:/foo", mtx)
loadMatrix("c:/foo", 1)
loadMatrix("c:/foo", 2)
...and here are the functions:
saveMatrixList <- function(baseName, mtxList) {
idxName <- paste(baseName, ".idx", sep="")
idxCon <- file(idxName, 'wb')
on.exit(close(idxCon))
dataName <- paste(baseName, ".bin", sep="")
con <- file(dataName, 'wb')
on.exit(close(con))
writeBin(0L, idxCon)
for (m in mtxList) {
writeBin(dim(m), con)
writeBin(typeof(m), con)
writeBin(c(m), con)
flush(con)
offset <- as.integer(seek(con))
cat('offset', offset)
writeBin(offset, idxCon)
}
flush(idxCon)
}
loadMatrix <- function(baseName = "data", index) {
idxName <- paste(baseName, ".idx", sep="")
idxCon <- file(idxName, 'rb')
on.exit(close(idxCon))
dataName <- paste(baseName, ".bin", sep="")
con <- file(dataName, 'rb')
on.exit(close(con))
seek(idxCon, (index-1)*4)
offset <- readBin(idxCon, 'integer')
seek(con, offset)
d <- readBin(con, 'integer', 2)
type <- readBin(con, 'character', 1)
structure(readBin(con, type, prod(d)), dim=d)
}