Matlab:结构的动态名称 [英] Matlab: dynamic name for structure

查看:123
本文介绍了Matlab:结构的动态名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在matlab脚本中创建一个带有变量名的结构.这个想法是提取由用户填充的一部分输入字符串,并使用该名称创建一个结构.例如:

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');

在此示例中, casename(12:18)给我的结果是 test001 .

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);

问题是 casename(12:18)= struct('x','y','z'); 行对于Matlab无效,因为它使我将字符串更改为一个结构.我在struct中找到的所有示例均基于

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');

而且我找不到基于字符串为 S 命名动态名称的方法.

And I can't find a way to make a dynamical name for S based on a string.

我希望有人能理解我写的内容:)我在FAQ和Google上进行了检查,但找不到相同的问题.

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 a structure with a dynamic field name.

例如,

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

将为您提供带有字段test001的结构mydata.

will give you a struct mydata with a field test001.

然后可以在其中添加xyz字段.

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

您以后可以通过mydata.test001.xmydata.(casename(12:18)).x使用这些字段.

You can use the fields later either by mydata.test001.x, or by mydata.(casename(12:18)).x.

如果有其他答案,请尽可能避免使用eval.这使得调试起来非常困难,并且给出了示例,该示例直接eval用户输入:

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));

甚至是安全的风险-如果用户键入所选字符为system(''rm -r /''); a的字符串会发生什么情况?不好的是这样.

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.

这篇关于Matlab:结构的动态名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆