MATLAB: How to use fprintf with MATLAB Coder

c codefprintfmatlab coder

I'm trying to use fprintf with MATLAB Coder but struggling to understand the limitation of "The formatSpec parameter must be constant."
I'm simply trying to save an array as an CSV or text file, and using the following code/function:
function write2CSV(varname, fname)
% Writes a particular variable to CSV file.
if nargin<2, fname = 'test.csv';end
fileID = fopen(fname,'w');
%fprintf(fileID,'%7.4f\n',varname);
fprintf(fileID,"%c\n",varname);
fclose(fileID);
You can call this function inside a script with any simple array as input such as:
write2CSV([1;2;3;4;5]);
It works fine in basic MATLAB. But when I try to generate C-code using MATLAB Coder, the specific error I'm getting is … "argument corresponding to conversion character 'c' in the formatspec parameter is not scalar. It has to be fixed size scalar". HOW DO I SPECIFY A FIXED-SIZE SCALAR IN THE FORMAT SPEC?
I have tried various combinations for the format spec, but don't understand how to make it a 'constant'.
Any ideas? thanks a bunch!

Best Answer

How are you generating code ? Are you using Coder App or Command Line ?
As the error says, you cannot pass an array as input when the format specifier is "%c". I modified the code like below and it worked for me :
function write2CSV(varname, fname)
% Writes a particular variable to CSV file.
if nargin<2, fname = 'test.csv';end
fileID = fopen(fname,'w');
%fprintf(fileID,'%7.4f\n',varname);
n = length(varname);
for i = 1:n
fprintf(fileID,"%c\n",varname(i));
end
fclose(fileID);
Code generation using command line :
codegen write2CSV -args {'hello','myFile.txt'} -report -config:lib
Hope this will be helpful