how to make 3d array by stacking 2d arrays from sentinel 5p data?

I have 36 different netcdf files for one month. Every file contains an array of 215x3245 size. Now i want to make an 3d array of size 36x215x3245 using those 36 different files. I could not upload the files as those are really big files. I can provide the code for doing this thing :
files = dir('S5P_OFFL_L2__CH4____201901*.*');
for j = 1:36
hello(i,:,:) = ncread(files(i).name,'/PRODUCT/methane_mixing_ratio');
end
I have the file name type in the first line. Total 36 files are there with this name. Now in every file the variable '/PRODUCT/methane_mixing_ratio' has a size of 215x3245. Now I want to stack all these 36 files using loop. How can I do that? Thank you.

 Accepted Answer

You are looping over the wrong dimension in your code. You want something like this:
files = dir('S5P_OFFL_L2__CH4____201901*.*');
% Preallocate the large array
hello = zeros(215,3245,36);
% Fill in each "slice" along the 3rd dimension
for j = 1:36
hello(:,:,j) = ncread(files(i).name,'/PRODUCT/methane_mixing_ratio'); % Note that I shifted j to the third position
end

4 Comments

Thanks for your response. I have also done the above code and for checking I have copied your code. But I got an error, which I have got previously also. the error looks like below :
Unable to perform assignment because the size of the left side is 215-by-3245 and the size of the right side is
215-by-3246.
Error in jan_2019 (line 17)
hello(:,:,j) = ncread(files(j).name,'/PRODUCT/methane_mixing_ratio'); % Note that I shifted j to the third
position
I could not understand what was the problem. I have also attached the ss of my codes. Thank you.
It means that (at least) one of your files is not 215x3245, but is actually 215x3246.
You could display the value of j during each for loop, and see what value of j you get to before the error:
for j = 1:36
j
hello(:,:,j) = ncread(files(i).name,'/PRODUCT/methane_mixing_ratio'); % Note that I shifted j to the third position
end
There are also more sophisticated ways to debug, using the MATLAB debugger.
Thank you sir. You were right. The 8th file had a different dimension. One thing, can you give some way to recover from this situation?
Obviously, we cannot know why one of your input files has an extra column. That is something you'll need to figure out.
After you figure that out, it is easy to delete a single column from an array, if that is the solution:
% Define a random input
rng default
A = rand(4,3)
A = 4×3
0.8147 0.6324 0.9575 0.9058 0.0975 0.9649 0.1270 0.2785 0.1576 0.9134 0.5469 0.9706
% Delete the 2nd column:
A(:,2) = []
A = 4×2
0.8147 0.9575 0.9058 0.9649 0.1270 0.1576 0.9134 0.9706

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!