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

답변 (2개)

Chad Greene
Chad Greene 2014년 10월 6일
Does this do what you need?
z = who;
Ch1.values = z.values{strcmp(z.title,'Ch1')};

댓글 수: 1

Jinn
Jinn 2014년 10월 6일
Nope, same issue I run into which is that you can't use the substructure of z because z is now a string instead of a structured variable.
I'm starting to think that 'who' is wrong. I need a function that will let me cycle through the variables in the workspace. Can't find a question that's been asked about this so if it's not solved with this thread I will open a new one about that.
Appreciate the help though

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

Guillaume
Guillaume 2014년 10월 6일
편집: Guillaume 2014년 10월 6일
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

José-Luis
José-Luis 2014년 10월 6일
편집: José-Luis 2014년 10월 6일
Using eval is a bad idea and can usually be avoided.
You could alternatively use assignin or evalin.
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에 대해 자세히 알아보기

태그

질문:

2014년 10월 6일

편집:

2014년 10월 30일

Community Treasure Hunt

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

Start Hunting!

Translated by