Finding a string in a series of unknown variables
1 view (last 30 days)
Show older comments
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 Comment
Answers (2)
Chad Greene
on 6 Oct 2014
Does this do what you need?
z = who;
Ch1.values = z.values{strcmp(z.title,'Ch1')};
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
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);
See Also
Categories
Find more on Workspace Variables and MAT-Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!