根据数值调整 fprintf 中的字符串格式

Adjusting string format in fprintf depending on numeric values

我想将数值数组导出为 .csv 文件。因此,简化的术语如下所示:

fid = fopen('output.csv','wt')
toprint = [1.0, 1.1, 1.2, 1.3];
fprintf(fid, '%f, %f, %f, %f\n', toprint);
fclose(fid)

在这种情况下是没有问题的。我使用字符串格式的 %f 来保持精度。然而,有时,或者更确切地说 通常 ,数组中有这样的零:

toprint = [1.0, 0, 0, 1.1];

在这种情况下,我想将字符串格式调整为:

'%f, %d, %d, %f\n' % where "%f" were replaced by "%d" at the positions of the zeros

减少输出文件大小,因为我不需要零数字的精度。我最初应用的解决方案是通过数组检测数据类型。如果检测到零,则将“%d”连接成字符串格式。但是好像效率很低

我正在寻找一种根据输入数据调整字符串格式的有效方法。有什么办法可以实现吗?

两种方法:

  1. 您可以尽可能使用“%g”来简化浮点输出。这也会缩短其他整数,例如 1.02.0,这可能是也可能不是您想要的
  2. 根据值动态构建格式字符串
>> fprintf('%g %g %g %g\n', [1.0, 1.1, 1.2, 1.3])
1 1.1 1.2 1.3
>> fprintf('%g %g %g %g\n', [1.0, 1.1, 0, 1.3])
1 1.1 0 1.3
>> fprintf('%g %g %g %g\n', [1.0, 1, 0, 1.3])
1 1 0 1.3

方法二:

>> a = [1.1 1.2 0 1.3]

a =

    1.1000    1.2000         0    1.3000

>> tokens = {'%f', '%d'}

tokens = 

    '%f'    '%d'

>> strformat = strcat(strjoin(tokens((a==0)+1), ', '), '\n')

strformat =

%f, %f, %d, %f\n

>> fprintf(strformat, a)
1.100000, 1.200000, 0, 1.300000