gpt4 book ai didi

c++ - 在 C++ 中创建一个执行 Matlab 操作 [z;z] 的函数,其中 z 是矩阵或 vector

转载 作者:太空狗 更新时间:2023-10-29 21:35:37 29 4
gpt4 key购买 nike

我正在尝试创建一个基本上复制 matlab 命令的函数:[z;-z] 其中 z = randn(m,n) 返回一个 m -by-n 随机条目矩阵。我能够在 C++ 中为下面的 randn 函数创建一个函数:

MatrixXd generateGaussianNoise(int n, int m){
MatrixXd M(n,m);
normal_distribution<double> nd(0.0, 1.0);
random_device rd;
mt19937 gen(rd());
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
M(i,j) = nd(gen);
}
}
return M;

现在我需要创建 [z;-z] 函数。例如,假设 z = randn(2,2) 那么输出将是:

   -2.2588    0.3188
0.8622 -1.3077

现在,当我编写 [z;-z] 时,我们得到:

   -2.2588    0.3188
0.8622 -1.3077
2.2588 -0.3188
-0.8622 1.3077

我在想的是创建一个函数,它接受矩阵或 vector z 将这些条目存储在另一个矩阵或 vector 中,然后创建一个新的矩阵或 vector ,其大小加倍以放置在正确的 (i,j) 位置关联条目。

我不确定我是否应该继续这样做。非常感谢任何意见或建议。附带说明一下,我在 C++ 方面还是有点新手。

最佳答案

您应该首先使用矩阵中的 rowscols 将输出矩阵初始化为正确的大小。然后您可以使用 comma initializer syntax通过垂直连接一个矩阵和同一矩阵的负值来填充这个矩阵

MatrixXd A(n, m);

normal_distribution<double> nd(0.0, 1.0);
random_device rd;
mt19937 gen(rd());

// Fill up the matrix
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
A(i, j) = nd(gen);
}
}

// Vertically concatenate the matrix with the negative version
MatrixXd B(A.rows() * 2, A.cols());
B << A, -A;

return B;

关于c++ - 在 C++ 中创建一个执行 Matlab 操作 [z;z] 的函数,其中 z 是矩阵或 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41838378/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com