Matlab: dynamic name for structure

2019-04-15 16:19发布

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.

3条回答
我想做一个坏孩纸
2楼-- · 2019-04-15 16:32

Use eval:

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

Edit: apologies, forgot the sprintf.

查看更多
Melony?
3楼-- · 2019-04-15 16:41

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.

查看更多
We Are One
4楼-- · 2019-04-15 16:46

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 = ...
查看更多
登录 后发表回答