替换 R 中矩阵中的非对角元素(希望这次能问得更好) [英] Replacing non-diagonal elements in a matrix in R (hopefully a better asked this time)

查看:36
本文介绍了替换 R 中矩阵中的非对角元素(希望这次能问得更好)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我之前问过这个问题,但我因为没有指定任何内容并且没有显示出以前尝试的迹象而受到抨击(当之无愧).所以让我再试一次..

Okay, I asked this question earlier but I got bashed (deservedly) for not specifying anything and showing no sign of previous attempt. So let me try again..

我正在使用 R,并且我有一个 463✕463 矩阵.我想做的是替换对角线以外的所有元素(X11、X22、X33、...,Xjj) 为零.

I'm using R, and I have a 463✕463 matrix. What I would like to do is to replace all elements other than the diagonal ones (X11, X22, X33,...,Xjj) with zero.

例如我要:

[1 4 5
 2 3 5
 3 9 8]

成为:

[1 0 0
 0 3 0
 0 0 8]

当我使用 diag() 函数时,它只是给我一个对角线值的列向量.我想我可以使用 replace() 函数以某种方式结合如果不是对角线"逻辑......但我迷路了.

When I use the diag() function, it simply gives me a column vector of the diagonal values. I imagine I can use the replace() function somehow combined with a "if not diagonal" logic...but I am lost.

是的,正如这里的一些人所猜想的那样,我可能比这里的许多人年轻得多,而且我对此完全陌生……所以请让我朝着正确的方向前进.非常感谢您的帮助!

And yes, as some here have guessed, I am probably much younger than many people here and am completely new at this...so please put me in the right direction. Really appreciate all your help!

推荐答案

在 R 中,diag 方法有两个功能.

In R, the diag method has two functions.

  1. 返回矩阵的对角线.即

m <- matrix(1:9, ncol=3)
m
#      [,1] [,2] [,3]
# [1,]    1    4    7
# [2,]    2    5    8
# [3,]    3    6    9
diag(m)
# [1] 1 5 9

  • 它可以构造一个对角矩阵.

    diag(1:3)
    #      [,1] [,2] [,3]
    # [1,]    1    0    0
    # [2,]    0    2    0
    # [3,]    0    0    3
    

  • 因此,在您的情况下,从现有矩阵中提取对角线并将其提供给 diag:

    So in your case, extract the diagonal from your existing matrix and supply it to diag:

    diag(diag(m))
    #      [,1] [,2] [,3]
    # [1,]    1    0    0
    # [2,]    0    5    0
    # [3,]    0    0    9
    

    这篇关于替换 R 中矩阵中的非对角元素(希望这次能问得更好)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆