简体   繁体   中英

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(k,m) = (2/t)*cos(((m-1)(k-1)*pi)/(t/2))

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

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() .

Gook Luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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