将matlab中的单元数组转换为R中的列表
我正在将一个单元格数组转换为R。 在MATLAB中,我使用x=cell10,n。我希望在循环中为每个单元格分配一个矩阵,如下所示:将matlab中的单元数组转换为R中的列表,r,matlab,R,Matlab,我正在将一个单元格数组转换为R。 在MATLAB中,我使用x=cell10,n。我希望在循环中为每个单元格分配一个矩阵,如下所示: for i in 1:10 for j in 1:n x(i,j) = [i*ones(len,1), ones(len,j)] 这里的n等于列数。 我在R怎么做? 我试过R中的列表,我猜这个x看起来像是包含10个列表,每个列表有n个子列表,每个子列表有一个矩阵。这是正确的吗 图中显示了在Matlab中生成的第一个循环。n=7。第一行在每个单元格中包含一个数
for i in 1:10
for j in 1:n
x(i,j) = [i*ones(len,1), ones(len,j)]
这里的n等于列数。
我在R怎么做?
我试过R中的列表,我猜这个x看起来像是包含10个列表,每个列表有n个子列表,每个子列表有一个矩阵。这是正确的吗
图中显示了在Matlab中生成的第一个循环。n=7。第一行在每个单元格中包含一个数值矩阵。
我想要得到的是能够通过使用
x[1][1] in R
参考文献
答:根据上面的链接,代码如下:
x<-NULL
for (i in 1:10){
test<-NULL
for (j in 1:n){
test[[j]]<-matrix
}
x[[i]]<-test
}
首先,指定输出中的行数和列数,并定义一个函数来返回输出矩阵中每个元素的内容
n_rows <- 5
n_cols <- 7
get_element <- function(i, j)
{
len <- 10
cbind(rep.int(i, len), matrix(1, len, j))
}
可以使用例如结果[[3,5]]访问单个矩阵
请注意,虽然带维度的列表最接近于MATLAB单元数组,但它是一种很少使用的数据结构。这意味着您将不会使用这种结构编写惯用的R代码。从MATLAB中的编码到R中的编码,一个最大的思想转变是从矩阵思维到向量思维
在这种情况下,一个明显的问题是为什么需要存储所有这些矩阵?。只需调用get_元素并根据需要检索值可能会更容易。这确实令人困惑。你到底想要什么作为输出?@最近的邮件请看图片,谢谢!那张照片来自哪里?这是matlab代码吗?R没有单元数组。不能将矩阵存储在普通矩阵中。您可以创建一个列表矩阵,但这些并不总是很容易使用。@MrFlick是的,这是我编写的一个matlab代码。还有更好的建议吗?x=vector'list',n有意义吗?您可以在列表中存储矩阵,具有类似矩阵的维度:matrixlistmatrix1:3、matrix2:4、matrix3:5、matrix4:6、nrow=2。正如@MrFlick所指出的那样,使用这些矩阵会很麻烦。
n_rows <- 5
n_cols <- 7
get_element <- function(i, j)
{
len <- 10
cbind(rep.int(i, len), matrix(1, len, j))
}
index <- arrayInd(seq_len(n_rows * n_cols), c(n_rows, n_cols))
result <- mapply(get_element, index[, 1], index[, 2])
dim(result) <- c(n_rows, n_cols)
result
## [,1] [,2] [,3] [,4] [,5] [,6] [,7]
## [1,] Numeric,20 Numeric,30 Numeric,40 Numeric,50 Numeric,60 Numeric,70 Numeric,80
## [2,] Numeric,20 Numeric,30 Numeric,40 Numeric,50 Numeric,60 Numeric,70 Numeric,80
## [3,] Numeric,20 Numeric,30 Numeric,40 Numeric,50 Numeric,60 Numeric,70 Numeric,80
## [4,] Numeric,20 Numeric,30 Numeric,40 Numeric,50 Numeric,60 Numeric,70 Numeric,80
## [5,] Numeric,20 Numeric,30 Numeric,40 Numeric,50 Numeric,60 Numeric,70 Numeric,80
result[[3, 5]]
## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] 3 1 1 1 1 1
## [2,] 3 1 1 1 1 1
## [3,] 3 1 1 1 1 1
## [4,] 3 1 1 1 1 1
## [5,] 3 1 1 1 1 1
## [6,] 3 1 1 1 1 1
## [7,] 3 1 1 1 1 1
## [8,] 3 1 1 1 1 1
## [9,] 3 1 1 1 1 1
## [10,] 3 1 1 1 1 1