Save Multiple Matrices from For Loop

조회 수: 13(최근 30일)
Michelle De Luna
Michelle De Luna 2021년 4월 11일
댓글: Michelle De Luna 2021년 4월 14일
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.
  댓글 수: 1
Michelle De Luna
Michelle De Luna 2021년 4월 14일
Abhishek, I appreciate your response! Thank you for your help!

댓글을 달려면 로그인하십시오.

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by