0

I wish to access data within a table with dot notation that includes strings. I have a list of strings representing columns of interest within the table. How can I access data using those strings? I wish to create a loop going through the list of strings.

For example for table T I have columns {a b c d e}. I have a 1x3 cell cols={b d e}.

Can I retrieve data using cols in the format (or equivalent) T.cols(1) to to give me the same result as T.b?

1 Answer 1

3

You can fetch directly the data using {curly braces} and strings as column indices as you would for a cell array.

For example, lets's create a dummy table (modified from the docs):

clc;
close all;


LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'};
a = [38;43;38;40;49];
b = [71;69;64;67;64];
c = [176;163;131;133;119];
d = [124 93; 109 77; 125 83; 117 75; 122 80];

T = table(a,b,c,d,...
    'RowNames',LastName)

The table looks like this:

T = 

                a     b      c         d     
                __    __    ___    __________

    Smith       38    71    176    124     93
    Johnson     43    69    163    109     77
    Williams    38    64    131    125     83
    Jones       40    67    133    117     75
    Brown       49    64    119    122     80

Now select columns of interest and get the data:

%// Select columns of interest
cols = {'a' 'c'};

%// Fetch data
T{:,cols}

ans =

    38   176
    43   163
    38   131
    40   133
    49   119

Yay!

3
  • do you know if you can use the same to name variables . e.g. T.cols(1)=T{:,datavector}
    – Mary
    Jul 2, 2015 at 13:44
  • 1
    @Mary - Yes. Use dynamic field names: T.(cols{1}) = T(:,datavector);.
    – rayryeng
    Jul 2, 2015 at 14:06
  • @Mary - My pleasure :) Happy MATLABing! Also feel free to stop by our room if you need further help: chat.stackoverflow.com/rooms/81987/matlab
    – rayryeng
    Jul 2, 2015 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.