How to get fprintf to save space for an empty numerical value?

In MATLAB, I use fprintfto print a list of numerical values ​​under column headings, for example:

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

The result is approximately the following:

    col1     col2     col3     col4
   123.5    234.6    345.7    456.8

However, when one of the cells is empty (for example, myVar{i,3} == []), the space is not saved:

    col1     col2     col3     col4
   123.5    234.6     456.8

How to save space in my format for a numeric value that may be empty?

+5
source share
1 answer

One option is to use the CELLFUN and NUM2STR functions to first change each cell to a row, then print each cell as a row using FPRINTF :

fprintf('%8s %8s %8s %8s\n', 'col1', 'col2', 'col3', 'col4');
for i = 1:size(myVar,1)
  temp = cellfun(@(x) num2str(x,'%8.4g'),myVar(i,:),'UniformOutput',false);
  fprintf('%8s %8s %8s %8s\n',temp{:});
end

, :

    col1     col2     col3     col4
   123.5    234.6             456.8

, FPRINTF, length(myVar) size(myVar,1), myVar.

+3

All Articles