Hey,
i have a problem importing several sheets into MatLab Workspace.
names is a String Array including different file names. I get an Error when i try to include the varibale as part of the file Directory:
May someone help :)
files = dir('.......');
names = {files.name};
for k=1:numel(names)
k = readtable("C:\Users\Desktop\Test\*(names{k})*.txt", opts);
end

댓글 수: 1

Mario Malic
Mario Malic 2020년 11월 8일
편집: Mario Malic 2020년 11월 8일
Are you trying to open sheets from one folder that have the same name in another?

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

답변 (1개)

dpb
dpb 2020년 11월 8일
편집: dpb 2020년 11월 9일

0 개 추천

Variables are variables, not text.
rootdir="C:\Users\Desktop\Test\"; % use variable so can change easily
filespec="*.txt"; % ditto for a file pattern
d=dir(fullfile(rootdir,filespec)); % use fullfile() to put pieces together
for i=1:numel(d)
t=readtable(fullfile(rootdir,d(i).name), opts);
end
ADDENDUM:
Above reads each in turn; process each before going on or catenate if same variables and makes sense or at worst, use cell array to store into and retrieve from.
In
readtable("C:\Users\Desktop\Test\*(names{k})*.txt", opts);
above, you've included the variable name names as literal text so it isn't recognized as a variable by the parser.

댓글 수: 4

Ok, so I adapted the code as follows:
files = dir('...');
names = {files.name};
rootdir = "C:\Users\Desktop\Test\";
for k=1:numel(names)
eval( [['T' int2str(k)] ' = readtable(fullfile(rootdir, names{k}), opts)']);
end
This gives me the TableData stored in Variables T1, T2, T3,.......
Now i want to change these T1, T2..... Variable Names to the name of the Files ( which names i stored in the names{} Array before the get the Path name)
Every Code i try results in Error messages that the eval() function needs text as input.
So what Code could work to replace ['T' int2str(k)] with the Names of the files storen in names.
The new Variable names should be names{k}.
Ty in advance.
dpb
dpb 2020년 11월 9일
Do NOT use eval to create dynamic names this way. As you see, "There be dragons!"
Either process each in turn before going on to the next or at worst store in a cell array to acces each by index.
If they're related data of same type, probably catenating into one table would be the better solution.
Whatever you choose, leave eval out of it; nothing good can come of venturing down that path.
Image Analyst
Image Analyst 2020년 11월 9일
Uh, yeah, that was a huge mistake. Why didn't you just go with dpb's code???
Stephen23
Stephen23 2020년 11월 9일
편집: Stephen23 2020년 11월 9일
"Why didn't you just go with dpb's code???"
Most likely because of this
and an attempt to "solve" it using dynamic variables: http://xyproblem.info/

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

카테고리

도움말 센터File Exchange에서 File Operations에 대해 자세히 알아보기

질문:

2020년 11월 8일

편집:

2020년 11월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by