循环访问编号变量 [英] Accessing numbered variables in loop

查看:83
本文介绍了循环访问编号变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Matlab文档或留言板上都找不到以下问题的答案.有关使用动态变量名称以及如何在创建变量时避免使用eval函数的信息很多.但是,我的查询涉及在循环内访问已编号的变量.

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 

我无法更改这些变量的名称,但只想在循环内访问字段x1, x2, x3.可以在不使用eval的情况下以简洁的方式执行此操作吗?

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?

使用eval的示例:

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

推荐答案

您可以使用getfield:

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

或更短:

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

这篇关于循环访问编号变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆