简体   繁体   English

将GNU Octave(或Matlab)矩阵输出到具有C数组语法的文件中

[英]Output GNU Octave (or Matlab) matrix into a file with C array syntax

I have a big matrix in octave which I need it's data to be imported into my C++ code. 我有一个八度的大矩阵,我需要将它的数据导入到我的C ++代码中。 The matrix is all numbers and I would like to save it as a C array in a header file. 矩阵是所有数字,我想将它保存为头文件中的C数组。

example : 例如:

> # 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

Needed output: 需要的输出:

/* 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,
};

For vectors, try this function 对于矢量,请尝试此功能

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);

For example 例如

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

ans =

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

The function would need to be adapted to process Matlab arrays. 该函数需要适应处理Matlab数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM