How do I use fprintf with MATLAB Coder?
31 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Arfoss Andy
il 7 Set 2020
Commentato: Darshan Ramakant Bhat
il 9 Set 2020
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!
0 Commenti
Risposta accettata
Darshan Ramakant Bhat
il 7 Set 2020
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
4 Commenti
Darshan Ramakant Bhat
il 9 Set 2020
I tried below code and it worked for me without error
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
fprintf(fileID,"%s\n",varname);
fclose(fileID);
codegen -config cfg write2CSV -args {coder.typeof('a',[inf inf]),coder.typeof('a',[inf inf])} -report
For EXE :
cfg = coder.config('exe');
cfg.GenerateExampleMain = "GenerateCodeAndCompile";
Above will generate EXE file with the default example main. We also generate makefile inside the codegen folder. You can modify the generated main and try to rebuild EXE using the makefile.
Più risposte (0)
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!