Matlab: dynamic name for structure

半腔热情 提交于 2019-12-04 19:24:27

Use a structure with a dynamic field name.

For example,

mydata.(casename(12:18)) = struct;

will give you a struct mydata with a field test001.

You can then later add your x, y, z fields to this.

You can use the fields later either by mydata.test001.x, or by mydata.(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 directly evals user input:

eval('%s = struct(''x'',''y'',''z'');',casename(12:18));

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 and y vectors have same length. In this case you can store all data from the different files into 2 matrices and call plot(x,y) to plot each column as a series.

Alternatively, you can use a cell array such that:

c = cell(2,nufiles);
for ii = 1:numfiles
     c{1,ii} = import x data from file ii
     c{2,ii} = import y data from file ii
end
plot(c{:})

A structure, on the other hand

s.('test001').x = ...
s.('test001').y = ...

Use eval:

eval(sprintf('%s = struct(''x'',''y'',''z'');',casename(12:18)));

Edit: apologies, forgot the sprintf.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!