Question

I have a 4d matrix (time-by-group-by-latitude-by-longitude) in MATLAB needs to be divided by a summed value from all groups in a 3d matrix (time-by-latitude-by-longitude) over a period of time. I would like to have a 4d matrix, presenting the fraction valve for each group in a 4d matrix (time-by-group-by-latitude-by-longitude) How can I do this?

For example (netcdf file):

short npp(time, pft, latitude, longitude) ;
short npptot(time, latitude, longitude) ;

I like to do this calculation:

fraction = npp ./ npptot

The results should be in a 4d matrix, time-by-group-by-latitude-by-longitude.

short fraction(time, pft, latitude, longitude) ;
Was it helpful?

Solution

bsxfun is for just this sort of dimension expansion. The trick is that the dimensions need to match exactly, except for the dimensions you want to expand. This means your 3d matrix needs to be instead a 4d time x 1 x lat x lon matrix:

npptot_reshaped = reshape(npptot, [size(npptot,1) 1 size(npptot,2) size(npptot,3)]);
fraction = bsxfun(@rdivide, npp, npptot_reshaped);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top