Sometimes we need to convert variables defined MATLAB to C variable declarations. For example, S-function would require some parameters that exist in workspace. This post will present some example codes for the realization.

The following codes show the method to convert a 2*2 matrix and a scalar to C variable declarations:

```
function matlab2c_matrix(M,fid,name)
% M: matlab to be converted
% fid: file address by fopen;
% name: C variable name
[n,m] = size(M);
fprintf(fid,'double %s[%d][%d] = { \n',name,n,m);
for i = 1 : n
fprintf(fid,'\t {');
for j = 1 : m-1
fprintf(fid,'%.20e, ',M(i,j));
end
fprintf(fid,'%.20e }, \n', M(i,m));
end
fprintf(fid,'\t }; \n\n');
end
function matlab2c_scalar(M,fid,name)
% M: matlab to be converted
% fid: file address by fopen;
% name: C variable name
fprintf(fid,'double %s = %.20e; \n',name,M);
fprintf(fid,'\t }; \n');
end
```

An example to call the above functions and generate a C head file is given as follows.

```
M=randn(3,3);
S=2.0;
fname = 'Para.h';
fid = fopen(fname,'w');
matlab2c_matrix(M,fid,'Mc');
matlab2c_scalar(S,fid,'Sc');
```

The generated Para.h file is shown as follows.