R语言中实现矩阵和三元组的相互转换

 

001、

1、矩阵转换为三元组

复制代码
num <- c(5, 2, 7, 0, 9, 3, 4, 2, 3, 1, 7, 8)
dat <- matrix(num, nrow = 3, ncol = 4, byrow = T)
dat

rows <- rep(1:nrow(dat), each = ncol(dat))    ## 行
rows
cols <- rep(1:ncol(dat), time = nrow(dat))    ## 列
cols

value <- c(t(dat))                            ## 值
value

result <- data.frame(rows, cols, value)
result
复制代码

 

 

2、三元组转换为矩阵 :

复制代码
result

rows <- max(result$rows)
cols <- max(result$cols)

dat <- matrix(0, nrow = rows, ncol = cols)
dat
for (i in 1:nrow(result)) {
  dat[result[i,1], result[i,2]] = result[i,3]      ## 三元组转换为矩阵
}
dat
复制代码

 

002、

1、矩阵转换为三元组

复制代码
num <- c(5, 2, 7, 0, 9, 3, 4, 2, 3, 1, 7, 8)
dat <- matrix(num, nrow = 3, ncol = 4, byrow = T)
dat

rows <- rep(1:nrow(dat), time = ncol(dat))
rows
cols <- rep(1:ncol(dat), each = nrow(dat))
cols
values <- as.vector(dat)
values

result <- data.frame(rows, cols, values)      ## 矩阵转换为三元组
result
复制代码

 

 

2、三元组转换为矩阵

复制代码
dat
rows <- max(dat$rows)
rows
cols <- max(dat$cols)
cols

result <- matrix(0, nrow = rows, ncol = cols)
result
for (i in 1:nrow(dat)) {                         ## 三元组转换为矩阵
  result[dat[i,1], dat[i,2]] = dat[i,3]
}
result
复制代码

 

posted @   小鲨鱼2018  阅读(729)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
历史上的今天:
2021-06-01 c语言 11-8
2021-06-01 c语言 11-7
2021-06-01 c语言中转换字符串函数 atoi函数
2021-06-01 c语言中 strncmp函数, 函数原型和头文件。
2021-06-01 c语言中strcmp函数,函数原型和函数头文件
2021-06-01 c语言中strncat函数,函数原型以头文件
2021-06-01 c语言中strcat函数,函数原型和函数头文件
点击右上角即可分享
微信分享提示