3

I Have the following 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

How can I test if a column in a table exists? For example isfield(T,'Hold') returns 0. Exist, isstruct also do not work. I would need the test to simply return a true or false result.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mary
  • 788
  • 6
  • 19
  • 43

4 Answers4

5

See: Table Properties

For example:

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)

Returns:

columnexists =

     1
sco1
  • 12,154
  • 5
  • 26
  • 48
4

You can convert to struct and then use isfield:

isfield(table2struct(T),'Hold')
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • 1
    This might be a performance hit for larger data sets. Probably better to use [solution by excaza](http://stackoverflow.com/a/32656035/388664) (with Mohsen's comment). – Nikola Malešević Aug 17 '16 at 11:33
0
ismember('myFieldName', myTable.Properties.VariableNames)

or put into a nice function:

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

How to use the function:

x = [2 5 3];
t = table(x); % create table with a field called 'x'

if tablehasfield(t, 'x')
    % do something
end
Phlox Midas
  • 4,093
  • 4
  • 35
  • 56
0

The usual tests cause a script to crash if the subject (Table in this case) doesn't exist: isfield(), ismember(), isempty() these all have that problem.

exist() checks without crashing, but only works on the table, so you still need checks for the existence of the column, and you asked whether there was data in the column:

%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

...and displays it as a bonus