简体   繁体   English

如何在R中生成矩阵

[英]how to generate a matrix in R

I tried two different approaches to compute the elements of a matrix. 我尝试了两种不同的方法来计算矩阵的元素。 I think both approaches are correct, but they generate different results. 我认为这两种方法都是正确的,但是它们会产生不同的结果。 I am very curious and have no idea which one is correct. 我很好奇,不知道哪一个是正确的。

For example, D is a (t/2+1) by (t/2+1) matrix, its elements read as 例如,D是一个(t / 2 + 1)x(t / 2 + 1)矩阵,其元素读为

  D(k,m) = (2/t)*cos(((m-1)(k-1)*pi)/(t/2))

k=m=1,...,(t/2+1). K = M = 1,...,(T / 2 + 1)。

My first code is: 我的第一个代码是:

   m<-seq(1,(t/2)+1,length=(t/2)+1);
   k<-m;

   D<-matrix(NA,nrow = length(k),ncol = length(k)); 

   for(i in 1:length(k)) # row
     for(j in 1:length(m)) # column
    {
     D[i,j]<-(2/t)*cos(((j-1)*(i-1)*pi)/(t*0.5))
    }

My second is: 我的第二个是:

D<-(2/(t))*cos(as.matrix(seq(0,t/2,by=1))%*%
   t(as.matrix(seq(0,t/2,by=1)))*pi)/(0.5*t)

pi=3.1415926 PI = 3.1415926

Should these two approaches produce the same results?Thanks for your advice! 这两种方法应该产生相同的结果吗?谢谢您的建议!

Change your second to this should solve the problem: 将此更改为第二应该可以解决问题:

D<-(2/(t))*cos(as.matrix(seq(0,t/2,by=1))%*%
             t(as.matrix(seq(0,t/2,by=1)))*pi/(0.5*t))

Note that you need /(0.5*t) inside cos() . 请注意,您需要在cos()内部/(0.5*t) cos()

Gook Luck! 祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM