3

我有下表,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

4 回答 4

5

请参阅:表属性

例如:

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
于 2015-09-18T15:42:03.900 回答
4

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

isfield(table2struct(T),'Hold')
于 2015-09-18T15:49:12.053 回答
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
于 2016-09-01T09:36:05.220 回答
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

...并将其显示为奖励

于 2017-05-10T12:50:43.453 回答