[英]How do I create a covariance matrix in R from MATLAB code?
I need some help with porting MATLAB code to R. 在将MATLAB代码移植到R方面,我需要一些帮助。
Below is MATLAB code for creating the covariance matrix, where Z
is a matrix of 17 columns and 27 rows. 以下是用于创建协方差矩阵的MATLAB代码,其中
Z
是17列27行的矩阵。 ehat
is a vector of 27 rows and 1 column. ehat
是27行1列的向量。
omegahat=zeros(cols(Z),cols(Z));
for i=1:N
omegahat=omegahat+ehat(i)^2*Z(i,:)'*Z(i,:);
end
How do I replicate a for
loop in R that works similarly to this MATLAB code? 我如何在R中复制与该MATLAB代码类似的
for
循环?
Try this code. 试试这个代码。 This essentially mirrors what the MATLAB code is doing, but I do question its efficiency.
这从本质上反映了MATLAB代码的作用,但我确实质疑其效率。 Also
cols
is not a function that is defined in MATLAB except for SQL tables. 此外,
cols
不是在MATLAB中定义的函数(SQL表除外)。 I'm assuming you want to determine the total number of columns? 我假设您要确定列总数? Use
size(Z,2)
for that instead. 改用
size(Z,2)
。
In any case, for R, t
denotes transpose, and to perform matrix multiplication, you must encapsulate the *
operator in %
signs. 无论如何,对于R,
t
表示转置,并且要执行矩阵乘法,必须将*
运算符封装在%
符号中。 As such: 因此:
omegahat <- matrix(0,ncol(Z),ncol(Z));
for (i in 1:N) { # N is 27 I suppose?
omegahat <- omegahat + (ehat[i]^2 * Z[i,] %*% t(Z[i,]))
}
Here's a small test on a smaller matrix. 这是在较小矩阵上的小测试。 Supposing
Z
is: 假设
Z
为:
Z =
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Also, let ehat
be: 另外,让
ehat
为:
ehat =
1 2 3 4
I'm also going to assume N = 4
. 我还要假设
N = 4
。
In MATLAB, this is the code to generate our output: 在MATLAB中,这是生成我们的输出的代码:
Z = vec2mat(1:16, 4);
ehat = 1:4;
N = 4;
omegahat = zeros(size(Z,2), size(Z,2)); %# Note the change
for i = 1 : N
omegahat = omegahat + ehat(i)^2*Z(i,:)'*Z(i,:);
end
We thus get: 因此,我们得到:
omegahat =
3534 3844 4154 4464
3844 4184 4524 4864
4154 4524 4894 5264
4464 4864 5264 5664
In R, this is the code to generate our output: 在R中,这是生成我们的输出的代码:
Z <- t(matrix(1:16,4,4))
ehat <- c(1,2,3,4)
N <- 4
omegahat <- matrix(0,ncol(Z),ncol(Z))
for (i in 1:N) {
omegahat <- omegahat + (ehat[i]^2 * Z[i,] %*% t(Z[i,]))
}
We thus get: 因此,我们得到:
> omegahat
[,1] [,2] [,3] [,4]
[1,] 3534 3844 4154 4464
[2,] 3844 4184 4524 4864
[3,] 4154 4524 4894 5264
[4,] 4464 4864 5264 5664
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.