表Matlab中列的存在性测试

时间:2015-09-18 15:36:18

标签: matlab boolean matlab-table

我有下表,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也不起作用。我需要测试才能简单地返回真或假的结果。

4 个答案:

答案 0 :(得分:5)

请参阅: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

答案 1 :(得分:4)

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

isfield(table2struct(T),'Hold')

答案 2 :(得分:0)

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

答案 3 :(得分:0)

如果主题(本例中为表格)不存在,通常的测试会导致脚本崩溃: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

...并将其显示为奖金