Kuo-Hsien Chang
Kuo-Hsien Chang

Reputation: 935

Matlab : 3d matrix divided by 2d matrix

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) ;

Upvotes: 1

Views: 338

Answers (1)

Peter
Peter

Reputation: 14947

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);

Upvotes: 4

Related Questions