Appending multiple variables onto a single file
3 次查看(过去 30 天)
显示 更早的评论
Hey all! So I'm having a bit of an issue in saving variables onto a single file. I have a variable called 'map' which is the result of a piece of code that I run for one single file at a time. I want to combine all the 'map' variables for all the files that I'm using to give me an image as the final result. The input for the final result is as follows
figure; imagesc(mean(map,3)); axis image; colormap(1-gray(256))
What is the best way to combine one map variable from one file with another map variable from another file, so that I can get a combined image for the figure. Saving the variables to a single .mat file just seems to overwrite the previous 'map' variable. Thanks in advance! Also the 'map' variable is a 1069X1900 double.
0 个评论
采纳的回答
Walter Roberson
2021-5-14
dinfo = dir('*.mat');
filenames = {dinfo.name};
nfile = length(filenames);
hasmap = false(nfile,1);
for K = 1 : nfile
info = whos('-file', filenames{K}, 'map');
if ~isempty(info)
hasmap(K) = true;
end
end
filenames = filenames(hasmap);
nfiles = length(filenames);
allmap = [];
for K = 1 : nfiles
datastruct = load(filenames{K}, 'map');
thisdata = datastruct.map;
if K == 1
alldata = thisdata;
if nfiles > 1
alldata(end,end,nfiles) = 0;
end
else
alldata(:,:,K) = thisdata;
end
end
This code does not assume a particular size for the map variable, but it does assume that all of the map variables are the same size.
This code does not assume that all .mat files in the directory contain a map variable.
The purpose of the loop with whos is optimization: the code locates files that have the map variable and selects only those files, which gives you the count of files. Then when the first file is read in, the code takes the array of data and zero pads it out to the final size. This saves MATLAB from having to extend the array dynamically.
There are other ways of achieving the same efficiency.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Lighting, Transparency, and Shading 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!