【问题标题】:MATLAB - split table into individual column arrays by their underlying data type?MATLAB - 按其基础数据类型将表拆分为单独的列数组?
【发布时间】:2017-02-26 17:07:04
【问题描述】:

在示例中:

load hospital
T = dataset2table(hospital)

我转换成一张桌子是因为我认为它可能更容易使用。但我并不关心答案中的方法是否适用于数据集或表。我想获取每一列,例如“LastName”、“Sex”等,获取其基础数据类型,并为每一列创建一个新变量。有没有办法在不遍历表的情况下完成此操作(即内置函数)?至少如果我无法转换为其基础类型,我可以将它们拆分为单独的单元格数组吗?

最终结果将在工作区中包含如下变量:

姓氏

性

年龄

重量

吸烟者

血压

试炼

【问题讨论】:

    标签: matlab


    【解决方案1】:

    使用表格,如果您想自动生成变量LastName、Sex、Age 等,您可以:

    • 获取变量的名称:它们存储在表的Properties.VariableNames 属性中
    • 然后将它们标识为变量列表的长度
    • 遍历表列(变量)以访问数据

    现在的问题在于创建用于在工作区中存储数据的单个变量的名称。

    您可以通过将数据存储在允许动态生成字段名称的struct 中来解决此问题。

    因此,您可以在表中的变量名称之后生成字段名称。

    建议的方法可能的实现如下:

    % Load the data
    load hospital
    % Convert dataset to table
    T = dataset2table(hospital)
    % Get the name of the varaibles
    var_names=T.Properties.VariableNames
    % Identify the number of varaibles (to be used in the next loop)
    n_var=length(var_names)
    % Store the data in a struct
    % Get the name of the rows
    hospital_data.row_names=T.Properties.RowNames;
    % Loop over the variables
    % Create dynamically the names of the fields of the struct after the name
    % of the variables
    for i=1:n_var
       hospital_data.(var_names{i})=T{:,i}
    end
    

    这会生成一个名为 hospital_data 的 struct,其字段为:

    hospital_data = 
    
            row_names: {100x1 cell}
             LastName: {100x1 cell}
                  Sex: [100x1 nominal]
                  Age: [100x1 double]
               Weight: [100x1 double]
               Smoker: [100x1 logical]
        BloodPressure: [100x2 double]
               Trials: {100x1 cell}
    

    希望这会有所帮助,

    卡普拉'

    【讨论】:

      【解决方案2】:

      我认为findgroups 和/或splitapply 函数可能会对您有所帮助!

      这是一个链接,您可以在其中查看它们的工作原理:

      https://www.mathworks.com/help/matlab/matlab_prog/split-table-data-variables-and-apply-functions.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-21
        • 1970-01-01
        • 2020-03-28
        • 1970-01-01
        • 1970-01-01
        • 2013-12-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多