MATLAB Answers

0

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

Asked by Russell Arnott on 29 Nov 2017
Latest activity Answered by Russell Arnott on 7 Dec 2017
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.

3 Answers

Answer by Matt J
on 30 Nov 2017
Edited by 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

Sign in to comment.


Answer by Stephen Cobeldick 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

Sign in to comment.


Answer by Russell Arnott on 7 Dec 2017

Thanks for your suggestions every one :-)

  0 Comments

Sign in to comment.