在 MATLAB 中将字符串单元格转换为 table 列

Convert cell of strings into column of table in MATLAB

我尝试使用向量作为 table(在 MATLAB 中)中的列。但是,我总是会遇到不同的错误。下面是一个可重现的例子,连同收到的错误:

% What I have:
my_table = array2table(NaN(5, 3));
my_table.Properties.VariableNames = {'col_1' 'col_2' 'col_3'};
my_cell = {'a', 'b', 'c', 'd', 'e'};

% What I tried:
my_table.col_3 = my_cell; %Error: To assign to or create a variable in a table, the number of rows must match the height of the table.
my_table.col_3(1:5) = my_cell; %Error: Conversion to double from cell is not possible.
my_table.col_3.Properties.VariableTypes = {'string'}; %Error: Unable to perform assignment because dot indexing is not supported for variables of this type.

我该如何解决这个任务?

以下作品:

my_table.col_3 = my_cell';
% or maybe you prefer
my_table.col_3 = cell2mat(my_cell)';

我们来分析一下你的问题:

  1. 你的尺寸不对,你只需要将输入转置,从一行到一列!

  2. 正如它所说,您不能直接从单元格隐式转换为其他内容。 cell2mat 是一种方法。

  3. 没有 my_table.col_3.Properties 这样的东西,所以 MATLAB 会感到困惑,并认为您正在用那个点 . 做其他事情。

如果您想保留 cell 类型,您可以使用:

my_table.col_3 = my_cell.'

优点:每一行可以存储多个字符。

为什么 my_table.col_3 = my_cell 不起作用:

%size(my_table.col_3) = <b>5x1</b>
%                       ↕ ↕
%size(my_cell)        = <b>1x5</b>
</pre>

如您所见,元胞数组第一维的大小与您 table 的第一维大小不匹配。因此,您可以简单地用 .'

置换单元格的尺寸

所以现在:

%size(my_table.col_3) = 5x1
%                       ↕ ↕
%size(my_cell.')      = 5x1

和 matlab(和你)is/are快乐。