필터 지우기
필터 지우기

Load file with changeable variable

조회 수: 1 (최근 30일)
J. Olondriz
J. Olondriz 2017년 4월 26일
편집: Stephen23 2017년 4월 26일
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
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
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:

추가 답변 (1개)

Geoff Hayes
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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by