Load file with changeable variable
1 次查看(过去 30 天)
显示 更早的评论
Dear all,
I would like to load some .mat file in this way:
File1 = 'D:\prj\MyComp\name.mat';
File2 = 'D:\prj\MyComp\anothername.mat';
File3 = 'D:\prj\MyComp\anotherdifferentname.mat';
namesWork = who;
outStr = regexpi(namesWork,'File');
ind = ~cellfun('isempty',outStr);
ind = ind(ind==1);
for h = 1:length(ind)
load(['File' num2str(h)])
...
end
But it returns this error message:
Error using load
Unable to read file 'File1'. No such file or directory.
Thanks in advance, JOE
1 个评论
Stephen23
2017-4-26
编辑:Stephen23
2017-4-26
What you are trying to do is load a file named 'File1', because that is the string that you are giving to load. To generate the value of the variable File1 you would have to evaluate the string. But that would be a bad way to write code: Slow, buggy, obfuscated, and really hard to debug:
采纳的回答
Stephen23
2017-4-26
编辑:Stephen23
2017-4-26
Don't waste your life writing buggy code. Much simpler and much more reliable would be to use a cell array:
C = {...
'D:\prj\MyComp\name.mat',...
'D:\prj\MyComp\anothername.mat',...
'D:\prj\MyComp\anotherdifferentname.mat'};
for k = 1:numel(C)
S = load(C{K});
...
end
By choosing to use a simple, easy-to-understand way of writing code (i.e. a cell array) I solved your task in just a few efficient lines of code. This is explained very well in the documentation and on this forum:
0 个评论
更多回答(1 个)
Geoff Hayes
2017-4-26
J - when you call
load(['File' num2str(h)])
you end up trying to load a file whose name is (if h is one) File1. This is a string and not the variable that you had previously initialized and so the error message makes sense.
What I would do is to add all of your file names to a cell array and then iterate over each element in the array. As each element is a valid file name, then you should be able to load the file. For example,
myFiles = cell(3,1);
myFiles{1} = 'D:\prj\MyComp\name.mat';
myFiles{2} = 'D:\prj\MyComp\anothername.mat';
myFiles{3} = 'D:\prj\MyComp\anotherdifferentname.mat';
and then
for k=1:length(myFiles)
X = load(myFiles{k});
% do something
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 String Parsing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!