如何在 Matlab 中重命名 table 变量?

How to rename table variables in Matlab?

我想从光谱数据矩阵创建一个 table,使用特定的变量列表(列,此处对应于 1000 个光谱波长值)而不是手动输入名称。 为此,我使用 array2table 函数,并且 matlab 文档显示行的名称和变量的标签必须作为元胞数组(而不是矩阵)放置。所以我需要先将我的 x 轴(光谱波长)转换为元胞数组。我使用以下内容:

C = num2cell(xaxis); % 转换成元胞数组(每个元胞包含 1 个值)

isvarname C % 检查变量作为元胞数组是否有效

T = array2table(R,'RowNames', concentration,'VariableNames',C);

这里:R是矩阵,浓度是1x500的Cell数组,x轴是光谱数据的波长1x1000(范围是600到1800,大约没有空值)。

不幸的是,我收到以下错误: “使用 array2table 时出错(第 62 行) VariableNames 属性 必须是元胞数组,每个元素包含一个非空字符串。"

这意味着我可以正确输入列(变量)名称(但是,行名称可以正常工作)。 注意:我尝试了 T.Properties.VariableNames = c 但它也不起作用。

我在 table 名称值上检查了另一个 post,但它没有帮助, 有没有想过这个? 非常感谢。

也许您输错了问题的代码,但您似乎使用的是数组 xaxis 而不是 C。不管怎样,我建议你尝试用这种方式将单元格内容转换为字符串

T = array2table(R,'RowNames', concentration,'VariableNames',cellfun(@(x)num2str(x),num2cell(xaxis),'uniformoutput',false));

编辑

查看 table docs 它说

Variable names, specified as the comma-separated pair consisting of 'VariableNames' and a cell array of character vectors that are nonempty and distinct. The number of character vectors must equal the number of variables. The variable names that you assign must be valid MATLAB® variable names. You can determine valid variable names using the function isvarname.

此外,isvarname 函数表示

A valid variable name begins with a letter and contains not more than namelengthmax characters. Valid variable names can include letters, digits, and underscores. MATLAB keywords are not valid variable names. To determine if the input is a MATLAB keyword, use the iskeyword function.

这意味着您不能将 xaxis 值本身用作变量名,您至少需要在前面加上一个字符并删除小数点。您可以使用以下方法

T = array2table(R,'RowNames', concentration,...
    'VariableNames',cellfun(@(x)['wavel_',regexprep(num2str(x),'.','_')],num2cell(xaxis),'uniformoutput',false));

此代码会将 'wavel_' 添加到数字字符串值之前。它还将使用 regexprep 函数将点替换为下划线。但是,这似乎真的没有必要,因为列名并不能真正提供信息。 array2table 函数的文档说,如果您不提供 'variableNames' 选项,它将执行以下操作:

If valid MATLAB identifiers are not available for use as variable names, MATLAB uses a cell array of N character vectors of the form {'Var1' ... 'VarN'} where N is the number of variables.

也许使用默认变量名就足够了。