Finding a string in a series of unknown variables
이전 댓글 표시
Say I have a list of variables on my workspace that were randomly generated, but each have a substructure with a title:
workspace looks like this:
- a
- b
- c
- d
but if you type a.title you output "Ch1". Each of these also have substructures where my data is located, usually named .values.
I want to write a script that renames my variables based on what the .title string is. I wrote it by doing this
z = who;
for i = 1:length(z)
if z(i).title == 'Ch1';
Ch1.values = z(i).values;
end
end
but encounter a problem becauze z(i) is not the variable, but rather the string of the variable. In other words, I can't do z(i).title because z(i) = 'a' instead of z(i) = a
Thanks for the help, Alex
댓글 수: 1
It is worth noting that generating variable names with eval is almost always a bad idea:
etc, etc...
답변 (2개)
Chad Greene
2014년 10월 6일
Does this do what you need?
z = who;
Ch1.values = z.values{strcmp(z.title,'Ch1')};
If I understood correctly, this should work:
for i = 1:numel(z)
v = eval(z{i});
if isstruct(v) && all(ismember({'title', 'values'}, fieldnames(v)))
eval([v.title ' = v.values;']);
eval(['clear ' z{i}]);
end
end
댓글 수: 2
Guillaume
2014년 10월 7일
The whole variable structure in the OP is a bad idea, but that's what it is. evalin would be of no benefit unless the code was written in a function. assignin could replace one of the eval, but in this case, there is no alternative for the 2nd eval.
For reference, the first eval could be replaced with:
assignin('base', v.title, v.values);
카테고리
도움말 센터 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!