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

조회 수: 6 (최근 30일)
Russell Arnott
Russell Arnott 2017년 11월 29일
답변: Russell Arnott 2017년 12월 7일
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
Stephen23
Stephen23 2017년 11월 30일
편집: Stephen23 2017년 11월 30일
"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 2017년 11월 30일
편집: Matt J 2017년 11월 30일
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.

댓글을 달려면 로그인하십시오.

답변 (3개)

Matt J
Matt J 2017년 11월 30일
편집: Matt J 2017년 11월 30일
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 2017년 11월 30일
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 2017년 12월 7일
Thanks for your suggestions every one :-)

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by