Question

I have a 4-d matrix (time, one_variable, Y_location, X_location) in Matlab.

Here is the 4-d matrix looks like:

>> size (npp_data_pft1)
ans =
100     1   289   570

100 means 100 timesteps; 1 means only 1 variable here; 289 and 570 are the y and x gridded cell indices.

How to get a mean value in a specific region?

For example, I like to get a mean value in timestep 1 within a region at 33 < Y_location < 47 and 112 < X_location < 176.

Was it helpful?

Solution 2

Here's the trick:

M = npp_data_pft1(:, 1, 33:47, 112:176);
mean(reshape(M,[],size(M,3)*size(M,4))');

In this example the answer will output values each with the mean of the region you selected per frame. I reshaped the 4D matrix to a 2D one. That matrix has 100 lines (total # of frames) and 975 columns (total # of pixels in the selected region). Then just using mean on that 2D matrix will yield the mean value of the entire region per frame. (I used ' to get the mean working in the right dimension, instead you can use mean(...,2))

OTHER TIPS

One way to do it is to extract your region and then take the mean.

A = npp_data_pft1(1, 1, 33:47, 112:176);
mean(A(:))    % returns scalar value

I assume you want to do the average for more than one time value. In that case I suggest the following, where 1:20 represents the range of time values you want to observe:

mean(mean(npp_data_pft1(1:20, 1, 33:47, 112:176),3),4);

This gives a 20x1 vector with the desired averages.

Note that the second argument of mean indicates along which dimension the average is computed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top