Accessing numbered variables in loop

青春壹個敷衍的年華 提交于 2019-12-11 03:19:12

问题


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


来源:https://stackoverflow.com/questions/31162148/accessing-numbered-variables-in-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!