Rename workspace variable (table) with a string value within a loop
10 views (last 30 days)
Show older comments
Hello, I am trying to process some data and want to upload all the files from a specific experiment over time.
tank=['02'] % insert experiment number
days=[21:25]; % insert date range
for d=1:length(days)
filename = ['201708' num2str(days(d)) '_tank' tank '_down_01.txt'];
T = readtable(filename);
z=filename(7:15);
%
% INSERT CODE HERE THAT ALLOWS ME TO RENAME T AS THE CONTENTS OF STRING z - HELP!
%
clear T
end
It'd be great if someone could help with the code! I'm trying to get away from using EVAL as I know that's not good programming etiquette... Maybe assignin ?
3 Comments
Stephen23
on 30 Nov 2017
Edited: Stephen23
on 30 Nov 2017
"I'm trying to get away from using EVAL as I know that's not good programming etiquette"
"Etiquette" is an interesting descriptor for the fact that using eval to magically access variables makes your code slow, complex, buggy, insecure, hard to debug, and obfuscates the code intent.
This has been discussed a thousand times before, and each of those discussions explains better alternatives: just use indexing or fieldnames.
"INSERT CODE HERE THAT ALLOWS ME TO RENAME T AS THE CONTENTS OF STRING z - HELP!"
That is exactly what you should not do. The problem is not eval in itself as you seem to think, the problem is caused by magically creating or accessing variable names dynamically. Read these to know more:
Matt J
on 30 Nov 2017
Edited: Matt J
on 30 Nov 2017
I'm trying to get away from using EVAL as I know that's not good programming etiquette... Maybe assignin
Assignin has the same hazards as eval. The same for evalin() and load() ... basically anything capable of implicitly creating variables in the workspace.
Answers (3)
Matt J
on 30 Nov 2017
Edited: Matt J
on 30 Nov 2017
If strings really are the most convenient way to differentiate the tables, then I would use dynamic structure field names.
S.(z)=T;
Functionally, there is no difference between a variable and a structure field, except that the latter can be dynamically named, gracefully.
0 Comments
Stephen23
on 30 Nov 2017
Note that the data being encoded is fundamentally numeric (days and experiment number). Rather than awkwardly and pointlessly converting numeric data to string you can just use a simple non-scalar structure to hold your data:
Exactly as Jos (10584) wrote twelve hours ago:
DATAS(d).values = T ;
0 Comments
See Also
Categories
Find more on Whos 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!