from
Generate Arrays
by Marco Zuliani
Converts a Matlab array to C and LaTeX
|
| generate_C_array(a, name, Nepl)
|
function str = generate_C_array(a, name, Nepl)
% str = generate_C_array(a, name, Nepl)
%
% DESC:
% generates a numeric C array in column major format. Use fprintf(str) to
% generate a matlab output that can be copied in your C source. The number
% of figures composing the number representation is estimated
% automatically.
%
% AUTHOR
% Marco Zuliani - zuliani@ece.ucsb.edu
%
% VERSION:
% 1.0.0
%
% INPUT:
% a = array
% name = array name (default = 'a')
% Nepl = number of elements per line (default = size(a,2))
%
% OUTPUT:
% str = C instructions: use fprintf(str)
% HISTORY:
% 1.0.0 - May 24, 2008 - initial version
% input parameters
if (nargin < 2)
name = inputname(1);
end;
if (nargin < 3)
Nepl = size(a, 2);
end;
format = ['%' num2str(get_integer_figures(a)) '.' num2str(get_decimal_figures(a))];
% detect array type
s = '';
type = '';
switch class(a)
case 'uint8'
type = 'unsigned char';
s = '';
format = [format 'd'];
case 'int8'
type = 'char';
s = '';
format = [format 'd'];
case 'single'
type = 'float';
s = 'f';
format = [format 'f'];
case 'double'
type = 'double';
s = 'd';
format = [format 'f'];
otherwise
error('Unknown type')
end;
% generate the string
l = numel(a);
CR = '\n';
str = [CR sprintf('%s %s[%d] = {', type, name, l) '\\' CR];
for h = 1:l-1
str = [str, sprintf([format '%s, '], a(h), s)];
if (mod(h, Nepl) == 0)
str = [str, '\\' CR];
end;
end;
str = [str, sprintf([format '%s};'], a(l), s) CR];
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Estimate the number of figures composing the number
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function n_max = get_integer_figures(a)
n_max = 0;
for h = 1:numel(a)
n = ceil(log10(abs(a(h))));
if(n > n_max)
n_max = n;
end;
end;
return;
function n_max = get_decimal_figures(a)
n_max = 0;
for h = 1:numel(a)
n = 1;
while true
if(round(a(h)) == a(h))
break;
else
a(h) = a(h) * 10;
n = n + 1;
end;
end;
if(n > n_max)
n_max = n;
end;
end;
return;
|
|
Contact us at files@mathworks.com