MATLAB: Error while writing output in a CSV file using fprintf

filefprintf

Hi,
I am consistently getting error while writing output in a CSV file using fprintf. I actually want to write my results in a CSV file. I have tried different lengths of the matrix and I get the same error even with 2 columns. Can anybody please help me understand what's the mistake here and how can I resolve this error?
Sample Code:
colname = {'col1' 'col2' 'col3'};
fid = fopen('test.csv','w');
fprintf(fid, '%s, %s, %s\n', colname{1:});
for p=1:5
% <some code>
fname = %reading image name from a directory
% <some code>
val1 = %calculating value1
val2 = %calculating value2
datacol = {fname val1 val2};
fprintf(fid, '%s, %f, %f\n', datacol{p+1:});
end
fclose(fid);
Error: "??? Index exceeds matrix dimensions. at fprintf(fid, '%s, %f, %f\n', datacol{p+1:});"
P.S. writing "datacol = {fname val1 val2};" as "datacol = {fname,val1,val2};" brought the same error message.

Best Answer

Why not simplify this greatly:
fid = fopen('test.csv','wt');
% fid = 1; % Print to command window.
fprintf(fid, 'col1, col2, col3\n');
for p = 1 : 5
% <some code>

fname = sprintf('File %d', p); %reading image name from a directory
% <some code>
val1 = rand(); %calculating value1
val2 = rand(); %calculating value2
fprintf(fid, '%s, %.4f, %.4f\n', fname, val1, val2);
end
fclose(fid);
No need to mess with cell arrays at all unless you need to store the data after the loop ends. Even if you do, a structure array or a table would be easier and more intuitive than a cell array.