Trying to pass a variable name for a file in a for loop to xlsread
5 次查看(过去 30 天)
显示 更早的评论
I'm trying to use xlsread to open a variable filename on each iteration of a for loop. The code I initially used was
for vj=1:prime_file_num
BaseName='15_File_';
k=prime_file_num1(vj,1);
FileName=[BaseName,num2str(k)];
[~,~,rawS] = xlsread(FileName);
which worked for one iteration, then just seemed to grind away forever trying to read the next File, and now just grinds even on the first iteration. I tried changing the code to
for vj=1:prime_file_num
BaseName='15_File_';
k=prime_file_num1(vj,1);
FileName=[BaseName,num2str(k)];
pathname = 'C:\Documents\MATLAB\FileName.xlsx';
[~,~,rawS] = xlsread(pathname);
But that just returns the error that xlsread can't find the file--its trying to open a file named 'C:\Documents\MATLAB\FileName.xlsx, rather than '15_File_2' for example.
Can anybody tell me what I'm doing wrong or is what I'm trying even possible. Thanks
4 个评论
采纳的回答
Jan
2021-9-26
编辑:Jan
2021-9-27
pathname = 'C:\Documents\MATLAB\FileName.xlsx';
This is a fixed CHAR vector and does not consider the variable FileName.
Stephen's appraoch is working, if the path name is fixed:
BaseName = '15_File_%d.xlsx'; % [EDITED, file extension added]
pathname = 'C:\Documents\MATLAB\';
for vj = 1:prime_file_num
filename = sprintf(BaseName, prime_file_num1(vj, 1));
file = fullfile(pathname, filename);
% [~,~,rawS] = xlsread(file);
disp(file); % For testing
...
end
2 个评论
Jan
2021-9-27
编辑:Jan
2021-9-27
No, my code does not open anything. It displays the file names only. This means, that you are doing something else and I cannot know, what it is.
Solve the problem step by step. Start with the shown code. Does it work? Do you see the different file names? If all filenames are equal, you have shown, that prime_file_num1 contains only the value 2.
Please post the output of the above code, if you get any problems there.
If this is working proceed with the next step to uncomment the xlsread() command. Do you get an error message now? If so, please post a copy of the complete message.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Entering Commands 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!