【问题标题】:Can table variable names start with a number character?表变量名称可以以数字字符开头吗?
【发布时间】:2018-02-23 16:46:30
【问题描述】:

我正在运行这样的东西:

table = readtable(path,'ReadVariableNames',true);

在 .csv 文件中,第一行的所有单元格都包含字符串标识符,例如 '99BM'、'105CL' 等。所有内容都以数字开头。上面的命令给出了一个带有变量名称的表,如'x99BM'、'x105CL' 等。

是否有可能摆脱这个'x'?我需要将这些标识符与另一个表中没有此 'x' 的列进行比较。

【问题讨论】:

  • 注意:不要使用table作为变量名,因为它会影响现有函数。

标签: matlab variables matlab-table


【解决方案1】:

不,表变量名称不能以数字开头,因为它们遵循与normal variables 相同的命名约定。 'x' 由readtable 自动添加以创建有效名称。你在调用readtable时应该已经注意到了这个警告:

Warning: Variable names were modified to make them valid MATLAB identifiers.
The original names are saved in the VariableDescriptions property.

因此,您无法摆脱表中的'x' within。但是,如果您需要进行任何比较,您可以与保存在 VariableDescriptions property 中的原始值进行比较,其格式如下:

>> T.Properties.VariableDescriptions

ans =

  1×2 cell array

    'Original column heading: '99BM''    'Original column heading: '105CL''

您可以使用regular expression 解析这些,例如:

originalNames = regexp(T.Properties.VariableDescriptions, '''(.+)''', 'tokens', 'once');
originalNames = vertcat(originalNames{:});

originalNames =

  2×1 cell array

    '99BM'
    '105CL'

然后在你需要做的任何字符串比较中使用这些。

【讨论】:

    【解决方案2】:

    没有。正如 gnovice 所提到的, readtable 函数会自动重命名无效名称。它通过调用matlab.lang.makevalidname 并将输出设置为列名来实现这一点。

    如果我理解正确,您是在将一个表中列的内容与另一个表中列的名称进行比较。在这种情况下,contains(['x' <contents of single row of column>], table.VariableNames) 会将 x 附加到表列的一行中的值(对于此实现,您需要遍历表的每一行),然后将此字符串与表的变量名称进行比较。您也可以使用 arrayfun 或其他东西在一行中执行此操作,但我现在正在从内存中执行此操作,无法回忆正确的语法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-19
      • 2022-11-16
      • 2012-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      相关资源
      最近更新 更多