如何解决生成随机矩阵时有些奇怪的东西本征库
我的意图是在 tmp 中堆叠作为 orth(randn(lenghtDim,dimsSubsp(iK)))'生成的矩阵(用Matlab表示法) 我用此过程模拟nresample次,每次计算 tmp 的平方范数并将其保存在normVal中。我尝试了不同的方式来生成这些随机矩阵,但是它们的范数始终是相同的(对于Matlab,我没有这种行为)!
您能帮助我理解这种奇怪的行为并解决它吗?谢谢
Eigen::VectorXd EmpDistrLargSV(const std::size_t lenghtDim,const std::vector<std::size_t>& dimsSubsp,int nresample ){
Eigen::VectorXd normVal;
Eigen::MatrixXd tmp(std::accumulate(dimsSubsp.cbegin(),dimsSubsp.cend(),0),lenghtDim);
normVal.resize(nresample);
std::normal_distribution<double> distribution(0,1);
std::default_random_engine engine (nresample );
for (int i = 0; i <nresample ; ++i) {
for (int iK = 0; iK < dimsSubsp.size(); ++iK) {
std::size_t row_start=std::accumulate(dimsSubsp.begin(),dimsSubsp.begin()+iK,0);
Eigen::MatrixXd myRandMat = Eigen::MatrixXd::NullaryExpr(lenghtDim,dimsSubsp[iK],[&](){return distribution(engine);});
Eigen::JacobiSVD<Eigen::MatrixXd> svd(myRandMat,Eigen::ComputeThinU );
tmp.block(row_start,lenghtDim)=svd.matrixU().transpose();
}
normVal(i)=tmp.squaredNorm();
}
return normVal;
}
-编辑--
我要用C ++编写的是下面的Matlab代码
nb = length(dimsSubsp);
tmp = zeros(sum(dimsSubsp),lengthDim);
normVal = zeros(1,nresample);
for i = 1:nresample
for ib = 1:nb
irow_start = sum(dimsSubsp(1 : (ib - 1))) + 1;
irow_end = sum(dimsSubsp(1 : ib));
tmp(irow_start : irow_end,:) = orth(randn(lengthDim,dimsSubsp(ib)))';
end
normVal(i) = norm(M,2)^2;
end
要获取orth()
,请在C ++中计算svd,然后取matrixU。
解决方法
编辑:
哈哈,我知道现在是什么。您正在执行SVD,并查看U
,它始终(无论输入如何)都是一个matrix矩阵。 unit矩阵的属性为U^T * U == I
,这表示其每一列的范数(和平方范数)正好为1。因此,矩阵的平方范数将等于列数(对于您的“瘦” U
而言,行或列的最小值),无论您使用哪种随机数生成器。
以下不育元素信息:
尝试使用std::default_random_engine
而不是std::mt19937
。我不确定使用nresample
作为种子是否重要,但是您可能想尝试使用类似std::chrono::high_resolution_clock::now().time_since_epoch().count()
的方法。否则,我认为您的方法类似于我的方法。
#include <chrono>
#include <random>
#include <Eigen/eigen>
MatrixX<double> random_matrix(int rows,int cols,double min,double max,unsigned seed)
{
std::mt19937 generator(seed);
std::uniform_real_distribution<double> distribution(min,max);
MatrixX<double> result(rows,cols);
for(double& val : result.reshaped())
val = distribution(generator);
return result;
}
MatrixX<double> rando = random_matrix(20,34,-30.1,122.3,std::chrono::high_resolution_clock::now().time_since_epoch().count());
,
根据default_random_engine documentation的默认构造函数创建linear congruential engine,该种子从某些种子开始进行简单的递增和取模。
因此,您使用的随机引擎是确定性的。
这就是为什么您获得相同的矩阵和相同的范数的原因。 Matlab可能不确定。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。