I want to create a structure with a variable name in a matlab script. The idea is to extract a part of an input string filled by the user and to create a structure with this name. For example:
CompleteCaseName = input('s');
USER WRITES '2013-06-12_test001_blabla';
CompleteCaseName = '2013-06-12_test001_blabla'
casename(12:18) = struct('x','y','z');
In this example, casename(12:18) gives me the result test001.
I would like to do this to allow me to compare easily two cases by importing the results of each case successively. So I could write, for instance :
plot(test001.x,test001.y,test002.x,test002.y);
The problem is that the line casename(12:18) = struct('x','y','z'); is invalid for Matlab because it makes me change a string to a struct. All the examples I find with struct are based on a definition like
S = struct('x','y','z');
And I can't find a way to make a dynamical name for S based on a string.
I hope someone understood what I write :) I checked on the FAQ and with Google but I wasn't able to find the same problem.
Use eval:
Edit: apologies, forgot the sprintf.
Use a structure with a dynamic field name.
For example,
will give you a struct
mydata
with a fieldtest001
.You can then later add your
x
,y
,z
fields to this.You can use the fields later either by
mydata.test001.x
, or bymydata.(casename(12:18)).x
.If at all possible, try to stay away from using
eval
, as another answer suggests. It makes things very difficult to debug, and the example given there, which directlyeval
s user input:is even a security risk - what happens if the user types in a string where the selected characters are
system(''rm -r /''); a
? Something bad, that's what.As I already commented, the best case scenario is when all your
x
andy
vectors have same length. In this case you can store all data from the different files into 2 matrices and callplot(x,y)
to plot each column as a series.Alternatively, you can use a cell array such that:
A structure, on the other hand