Save Multiple Matrices from For Loop
Show older comments
Good afternoon!
I'm currently working on reading through various levels of a group of .nc files. Every time I read through the levels of an individual .nc file, I produce a 21x21 matrix representing the data values at 21 different latitudes and 21 different levels. Ideally, I would like to save each of my matrices from each of my .nc files separately so that I may then perform separate calculations on each of them. However, I am having trouble doing so. I've played around with my code for a couple of hours, but I can't seem to get it to work like I'd like it to. Any recommendations? Here's what I have so far...
Folder = 'C:\My\Folder\Here'
FileList = dir(fullfile(Folder, '*.nc'))
for iFile = 1:numel(FileList)
file = fullfile(FileList(iFile).folder, FileList(iFile).name)
latitude = ncread(file, 'lat');
longitude = ncread(file, 'lon');
time = ncread(file, 'time');
level = ncread(file, 'lev')
qv = []
for i = 1:numel(level)
i
z = ncread(file, 'QV', [548, 130, i, 1], [1, 21, 1, 1])
qv = [qv; z] %this produces the 21x21 matrix...
end
qv(:,:,iFile) = qv %this is where I am hoping to save each of my matrices separately..
end
1 Comment
David Fletcher
on 11 Apr 2021
This seems to be a common problem tonight - is there a full moon? This line in the iFile loop
qv = []
is going to overwrite the location you are trying to store your matrices with nothing on every iteration
qv(:,:,iFile) = qv
So you read your data, put it into a store, go to the next iteration, overwrite your store with nothing, read your data, put it into the store, etc.
Accepted Answer
More Answers (0)
Categories
Find more on Cell Arrays 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!