How do I name this variable dynamically?

1 次查看(过去 30 天)
I am trying to fetch a series of simulation runs from a computer, and the following works just fine:
dataset = j1.fetchOutputs{:};
However, I have more than simply j1. I have j1 to ji. So, I thought looping through 1:i using the following line would work, but it doesn't:
batch = sprintf('j%d' ,i)
and then
dataset = batch.fetchOutputs{:};
I get the error:
"Struct contents reference from a non-struct array object". Can someone help me out here?

回答(2 个)

Stephen23
Stephen23 2016-9-12
编辑:Stephen23 2019-6-19

Henry Giddens
Henry Giddens 2016-9-12
In your example above, the variable "batch" is a string. You cant reference object properties or methods, or structure fields from a string, which is what the error message is telling you.
In answer to your question for dynamically addressing variable names, you can use 'eval'
batch = eval(sprintf('j%d' ,i));
dataset = batch.fetchOutputs
% or
% dataset = eval(sprintf('j%d.fetchOutputs{:});
A better way i guess would be to store all the variables "j1" to "ji" as inputs to an array when they are created, rather than as seperate variables. Then you would just need to reference each entry in the array and avoid using eval.
  2 个评论
Stephen23
Stephen23 2016-9-12
Let me quote Steve Lord, who works for TMW (the company that make MATLAB):
I know, beginners always think that magically making variables pop into existence is a great idea. It isn't. It is slow and buggy, and those beginners should take the time to learn from Steve Lord and other MATLAB experts who show much faster and more efficient ways to write code.
Henry Giddens
Henry Giddens 2016-9-12
编辑:Henry Giddens 2016-9-12
Just to say that I agree, and don't ever use it myself (Don't really know why I suggested it...). Thanks Stephen for giving a good explanation as to why its a bad idea!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Cell Arrays 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by