如何替换矩阵中的非对角元素? [英] How to replace non-diagonal elements in a matrix?

查看:64
本文介绍了如何替换矩阵中的非对角元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更具体地说,我希望对角线元素(X_11、X_22、X_33、...、X_jj)以外的所有元素都为零.

More specifically, I want all elements other than the diagonal ones (X_11, X_22, X_33,...,X_jj) to be zero.

例如我要:

 [1 4 5
  2 3 5
  3 9 8]

成为:

 [1 0 0
  0 3 0
  0 0 8]

这可能吗?抱歉,我完全是个菜鸟..

Is this possible? Sorry I'm a complete noob at this..

推荐答案

这是一个简单的单线.首先,获取数据:

It's a simple one liner. First, get the data in:

> (a <- matrix(scan(),nr=3,byrow=TRUE))
1: 1 4 5 2 3 5 3 9 8
10: 
Read 9 items
     [,1] [,2] [,3]
[1,]    1    4    5
[2,]    2    3    5
[3,]    3    9    8

方法一:

> diag(diag(a))
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    3    0
[3,]    0    0    8

问题是,如果它的参数是一个矩阵,diag 提取对角线...但如果参数是一个向量,它是一个函数,创建一个对角矩阵.所以只需使用它两次.(事实上​​,diag四种不同的用途,这取决于你给它什么,尽管其中两种情况非常相似.)参见 ?diag

The thing is, if its argument is a matrix, diag extracts the diagonal... but if the argument is a vector, it's a function that creates a diagonal matrix. So just use it twice. (In fact diag has four different uses, depending on what you give it, though two of the cases are quite similar.) See ?diag

如果您的矩阵很大,这可能不是最有效的方法,但对于中等大小的情况,我就是这样做的.

If your matrices are huge this isn't likely to be the most efficient way, but for moderate size cases that's the way I do it.

---

方法二:

一种完全不同的单线也有效 -

A completely different one-liner that also works -

ifelse(row(a)==col(a),a,0)

两者在方阵上的工作方式相同.但是它们在非方阵上有不同的结果——第一个返回一个方阵(维度是两个原始维度中较小的一个),而第二个返回一个与其参数形状相同的对象;这取决于具体情况.

The two work the same on square matrices. But they have a different result on non-square matrices - the first one returns a square matrix (of dimension the smaller of the two original dimensions), while the second one returns an object of the same shape as its argument; this can be useful depending on the situation.

这篇关于如何替换矩阵中的非对角元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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