我有一个八度的大矩阵,我需要将它的数据导入我的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,
};
最佳答案 对于矢量,请尝试此功能
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数组.