MATLAB Answers

How do I name this variable dynamically?

15 views (last 30 days)
Ulrik William Nash
Ulrik William Nash on 12 Sep 2016
Edited: Stephen on 19 Jun 2019
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?

Answers (2)


Henry Giddens
Henry Giddens on 12 Sep 2016
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 Comments
Henry Giddens
Henry Giddens on 12 Sep 2016
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!

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by