本文介绍了在R中重复一个简单的矩阵算法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我试图通过创建第一部分来避免重复一些简单的计算。但是我想知道为什么我不能获得与第二部分计算结果相同的结果(第二部分给出了正确答案)? 第一部分: a =矩阵(c(8,11,2,6,8) (a) mc = colMeans(a) nc = ncol(a) mc = mr = rowMeans(a) gr = mean(a) (m =矩阵(c(a [rep(1:nr,nr) nc,each = nc)] - mr [rep(1:nr,nr)] - mc [rep(1:nc,each = nc)] + gr),nrow = nr,ncol = nc)) ##这是不正确的答案! 第二部分: a11 a21 a31 a12 a22 a32 a13 a23 a33 a14< - a [1,4] - mr [1] - mc [4] + gr a24 a34 < - a [3,4] - mr [3] - mc [4] + gr g = paste0(a,rep(1:3,3) ,每个= 3))(m =矩阵(c(mget(g)),nr = 3,ncol = 4))##这是正确的答案! 解决方案您可以使用 / code>来计算差异: $ $ $ $ $ $ $ myMat myMat [,1] [,2] [,3] [,4] [1,] 2 1 0 -3 [ 2,] 2 0 -2 0 [3,] -4 -1 2 3 重建m,使它不是一个列表 $ b $ pre $ m $ m = matrix(unlist(mget(g)),nr = 3, ncol = 4) 现在,检查它们是否一致: 相同(m,myMat) [1] TRUE I'm trying to avoid repeating some simple calculations by creating the first part. But I'm wondering why I don't obtain the same result as calculated by the second part (second part gives the correct answer)?First part: a = matrix(c(8,11,2, 6,8,4, 4,5,6, 2,8,8), nrow = 3) nr = nrow(a)nc = ncol(a)mc = colMeans(a)mr = rowMeans(a)gr = mean(a)(m = matrix(c(a[rep(1:nr, nr), rep(1:nc, each = nc)] - mr[rep(1:nr, nr)] - mc[rep(1:nc, each = nc)] + gr), nrow = nr, ncol = nc)) ## This is NOT correct answer !!Second part:a11 <- a[1, 1] - mr[1] - mc[1] + gra21 <- a[2, 1] - mr[2] - mc[1] + gra31 <- a[3, 1] - mr[3] - mc[1] + gra12 <- a[1, 2] - mr[1] - mc[2] + gra22 <- a[2, 2] - mr[2] - mc[2] + gra32 <- a[3, 2] - mr[3] - mc[2] + gra13 <- a[1, 3] - mr[1] - mc[3] + gra23 <- a[2, 3] - mr[2] - mc[3] + gra33 <- a[3, 3] - mr[3] - mc[3] + gra14 <- a[1, 4] - mr[1] - mc[4] + gra24 <- a[2, 4] - mr[2] - mc[4] + gra34 <- a[3, 4] - mr[3] - mc[4] + grg = paste0("a", rep(1:3, 3), rep(1:4, each = 3))(m = matrix(c(mget(g)), nr = 3, ncol = 4)) ## This is the correct answer !! 解决方案 You can use outer to calculate the differences:myMat <- a - outer(mr, mc, "+") + grmyMat [,1] [,2] [,3] [,4][1,] 2 1 0 -3[2,] 2 0 -2 0[3,] -4 -1 2 3rebuild m so that it is not a listm = matrix(unlist(mget(g)), nr = 3, ncol = 4)Now, check that they are identical: identical(m, myMat)[1] TRUE 这篇关于在R中重复一个简单的矩阵算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-15 04:35