How do I sum over one dimension of a multidimensional array?

88 vues (au cours des 30 derniers jours)
Nesha Wright
Nesha Wright le 21 Juin 2018
I have four dimensions in a netcdf file: lat, long, sector and time. I want to sum over JUST sector. Is there a simple command to do this?

Réponse acceptée

Adam Danz
Adam Danz le 21 Juin 2018
Modifié(e) : Adam Danz le 21 Juin 2018
Are you using ncread() or something similar to load the variable into the matlab workspace? If the variable is a matrix, you can use the 2nd input to sum() to sum across a specified dimension.
Example:
r = rand(5,4,3,2); %4D data
squeeze(sum(r,3)) %sums across the 3rd dim.
Squeeze() just removes the extra singleton dimensions.
  2 commentaires
Nesha Wright
Nesha Wright le 21 Juin 2018
I think this would work. Is there a way to tell what order the dimensions are in?
Walter Roberson
Walter Roberson le 21 Juin 2018
ncinfo can give you information about the order the variables are in the file. But be careful because nc files are "row major" instead of "column major" -- that is, the memory storage varies most quickly across rows instead of down columns. Because of this it is common that you need to use permute() on the result of ncread() to get the data order you expect. For example,
TheArray = permute(TheArray, [2 1 3 4]);
When you are working with ncf data sets it is useful to pay close attention to the array sizes you get back compared to the length of the marginal index, to determine whether your first two dimensions need to be exchanged or not.

Connectez-vous pour commenter.

Plus de réponses (1)

Juan Fernandez
Juan Fernandez le 21 Juin 2018
Yes, there is a simple single command. Use the sum(A,dim) function. If this is not working, then provide additional information and perhaps I can be of more assistance.
  5 commentaires
Adam Danz
Adam Danz le 24 Mar 2021
> if I wanted to sum, say, just the N first elements of the 3rd dimension, how would one go about that?
sum(x(:,:,1:N), 3)
Louis-Philippe Guinard
Louis-Philippe Guinard le 25 Mar 2021
I wasn't too far off, I did sum(x(:,:,1:N)) and returned a 1x256xN array. Aight thanks a lot! :)

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by