Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. The matrix is all numbers and I would like to save it as a C array in a header file.

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,
};
like image 840
sorush-r Avatar asked Oct 17 '22 14:10

sorush-r


1 Answers

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.

like image 50
user1097111 Avatar answered Oct 21 '22 08:10

user1097111