Load file with changeable variable
    4 views (last 30 days)
  
       Show older comments
    
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 Comment
  Stephen23
      
      
 on 26 Apr 2017
				
      Edited: Stephen23
      
      
 on 26 Apr 2017
  
			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:
Accepted Answer
  Stephen23
      
      
 on 26 Apr 2017
        
      Edited: Stephen23
      
      
 on 26 Apr 2017
  
      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 Comments
More Answers (1)
  Geoff Hayes
      
      
 on 26 Apr 2017
        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 Comments
See Also
Categories
				Find more on Entering Commands in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

