How do I use fprintf with MATLAB Coder?
20 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Darshan Ramakant Bhat
2020-9-7
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 个评论
Darshan Ramakant Bhat
2020-9-9
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.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!