MATLAB矩阵保存后由C++读取文件

楼主在调试自己的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();

数据内容分为实部与虚部一起保存。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值