In MATLAB, I’m using fprintf to print a list of numerical values under column headings, like so:
fprintf('%s %s %s %s\n', 'col1', 'col2', 'col3', 'col4')
for i = 1:length(myVar)
fprintf('%8.4g %8.4g %8.4g %8.4g\n', myVar{i,1}, myVar{i,2}, myVar{i,3}, myVar{i,4})
end
This results in something like this:
col1 col2 col3 col4
123.5 234.6 345.7 456.8
However, when one of the cells is empty (e.g. myVar{i,3} == []), space is not preserved:
col1 col2 col3 col4
123.5 234.6 456.8
How do I preserve space in my format for a numerical value that may be empty?
One option is to use the functions CELLFUN and NUM2STR to change each cell to a string first, then print each cell as a string using FPRINTF:
This should give you output like:
Notice also that I added eights to your first FPRINTF call to fix the formatting of the column labels and changed
length(myVar)tosize(myVar,1)since you are looping over the rows ofmyVar.