Save Multiple Matrices from For Loop

10 次查看(过去 30 天)
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 个评论
David Fletcher
David Fletcher 2021-4-11
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.

请先登录,再进行评论。

采纳的回答

Abhishek Gupta
Abhishek Gupta 2021-4-14
Hi,
You can solve the issue as follows: -
Folder = 'C:\My\Folder\Here';
FileList = dir(fullfile(Folder, '*.nc'));
output = zeros(21,21,numel(FileList)); % initialize the 3D matrix to store 21x21 matrices
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)
z = ncread(file, 'QV', [548, 130, i, 1], [1, 21, 1, 1]);
qv = [qv; z]; %this produces the 21x21 matrix...
end
output(:,:,iFile) = qv; % store 21x21 matrix
end
Note: Instead of overwriting the 'qv,' use the output matrix to store the 21x21 matrix on every iteration.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Oil, Gas & Petrochemical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by