You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言中如何对称化矩阵并将对称位置的0替换为1?

矩阵对称位置零值替换解决方案

原始矩阵

contingency.table.1 <- structure(c(40, 5, 1, 0, 24, 8, 0, 1, 2, 1, 1, 0, 0, 1, 0, 1), .Dim = c(4L, 
4L), .Dimnames = list(col1 = c("0", "1", "2", "3"), col2 = c("0", 
"1", "2", "3")), class = "table")

已完成操作:替换对角线零值

已执行代码将矩阵对角线上的0替换为1:

contingency.table.1[row(contingency.table.1) == 
                      col(contingency.table.1) & contingency.table.1 == 0] <- 1

需求实现:替换对称位置均为0的元素

需要将矩阵中对称位置((i,j)与(j,i))均为0的两个位置同时替换为1,可通过以下代码实现:

# 获取行、列索引矩阵
rows <- row(contingency.table.1)
cols <- col(contingency.table.1)

# 筛选上三角区域中,原位置和对称位置均为0的索引对
sym_zero_indices <- which(rows < cols & contingency.table.1 == 0 & t(contingency.table.1) == 0, arr.ind = TRUE)

# 对筛选出的位置及其对称位置赋值为1
contingency.table.1[sym_zero_indices] <- 1
contingency.table.1[sym_zero_indices[, c("col", "row")]] <- 1

最终结果矩阵

执行后得到期望的矩阵:

contingency.table.1 <- structure(c(40, 5, 1, 1, 24, 8, 0, 1, 2, 1, 1, 0, 1, 1, 0, 1), .Dim = c(4L, 
4L), .Dimnames = list(col1 = c("0", "1", "2", "3"), col2 = c("0", 
"1", "2", "3")), class = "table")

代码说明

  • 使用rows < cols限定只处理上三角区域,避免重复操作同一对对称位置;
  • 通过t(contingency.table.1) == 0判断对称位置是否也为0;
  • 找到符合条件的索引后,同时对原位置和对称位置赋值1,确保对称位置同时被修改。

内容的提问来源于stack exchange,提问作者GOGA GOGA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 13:20:51