Load file with changeable variable
4 ビュー (過去 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 で Entering Commands についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!