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?
0 件のコメント
回答 (2 件)
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
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
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 Center および File Exchange で Cell Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!