[英]Output GNU Octave (or Matlab) matrix into a file with C array syntax
我有一個八度的大矩陣,我需要將它的數據導入到我的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數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.