Finding a string in a series of unknown variables

1 view (last 30 days)
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

Answers (2)

Chad Greene
Chad Greene on 6 Oct 2014
Does this do what you need?
z = who;
Ch1.values = z.values{strcmp(z.title,'Ch1')};
  1 Comment
Jinn
Jinn on 6 Oct 2014
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

Sign in to comment.


Guillaume
Guillaume on 6 Oct 2014
Edited: Guillaume on 6 Oct 2014
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 Comments
José-Luis
José-Luis on 6 Oct 2014
Edited: José-Luis on 6 Oct 2014
Using eval is a bad idea and can usually be avoided.
You could alternatively use assignin or evalin.
Guillaume
Guillaume on 7 Oct 2014
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);

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!