【问题标题】:Output GNU Octave (or Matlab) matrix into a file with C array syntax使用 C 数组语法将 GNU Octave(或 Matlab)矩阵输出到文件中
【发布时间】:2017-04-07 09:52:33
【问题描述】:

我有一个八度音阶的大矩阵,我需要将它的数据导入到我的 C++ 代码中。矩阵全是数字,我想将它保存为头文件中的 C 数组。

示例:

> # octave:
results =

  -3.3408e+01  -5.0227e+00   4.3760e+01   3.2487e+01   1.0167e+01   4.1076e+01   6.3226e+00  -3.7095e+01   1.3318e+01   3.8582e+01
  -2.1087e+01  -6.1606e+00   4.8704e+01   3.1324e+01   3.0287e+01   4.0114e+01   1.5457e+01  -3.6283e+01   2.6035e+01   4.0112e+01

需要的输出:

/* In some foo.h */

static const float results = {   
    3.3408e+01,-5.0227e+00,4.3760e+01,3.2487e+01,1.0167e+01,4.1076e+01,6.3226e+00,-3.7095e+01,1.3318e+01,3.8582e+01,
    2.1087e+01,-6.1606e+00,4.8704e+01,3.1324e+01,3.0287e+01,4.0114e+01,1.5457e+01,-3.6283e+01,2.6035e+01,4.0112e+01,
};

【问题讨论】:

  • 您可能需要使用 Octave 的 sprintf 手动执行此操作,然后添加声明和花括号。例如,参见sprintf('%e,', results) 的输出
  • 正如@LuisMendo 所写,您可以使用strcat("static const float result = {", sprintf('%e,', result), "}\n"),它为您提供static const float result = {-3.340800e+01,-2.108700e+01,-5.022700e+00,-6.160600e+00,4.376000e+01,4.870400e+01,},但您可能对strcat("static const float result[2][3] = {{", sprintf('%e,', result(1,:)), "}{", sprintf('%e,', result(2,:)),"}}\n") 更感兴趣,它为您提供static const float result[2][3] = {{-3.340800e+01,-5.022700e+00,4.376000e+01,}{-2.108700e+01,-6.160600e+00,4.870400e+01,}}
  • @mucka 这看起来像是对我的回答

标签: c++ c matlab matrix octave


【解决方案1】:

对于向量,试试这个函数

function str = convertarraytoc(B, type, precision, varName)

if nargin < 2
    type = 'float';
end
if nargin < 3
    precision = 35;
end
if nargin < 4
    varName = 'B';
end

str = sprintf('%s %s[%d] = {', type, varName, length(B));
for iB=1:length(B)
    if strcmpi(type, 'float')
        str = [ str sprintf( ['%1.' int2str(precision) 'ff'], B(iB)) ];
    else
        str = [ str sprintf('%d', B(iB)) ];
    end
    if iB ~= length(B)
        str = [ str sprintf(',') ];
    end
    if mod(iB, 501) == 0, str = [ str sprintf('\n') ]; end
end
str = [ str sprintf('};\n') ];
fprintf('%s', str);

例如

convertarraytoc(rand(1,5), 'float', 8, 'test')

ans =

    'float test[5] ={0.84627244f,0.63743734f,0.19773495f,0.85582346f,0.24452902f};'

该函数需要适应处理 Matlab 数组。

【讨论】:

    猜你喜欢
    • 2013-03-11
    • 2019-11-18
    • 2014-08-06
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    相关资源
    最近更新 更多