Clear Filters
Clear Filters

Creating variable averaged over two strata

2 views (last 30 days)
Hi there,
I have a two long variables (+40,000 measures) of doubles x & y and i would like to calculate a third variable from them z. However X and Y are measured over time and at various depths in the ocean, not always at the same exact depths so in order to calculate my z variable i need to do some matlab wizardry?? (I have the date in every format under the sun and also separate variable for the year,month and day seperately)
I would like a code that calculates monthly averages at certain depths.
For example to go from a matrix of [date, x, y, depth] which contain various NaNs to one which has 1:20:4000 depth in the first column repeated for every month (total of 350 months in my data set) and then corresponding monthly average for x and y.
Thank you for any help with this in advance

Accepted Answer

Mohammad Abouali
Mohammad Abouali on 1 Mar 2016
Edited: Mohammad Abouali on 2 Mar 2016
first convert your date so that you get year and month separately. If you have the date as a string you can use datevec() command as follows:
dateVector = datevec(dateStr);
year = dateVector(:,1);
month = dateVector(:,2);
then you can use grpstats(). I suggest to create a table first, but you can also use a regular array.
dataTBL = table();
dataTBL.Year= year;
dataTBL.month= month;
dataTBL.depth = depth;
dataTBL.x = x;
dataTBL.y = y;
monthlyMean = grpstats(dataTBL, {'year',month','depth'},{@(c) (nanmean(c(:)))})
If you upload a sample data we can be of more help.
aaron Harvey
aaron Harvey on 1 Mar 2016
Thank-you, a very quick reply and it has helped me sort this out. However i now have a the probablem of multiplying by NaN in my data. How can i multiply two vectors containin NaN's such that.
a=[1 2 3 NaN 2 3]'
b=[3 2 NaN 2 1 5]'
a*b=[3 4 NaN NaN 2 15]'
Mohammad Abouali
Mohammad Abouali on 2 Mar 2016
Edited: Mohammad Abouali on 2 Mar 2016
I am not sure what you are asking. If you are trying to multiply two vectors element by element you need to use .* instead of * (pay attention to the dot before *).
So it would be something like this
a=[1 2 3 NaN 2 3]'
b=[3 2 NaN 2 1 5]'
ans =
If one of the element is NaN, then the multiplication results would be NaN.
Since you mentinoed your data has some NaN, earlier I suggested using nanmean instead of mean.

Sign in to comment.

More Answers (0)


Find more on Shifting and Sorting Matrices in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!