Rename workspace variable (table) with a string value within a loop

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

Why do want to do that? It is easier to use the same variable name for all the code. I you want to store multiple data into a single variable use a struct or a cell array
DATAC{d} = T ;
DATAS(d).values = T ;
"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:
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.

Sign in to comment.

Answers (3)

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.
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 ;

Categories

Asked:

on 29 Nov 2017

Answered:

on 7 Dec 2017

Community Treasure Hunt

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

Start Hunting!