Error using eval when load many files in recursive
7 次查看(过去 30 天)
显示 更早的评论
I want to load many files, i.e.
load('SST_mw_region6.mat','sst','time','lon','lat');
where "6" can be vary from 1 to 20
I did try using :
for k=1:20
eval(['load SST_mw_region' num2str(k) '.mat','sst','time','lon','lat';'])
end
I am not sure where I have to put ' ' and how many of them
Thanks
Dwi
0 个评论
回答(1 个)
Walter Roberson
2019-9-20
Don't use eval(). Construct your filenames using sprintf() and use the function form of load instead of the command form.
Note that when you do not assign the output of load() to a variable, that each iteration each of the variables you just loaded will be overwritten completely with the variables you just loaded.
4 个评论
Guillaume
2019-9-20
As Walter said, don't use eval. With eval you're effectively writing code that generates code. (one of) The (many) problem(s) is you can't easily tell what code is being generated and thus can't easily debug it. E.g. in your case, you're "not sure where I have to put ' ' and how many of them". You're giving yourself twice as much work to do. You have to make sure that your code generator is correct (the eval line) and that the generated code is correct (the stuff eval creates).
There are plenty of ways to construct file names (as per Walter's link). In your case, this should work:
numfiles = 20;
matdata = cell(1, numfiles); %preallocate cell array that stores the data from each matfile
for file = 1:numfiles
matdata{file} = load(sprintf(' SST_mw_region%d.mat', file), 'sst', 'time', 'long', 'lat');
end
%optional: since all cells will be scalar structures with the same fields
matdata = [matdata{:}]; %matdata will be a 1xnumfiles structure array.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!