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

16 Ansichten (letzte 30 Tage)
Russell Arnott
Russell Arnott am 29 Nov. 2017
Beantwortet: Russell Arnott am 7 Dez. 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 Kommentare
Stephen23
Stephen23 am 30 Nov. 2017
Bearbeitet: Stephen23 am 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
Matt J am 30 Nov. 2017
Bearbeitet: Matt J am 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.

Melden Sie sich an, um zu kommentieren.

Antworten (3)

Matt J
Matt J am 30 Nov. 2017
Bearbeitet: Matt J am 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.

Stephen23
Stephen23 am 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 ;

Russell Arnott
Russell Arnott am 7 Dez. 2017
Thanks for your suggestions every one :-)

Community Treasure Hunt

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

Start Hunting!

Translated by