Concatenate multiple matrices by 3rd dimension using 'for' loop (considering a specific variable in netCDF files)

2 views (last 30 days)
Hi. I've got a series of netCDF files (250) each having several variables. I read each file and extracted 'lwe_thickness' variable from each file. It's a 360*180 matrix in each. My objective is to concatenate these matrices by 3rd dimension and get the mean matrix by element for 'lwe_thickness'. I tried the following loop considering just 4 files, but it does not concatenate by 3rd dim. Could anyone please help me find what's going wrong here. (It gives All_LWE = -0.0070 -0.0157 -0.0215 -0.0259 as the ans). (LWE is transposed to agree with [lon] & [lat] dimensions which is for later use)
-Thank you in advance-
Folder = 'C:\Users\Matlab1\ncfiles';
Patternoffiles = fullfile(Folder, '*.nc');
ncfiles = dir(Patternoffiles);
n = length(ncfiles);
for i = 1:n
filename = fullfile(ncfiles(i).folder, ncfiles(i).name);
ncdisp(filename);
LWE=ncread(filename,'lwe_thickness');
LWE=LWE';
All_LWE=cat(3,LWE(1:n))
end

Accepted Answer

KSSV
KSSV on 21 Oct 2022
Edited: KSSV on 21 Oct 2022
Folder = 'C:\Users\Matlab1\ncfiles';
Patternoffiles = fullfile(Folder, '*.nc');
ncfiles = dir(Patternoffiles);
n = length(ncfiles);
ALL_LWE = zeros(360,180,n) ; % preallocate/ initialize
for i = 1:n
filename = fullfile(ncfiles(i).folder, ncfiles(i).name);
ncdisp(filename);
LWE=ncread(filename,'lwe_thickness');
LWE=LWE';
All_LWE(:,:,i) = LWE ; % fill the matrix here
end

More Answers (0)

Categories

Find more on Agriculture 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!