Matlab如何保存复数数组到csv文件和Qt里怎么读取

1、Matlab如何保存复数数组到csv文件

% 分离实部和虚部
real_part = real(xHat_WithIQImb);  % 提取实部  xHat_WithIQImb是需要进行操作的复数数组
imag_part = imag(xHat_WithIQImb);  % 提取虚部

% 按列拼接(前一半是实部,后一半是虚部)
combined_data = [real_part, imag_part];

csvwrite("D:\temp.csv",combined_data);

2、Qt里怎么读取

bool readMatlabComplexCsv(const QString& filePath,
                          std::vector<std::vector<_complex>>& complex2DArray,
                          int& rows, int& cols) {
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件:" << filePath;
        return false;
    }

    QTextStream in(&file);
    complex2DArray.clear();  // 清空输出数组
    rows = 0;
    cols = 0;

    while (!in.atEnd()) {
        QString line = in.readLine().trimmed();
        if (line.isEmpty()) continue;

        QStringList parts = line.split(',', Qt::SkipEmptyParts);
        for (QString& part : parts) {
            part = part.trimmed();
        }

        // 检查列数是否为偶数(实部和虚部数量必须相等)
        if (parts.size() % 2 != 0) {
            qDebug() << "第" << rows+1 << "行格式错误:实部和虚部数量不匹配";
            return false;
        }

        // 确定当前行的复数列数(总列数的一半)
        int currentCols = parts.size() / 2;
        if (rows == 0) {
            cols = currentCols;  // 第一行确定列数
            if (cols == 0) {
                qDebug() << "文件内容为空";
                return false;
            }
        } else if (currentCols != cols) {
            qDebug() << "第" << rows+1 << "行列数与第一行不一致";
            return false;
        }

        // 解析当前行的复数,存储为一维向量(代表一行数据)
        std::vector<_complex> rowData;
        for (int i = 0; i < cols; ++i) {
            bool realOk, imagOk;
            double realVal = parts[i].toDouble(&realOk);           // 前半部分为实部
            double imagVal = parts[cols + i].toDouble(&imagOk);    // 后半部分为虚部

            if (!realOk || !imagOk) {
                qDebug() << "第" << rows+1 << "行第" << i+1 << "个复数解析失败";
                return false;
            }

            rowData.emplace_back(_complex{realVal, imagVal});  // 添加到当前行
        }

        complex2DArray.push_back(rowData);  // 将当前行添加到二维数组
        rows++;
    }

    file.close();
    return true;
}


/*  这是我使用的复数类型
        struct _complex
        {
            double x, y; // real and imaginary parts
        };

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值