将mxn矩阵转换成n* mx3矩阵。

时间:2021-06-22 04:39:13

I currently have a matrix that is 479 x 729, and I would like to convert this matrix into a three column matrix such that the first column is the row entry of the original matrix, the second column is the column entry of the original matrix, and the third column is the value at that column and row entry.

我目前有一个矩阵是479 x 729,我想这个矩阵转化为一个三列矩阵,第一列是原始矩阵的行条目,第二列是原始矩阵的列条目,第三列的值列和行条目。

Is there an easy way to do this? I have looked at the reShape function but have not figured out how to apply this here. The motivation for this is to be able to create a distance table for elements within the matrix that includes their location.

有没有一种简单的方法?我已经看了整形功能但还没有想到如何应用这个。这样做的动机是能够为包含其位置的矩阵中的元素创建一个远程表。

2 个解决方案

#1


1  

There's probably a better or more clever way, but this seems straight-forward and fast enough:

也许有一个更好或更聪明的方法,但这似乎是直接和足够快的:

m <- matrix(rnorm(349191), 479, 729)

row_num <- as.vector(row(m))
col_num <- as.vector(col(m))
val <- as.vector(m)

new_m <- as.matrix(cbind(row_num, col_num, val))

dim(new_m)
# [1] 349191      3

head(new_m)
#      row_num col_num          val
# [1,]       1       1 1.0839690124
# [2,]       2       1 0.7363313818
# [3,]       3       1 0.0001195304
# [4,]       4       1 0.2123100877
# [5,]       5       1 0.1293427830
# [6,]       6       1 1.1773676868

tail(new_m)
#           row_num col_num         val
# [349186,]     474     729 -0.07942063
# [349187,]     475     729 -0.25694755
# [349188,]     476     729 -0.69421258
# [349189,]     477     729  1.24861689
# [349190,]     478     729  0.24377606
# [349191,]     479     729  0.49150676

#2


1  

You can use:

您可以使用:

library(reshape2)
melt(M)

where M is your matrix

你的矩阵在哪?

#1


1  

There's probably a better or more clever way, but this seems straight-forward and fast enough:

也许有一个更好或更聪明的方法,但这似乎是直接和足够快的:

m <- matrix(rnorm(349191), 479, 729)

row_num <- as.vector(row(m))
col_num <- as.vector(col(m))
val <- as.vector(m)

new_m <- as.matrix(cbind(row_num, col_num, val))

dim(new_m)
# [1] 349191      3

head(new_m)
#      row_num col_num          val
# [1,]       1       1 1.0839690124
# [2,]       2       1 0.7363313818
# [3,]       3       1 0.0001195304
# [4,]       4       1 0.2123100877
# [5,]       5       1 0.1293427830
# [6,]       6       1 1.1773676868

tail(new_m)
#           row_num col_num         val
# [349186,]     474     729 -0.07942063
# [349187,]     475     729 -0.25694755
# [349188,]     476     729 -0.69421258
# [349189,]     477     729  1.24861689
# [349190,]     478     729  0.24377606
# [349191,]     479     729  0.49150676

#2


1  

You can use:

您可以使用:

library(reshape2)
melt(M)

where M is your matrix

你的矩阵在哪?