Accessing numbered variables in loop

2019-07-19 06:11发布

问题:

I've been unable to find an answer to the following question either in the Matlab documentation, or on message boards. There is much information regarding the use of dynamic variable names and how to avoid use of the eval function when creating variables. My query however concerns accessing pre-existing variables, which are numbered, inside a loop.

Consider that someone has sent me a table with various field values. Some of them are numbered such that we have something like:

table.abc
table.x1
table.x2
table.x3
table.xyz 

I am unable to change the names of these variables, but would like to access only the fields x1, x2, x3 inside a loop. Is it possible to do this in a neat way whilst avoiding the use of eval in this case?

An example using eval:

for i=1:3
    extract(i) = eval(['table.x',num2str(i)]);
end

回答1:

You can use getfield:

for i=1:3
    extract(i) = getfield(table,['x',num2str(i)]);
end

or even shorter:

for i=1:3
    extract(i) = table.(['x',num2str(i)]);
end