从较小的矩阵创建一个较大的矩阵
我有一个矩阵 A,它是:
A <- matrix(c(1:15), byrow=T, nrow=5)
A
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
[4,] 10 11 12
[5,] 13 14 15
现在我想创建一个矩阵 B,它的尺寸为 8x8(或 10x10,或 15x15 等),看起来像这样:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 2 3 0 0 0 0 0
[2,] 4 5 6 0 0 0 0 0
[3,] 7 8 9 0 0 0 0 0
[4,] 10 11 12 0 0 0 0 0
[5,] 13 14 15 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0
所以从 A 开始,我想添加列和行,到 8x8 尺寸,全部替换为零值...... 有什么想法吗? 先感谢您!!
I have a matrix A which is:
A <- matrix(c(1:15), byrow=T, nrow=5)
A
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
[4,] 10 11 12
[5,] 13 14 15
Now I want to create a matrix B, which is 8x8 dimensions (or 10x10, or 15x15, etc), which would look like this:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 2 3 0 0 0 0 0
[2,] 4 5 6 0 0 0 0 0
[3,] 7 8 9 0 0 0 0 0
[4,] 10 11 12 0 0 0 0 0
[5,] 13 14 15 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0
So starting from A, I want to add columns and rows, to an 8x8 dimensions, all replaced with zero values...
Any idea?
Thank you in advance!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
另一种方法是首先创建较大的矩阵,然后插入较小的矩阵,如以下函数所示:
不确定哪个更好(更快、更干净等)。如果您尝试扩展到小于原始大小,则会出现错误。
Another way is to first create the bigger matrix, and then slot the small one in, as in this function:
Not sure which is better (faster, cleaner etc). Mine errors if you try and expand to a size that's smaller than the original.
尝试假设
A
至少有一行和一列:或者作为单个语句:
如果
A
可以有零行或零列,则使用seq_len(nrow (A))
和seq_len(ncol(A))
代替1:nrow(A)
和1:ncol(A)< /代码>。
或者,即使在 A 具有零行或零列的情况下,这也有效:
或
或
Try this assuming
A
has at least one row and one column:or as a single statement:
If
A
can have zero rows or zero columns then useseq_len(nrow(A))
andseq_len(ncol(A))
in place of1:nrow(A)
and1:ncol(A)
.Alternately, this works even in the case that A has zero rows or columns:
or
or
怎么样:
然后
或者
如果您最想要方阵作为输出,也可以给它一个默认值:
然后
expandMatrix(A, 8)
就足够了。How about:
Then
or
Could also give it a default if you mostly want square matrix as outputs:
Then
expandMatrix(A, 8)
would suffice.