【问题标题】:Test for existance of column in table Matlab测试表 Matlab 中是否存在列
【发布时间】:2015-12-15 20:00:15
【问题描述】:

我有下表,T:

      Hold       Min    Max 
    _________    ___    ____

     0.039248    0      0.05
     0.041935    0      0.05
     0.012797    0      0.05
    0.0098958    0      0.05
     0.014655    0      0.05

如何测试表中的列是否存在?例如isfield(T,'Hold') 返回0Existisstruct 也不行。我需要测试来简单地返回一个真假结果。

【问题讨论】:

    标签: matlab boolean matlab-table


    【解决方案1】:

    见:Table Properties

    例如:

    LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'};
    Age = [38;43;38;40;49];
    Height = [71;69;64;67;64];
    Weight = [176;163;131;133;119];
    BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
    
    T = table(Age,Height,Weight,BloodPressure,...
        'RowNames',LastName);
    
    myquery = 'Age';
    columnexists = ismember(myquery, T.Properties.VariableNames)
    

    返回:

    columnexists =
    
         1
    

    【讨论】:

    • 你可以在最后一行使用ismember columnexists =ismember(myquery, T.Properties.VariableNames)
    【解决方案2】:

    您可以转换为struct,然后使用isfield

    isfield(table2struct(T),'Hold')
    

    【讨论】:

    • 这可能会影响较大数据集的性能。使用solution by excaza 可能更好(与 Mohsen 的评论)。
    【解决方案3】:
    ismember('myFieldName', myTable.Properties.VariableNames)
    

    或放入一个不错的函数:

    function hasField = tablehasfield(t, fieldName)
        hasField = ismember(fieldName, t.Properties.VariableNames);
    end
    

    如何使用该功能:

    x = [2 5 3];
    t = table(x); % create table with a field called 'x'
    
    if tablehasfield(t, 'x')
        % do something
    end
    

    【讨论】:

      【解决方案4】:

      如果主题(本例中为表格)不存在,通常的测试会导致脚本崩溃:isfield(), ismember(), isempty() 这些都有这个问题。

      exist() 检查不会崩溃,但仅适用于表,因此您仍然需要检查列是否存在, 并且您询问该列中是否有数据:

      %define table
      Hold = [0.039248 0.041935 0.012797 0.0098958 0.014655]';
      Min=[0 0 0 0 0]';
      Max = [0.05 0.05 0.05 0.05 0.05]';
      T = table(Hold,Min,Max);
      
      %test table
      if exist('T') 
         myquery = 'Max';
         if ismember(myquery, T.Properties.VariableNames)
             col = find(strcmp(myquery, T.Properties.VariableNames));
             T(:,col)
         end
       end
      

      ...并将其显示为奖励

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-04
        • 2010-09-14
        • 2011-04-09
        • 2019-06-13
        • 2011-08-04
        • 2012-04-16
        • 2018-02-18
        • 2013-10-17
        相关资源
        最近更新 更多