How to avoid eval when eval seems unavoidable
5 次查看(过去 30 天)
显示 更早的评论
Everybody on this forum agrees that eval is a terrible terible thing to use. But often it seems to me to be unavoidable. The one below is only the most recent of these that I have encountered. Suppose I want to "unpack" a struct, using the fields of the struct as variable names.
For example
S.a = 1
S.b = 2
etc
Now I want to create variables a=1 and b=2, etc. The only way I know how to do this goes something like this;
Fields = fieldnames(S);
for ii=1:numel(Fields);
field = Fields{ii};
value = getfield(S,field);
eval([ field '=' num2str(value) ';']);
end
a
b
How can I do a loop like this, without using eval?
2 个评论
Steven Lord
2021-11-1
Do you have to unpack the struct? Is there a reason you can't or don't want to just index into the struct?
回答(2 个)
Matt J
2021-11-1
编辑:Matt J
2021-11-1
One way to avoid eval in this case is to use an automatic code-writing tool instead of unpacking at run time. I created the following precisely for this purpose,
Walter Roberson
2021-11-1
orderfields, struct2cell, cell expansion in the context of a multiple variable output.
Assuming that the list of fields is fixed but not necessarily their order.
3 个评论
Walter Roberson
2021-11-1
It is not clear to me why my suggestion is not suitable for your purposes? Do you need to have struct with unpredictable field names that have to be moved into variables?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!