从稀疏矩阵中提取i和j [英] Extract i and j from a sparse Matrix
问题描述
我可以使用i的向量来定义稀疏矩阵, j和x:
I can define a sparse Matrix using a vector for i, j, and x:
i <- c(1,3:8)
j <- c(2,9,6:10)
x <- 7 * (1:7)
(A <- sparseMatrix(i, j, x = x))
我想从这个稀疏矩阵中提取i
,j
和x
元素,因此我可以在另一个程序包中重新创建该矩阵.使用i
和x
很容易:
I want to extract the i
, j
, and x
elements from this sparse matrix, so I can re-create the matrix in another package. This is easy with i
and x
:
i <- A@i + 1
x <- A@x
(请注意,i和x的顺序已更改,但是它们的相对关联是相同的:i = 4仍与x = 21位于同一位置)
(Note that the order of i and x has changed, but their relative association is the same: i=4 is still in the same place as x=21)
但是,稀疏矩阵的最后一个元素是p
:指针的数字(整数值)向量,每列(或行)一个,指向元素中初始(从零开始)索引.列(或行)."
However, the last element of the sparse matrix is p
: "a numeric (integer valued) vector of pointers, one for each column (or row), to the initial (zero-based) index of elements in the column (or row)."
如何将A@i
和A@p
转换为用于定义矩阵的原始j
元素?
How can I convert A@i
and A@p
into the original j
element used to define the matrix?
推荐答案
弄清楚列的存储方式有些棘手.我很难解释,但是也许代码可以帮助您了解正在发生的事情:
It is a little tricky to figure out how columns is stored. I have a hard time explaining it, but maybe the code will help you get what is going on:
# Rows
A@i+1
# [1] 1 4 5 6 3 7 8
# Cols (a little tricky..)
findInterval(seq(A@x)-1,A@p[-1])+1
# [1] 2 6 7 8 9 9 10
# Values
A@x
# [1] 7 21 28 35 14 42 49
因此,在删除第一个元素之后,A@p
每列都有一个元素. A@p+1
的范围是1:length(A@x)
.基本上,对于每一列,它表示此列中出现的A@x
的第一个元素位于该A@x
的索引处.但是棘手的部分是,如果 nothing 位于该列中,那么它将使用最后一列的索引.那是我的错误解释...希望它将与代码结合使用.
So, after you remove the first element, A@p
has one element for every column. The range of A@p+1
is 1:length(A@x)
. Basically, for each column, it says that the first element of A@x
that occurs in this column is located at this index of A@x
. But the tricky part is that if nothing is located in that column, then it uses the index of the last column. That is my bad explanation... hopefully it will help in conjunction with the code.
这篇关于从稀疏矩阵中提取i和j的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!