Save Multiple Matrices from For Loop

12 ビュー (過去 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 件)

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by