Mary
Mary

Reputation: 788

Test for existance of column in table Matlab

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.

Upvotes: 3

Views: 1866

Answers (4)

Adam Ratcliff
Adam Ratcliff

Reputation: 1

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

Upvotes: 0

sco1
sco1

Reputation: 12214

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

Upvotes: 5

Phlox Midas
Phlox Midas

Reputation: 4349

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

Upvotes: 0

Luis Mendo
Luis Mendo

Reputation: 112659

You can convert to struct and then use isfield:

isfield(table2struct(T),'Hold')

Upvotes: 4

Related Questions