# Save Multiple Matrices from For Loop

11 views (last 30 days)
Michelle De Luna on 11 Apr 2021
Commented: Michelle De Luna on 14 Apr 2021
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 CommentShowHide None
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.

Abhishek Gupta on 14 Apr 2021
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 CommentShowHide None
Michelle De Luna on 14 Apr 2021
Abhishek, I appreciate your response! Thank you for your help!