以数字方式迭代 MATLAB 结构体
是否可以像向量一样以数字方式迭代 MATLAB 结构,而不是使用字段名称?
简而言之,我尝试在 Simulink 的 EML 块内执行以下操作:
S.a.type = 1;
S.a.val = 100;
S.a.somevar = 123;
S.b.type = 2;
S.b.val = 200;
S.b.somevar2 = 234;
S.c.type = 3;
S.c.val = 300;
S.c.somevar3 = 345;
for i = 1:length(s)
itemType = S(i).type;
switch itemType
case 1
val = S(i).val * S(i).somevar1;
case 2
val = S(i).val * S(i).somevar2;
case 3
val = S(i).val * S(i).somevar3;
otherwise
val = 0
end
end
disp(var);
Is it possible to iterate through a MATLAB structure numerically like a vector instead of using the field names?
Simply, I am trying to do the following inside an EML block for Simulink:
S.a.type = 1;
S.a.val = 100;
S.a.somevar = 123;
S.b.type = 2;
S.b.val = 200;
S.b.somevar2 = 234;
S.c.type = 3;
S.c.val = 300;
S.c.somevar3 = 345;
for i = 1:length(s)
itemType = S(i).type;
switch itemType
case 1
val = S(i).val * S(i).somevar1;
case 2
val = S(i).val * S(i).somevar2;
case 3
val = S(i).val * S(i).somevar3;
otherwise
val = 0
end
end
disp(var);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够使用 sprintf 动态生成字段名,如下所示:
You should be able to generate the fieldnames dynamically using sprintf using something like the following:
您需要使用字段名称,但您可以动态地这样做。如果您的结构定义为:
那么您可以使用以下任一方式访问字段
field1
您唯一需要的是函数
fieldnames
来动态获取字段名称,以便您的代码示例看起来有点像如果这些是确切的字段名称,您应该做一些其他事情。首先,您需要重新考虑您的名称,其次您可以使用 Matt 的解决方案的一部分来简化您的代码。
You need to use the field names, but you can do so dynamically. If you have a structure defined as:
Then you can access the field
field1
with eitherThe only thing you need is the function
fieldnames
to dynamically get the field names such that your code example will look somewhat likeIf those are the exact field names, you should do some other things. First of all you would need to rethink your names and secondly you could use part of Matt's solution to simplify your code.