How to avoid eval when eval seems unavoidable

조회 수: 8 (최근 30일)
Leo Simon
Leo Simon 2021년 11월 1일
댓글: Walter Roberson 2021년 11월 1일
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
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?
Leo Simon
Leo Simon 2021년 11월 1일
definitely wnat (though don't necessarily need) to unpack the struct.

댓글을 달려면 로그인하십시오.

답변 (2개)

Matt J
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,
  댓글 수: 2
Leo Simon
Leo Simon 2021년 11월 1일
This is really nice but isn't there some kind of way to actually make it work at runtime? Eg., it looks like this *should* work, (using the maligned eval)
eval(structvars(S))
but of course it doesn't. Would be truly wonderful if it did though.
Matt J
Matt J 2021년 11월 1일
편집: Matt J 2021년 11월 1일
I don't see what advantage you anticipate in having the unpacking done at runtime. The expressed purpose of your post was to avoid the disadvantages of eval(). However, you can make it work with eval() by doing,
eval(structvars(S).')

댓글을 달려면 로그인하십시오.


Walter Roberson
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
Steven Lord
Steven Lord 2021년 11월 1일
Why? What's your use case where you need the fields as independent variables?
Walter Roberson
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 CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by