0

So I have a cell array with multiple tables and I am trying to access the first column name of the table.

c={'table1', 'table2', 'table3'}

Both of the following lines gives me the error:

fieldnames(c{1})(1) 
fieldnames(c{1}){1}

Error: ()-indexing must appear last in an index expression.

But if I do following, it works:

fn=fieldnames(c{1})
fn{1}

Is there a way to do this with one line of code and can someone please explain the error?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user3919274
  • 3
  • 1
  • 2

2 Answers2

1

See this question.

Generally such problems can be solved using a function call (either a dummy function that just returns the input) or you could just replace the fn{} with an explicit call to subsref:

subsref(fieldnames(c{1}),substruct('{}',{1}));

Regarding your question about why the error happens - maybe this link could help.

Community
  • 1
  • 1
Dev-iL
  • 23,742
  • 7
  • 57
  • 99
  • I get following error: The "subs" field for the subscript argument to SUBSREF and SUBSASGN must be a cell or character array. – user3919274 Aug 26 '14 at 14:31
  • I was missing {} around the `1` inside `substruct`. Should work now. You should take a look at the links I mentioned for more info. – Dev-iL Aug 26 '14 at 14:37
  • The question @Dev-iL links to looks like exactly what you need. The anonymous function looks like a neat solution. `subindex = @(A,r,c) A(r,c); s = subindex(fieldnames(c{1}), 1, 1);` – sclarke81 Aug 26 '14 at 14:42
1

I've assumed that the follow code reproduces your data structure:

col1 = [1; 2; 3];
col2 = [4; 5; 6];
t1 = table(col1, col2);
t2 = table(col1, col2);
t3 = table(col1, col2);
c = {t1, t2, t3};

If that is the case then this should work:

subsref(fieldnames(c{1}),substruct('{}',{1}))
sclarke81
  • 1,739
  • 1
  • 18
  • 23