Append data to 3rd dimension in loop

15 Ansichten (letzte 30 Tage)
Elin Jacobs
Elin Jacobs am 28 Sep. 2022
Kommentiert: Elin Jacobs am 28 Sep. 2022
I have 68 4320x2160x24 files that I use a for loop to read in and perform some tasks on, then I iteratively store output in a new variable. Towards the end of the script, I want to iteratively store the 4320x2160x12 matrix ndvi_mmax into a 4320x2160x(12*68) matrix (NDVI_monthmax). My current attempts have failed, I'm notsure whther I need to create a 4D matrix or if I need another, nested, loop, or convert to a cell. Any help appreciated.
startyear = 1982;
endyear = 2015;
nyears = length(startyear:endyear);
nmonths = nyears*12;
%Preallocate variables for output file
NDVI_mean = zeros(4320,2160,nyears); % mean annual NDVI
NDVI_monthmax = zeros(4320,2160,nmonths); % highest monthly mean NDVI
MD = zeros(4320,2160,nyears); % # of missing datapoints each year
%load data and define variables
for i = 1:nyears
yr = (startyear-1)+i;
filename1 = sprintf('ndvi3g_geo_v1_%d_0106.nc4', yr);
filename2 = sprintf('ndvi3g_geo_v1_%d_0712.nc4', yr);
fullFileName1 = fullfile(myFolder, filename1);
fullFileName2 = fullfile(myFolder, filename2);
ncid1 = netcdf.open(fullFileName1);
ncid2 = netcdf.open(fullFileName2);
%disp(filename1)
%ncdisp(fullFilename1)
NDVI1 = ncread(fullFileName1, 'ndvi');
NDVI2 = ncread(fullFileName2, 'ndvi');
flag1 = ncread(fullFileName1, 'percentile');
flag2 = ncread(fullFileName2, 'percentile');
NDVI = cat(3,NDVI1,NDVI2);
NDVI = double(NDVI);
NDVI(NDVI == -32768) = NaN;
NDVI(NDVI == -5000) = NaN;
NDVI = NDVI/10000; % scaling factor
flag = cat(3,flag1,flag2);
NDVI(flag >= 4000) = NaN; %remove snow/cloud flagged pixels
latitude = ncread(fullFileName1, 'lat');
longitude = ncread(fullFileName1, 'lon');
md = sum(isnan(NDVI),3);
ndvi_mean = nanmean(NDVI,3);
ndvi_monthmax = max(reshape(NDVI,4320,2160,2,12),3); % max NDVI each month
ndvi_monthmax(:,:,2:end,:) = [];
ndvi_mmax = squeeze(ndvi_monthmax); % remove 3rd dimension
%HERE'S WHERE I RUN INTO PROBLEMS:
NDVI_monthmax(:,:,12) = ndvi_mmax;
%THIS WORKS FINE:
NDVI_mean(:,:,i) = ndvi_mean;
MD(:,:,i) = md;
end

Akzeptierte Antwort

Kevin Holly
Kevin Holly am 28 Sep. 2022
Assuming you have 68 files that are distinguished based on the year and the above is only looking at 33 of the files/years.
3D - 4320x2160x(12*68)
NDVI_monthmax(:,:,(i-1)*12:(i-1)*12+12) = ndvi_mmax;
or 4D - 4320x2160x12x68
NDVI_monthmax(:,:,:,i) = ndvi_mmax;
  2 Kommentare
Kevin Holly
Kevin Holly am 28 Sep. 2022
Or if you just want to append:
NDVI_monthmax = [NDVI_monthmax; ndvi_mmax];
Be sure to write the following command before your for loop:
NDVI_monthmax = [];
Elin Jacobs
Elin Jacobs am 28 Sep. 2022
Works great, thank you!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by