【问题标题】:How to display formatted numbers from a cell array with n decimal places如何显示具有 n 位小数的元胞数组中的格式化数字
【发布时间】:2013-12-04 08:42:08
【问题描述】:

我有一个包含数字和字符串的元胞数组。我想打印单元格数组,以便在小数点后只看到 5 个数字。例如:

c{1, 1} = pi;
c{2, 1} = pi / 2;
c{3, 1} = pi / 4;
c{4, 1} = 2 ^ 0.5;

使用format long 后,我收到了:

>> c
c = 
    [3.141592653589793]
    [1.570796326794897]
    [0.785398163397448]
    [1.414213562373095]

但我希望输出是:

>> c
c = 
    [3.14159]
    [1.57079]
    [0.78539]
    [1.41421]

【问题讨论】:

  • format short 显示小数点后 4 位。太少了?
  • 对于“打印”使用fprintfsprintf - 对于“显示”它有点复杂。虽然我想你可以用你的代码覆盖disp(我想包含 fprintf)
  • @chappjc 元胞数组中也有字符串..

标签: matlab format cell-array


【解决方案1】:

一种可能的解决方案是生成一个格式化字符串,例如

sprintf('%.5f\n', c{:})

对于您的示例,结果将是:

ans =
    3.14159
    1.57080
    0.78540
    1.41421

format 不同,生成您自己的字符串允许您将小数点后显示的位数调整为您想要的任何值。

如果您的元胞数组包含非数字值(例如字符串),您可以执行以下 hack:

c_fmt = c;                                              %// Temporary cell array
idx = cellfun(@isnumeric, c(:));                        %// Locate numbers
c_fmt(idx) = cellfun(@(x){sprintf('%.5f', x)}, c(idx)); %// Format as strings

本质上将数字转换为格式化的字符串。显示结果 c_fmt 应该会给你一个可接受的输出。

【讨论】:

    【解决方案2】:

    转到文件 -> 首选项从左侧列表中选择“命令窗口”。
    将“文本显示”从'long' 更改为'short'

    c = 
    [3.1416]
    [1.5708]
    [0.7854]
    [1.4142]
    

    【讨论】:

    • 他要的是五位数,而不是四位数。
    • 实现这一点的快速方法当然是输入format short
    【解决方案3】:

    使用compose:

    disp(cell2mat(compose('%1.4f',cell2mat(c))))
    

    这将为您每行提供一个字符。将其转换为数组:

    str2num(cell2mat(compose('%1.4f',cell2mat(c))))
    

    【讨论】:

      猜你喜欢
      • 2013-10-27
      • 1970-01-01
      • 1970-01-01
      • 2013-06-29
      • 2011-01-01
      • 2011-09-02
      • 1970-01-01
      相关资源
      最近更新 更多