楼主在调试自己的C++代码时候偶尔需要与MATLAB的生成流程对数,故在此做一个保存与读取文件的代码块记录。
MATLAB变量保存
fid = fopen('m_test', 'w');//这里报错可能是地址问题,试一试绝对地址
lte_fft_a = real(lte_fft);
lte_fft_b = imag(lte_fft);
for j = 1:size(lte_fft,2)
for i = 1:size(lte_fft,1)
//矩阵按列保存,矩阵元素拆分为实部与虚部
fprintf(fid, '%.6f\n%.6f\n', lte_fft_a(i,j), lte_fft_b(i,j));
end
end
/*
举例说明:lte_fft是一个2x2矩阵
lte_fft = {{-1+i,-2-i};{1+i,3-i}};
存储完毕后,m_test文件中应该是2x2x2=8个数据
-1
1
-2
-1
1
1
3
-1
*/
C++文本数据读取
std::ifstream infile;
infile.open("m_test");
vector<complex<fp64>> input_test;
string real;
string imag;
while(!infile.eof())
{
infile >> real;
infile >> imag;
input_test.emplace_back(complex<fp64>({atof(real.c_str()), atof(imag.c_str())}));
}
input_test.pop_back();//最后一个数字在循环中读了两次,弹出最后一个数字
input_test.close();
c++读取时一次读取两行,以string类型读取,读取后再转换类型,最后得到复数容器input_test。
c++文本数据保存
std::ofstream outfile;
outfile.open("../test_data/m_espdata_c");
outfile.setf(std::ios::fixed, std::ios::floatfield); // 设定为 fixed 模式,以小数点表示浮点数
outfile.precision(6); // 设置精度 6
if(outfile.is_open())
{
for(int32 column_pnt = 0; column_pnt < static_cast<int32>(espdata.size()); ++column_pnt)
{
for(int32 row_pnt = 0; row_pnt < static_cast<int32>(espdata.at(column_pnt).size()); ++row_pnt)
{
outfile << espdata.at(column_pnt).at(row_pnt).real() <<endl;
outfile << espdata.at(column_pnt).at(row_pnt).imag() <<endl;
}
}
}
outfile.close();
数据内容分为实部与虚部一起保存。