在R中创建矩阵的有效方法 [英] Efficient way to create matrix in R

查看:141
本文介绍了在R中创建矩阵的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从向量创建这样的矩阵:

I am trying to create a matrix like this from a vector:

    vec= c(2, 5, 9)
    > A
            [,1] [,2] [,3] [,4]
    [1,]     2    0    0    0
    [2,]     5    3    0    0
    [3,]     9    7    4    0

实际上,第一列始终是矢量元素,第二列从0开始,然后是(5-2 = 3),然后第二列的thirld元素是(9-2 = 7).然后,第三列从0开始,然后从0开始,然后(9-5 = 4),最后一列始终为零. vec的长度可能更改为任意数字,例如4,5,....如何编写有效的函数或代码来创建此矩阵?

Actually always the first column is the vector element, the second column start with 0 and then the (5-2 = 3) and then the thirld element of second column is (9-2 = 7). Then the third column start with 0 and then 0 and (9-5 = 4) and the last column is always zero. May be the length of vec changes to any number for example 4, 5,... .How can I write an efficient function or code to create this matrix?

推荐答案

我认为这将满足您的要求:

I think this will do what you want:

f = function(vec)
{
   n = length(vec)  
   M = matrix(0,n,n+1)
   M[,1] = vec
   for(i in 1:n) M[,i+1] = c(rep(0,i),vec[-c(1:i)]-vec[i])
   return(M)
}

vec = c(2,5,9)
f(vec)
     [,1] [,2] [,3] [,4]
[1,]    2    0    0    0
[2,]    5    3    0    0
[3,]    9    7    4    0

这篇关于在R中创建矩阵的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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