How can I calculate an average for a given time period?

10 views (last 30 days)
I’m trying to calculate the mean tidal depth for a given time period (the example below is for 1436h-1509h on March 9, 2012). The tidal data that I have are at 5 minute intervals, so I’m using ‘>=’ and ‘<=’ to define the time interval for which I’d like the average depth:
tideHeight=mean(Depth(MATLABdate >= datenum(2012,03,09,14,36,0):MATLABdate <= datenum(2012,03,09,15,09,0)))
I’m getting the following error: ‘Error using >= ...Matrix dimensions must agree.’

Accepted Answer

Jan
Jan on 7 Apr 2014
Edited: Jan on 7 Apr 2014
What do you assume as output of this expression:
MATLABdate >= datenum(2012,03,09,14,36,0):MATLABdate <= datenum(2012,03,09,15,09,0)
1. Is MATLABdate >= datenum(2012,03,09,14,36,0) calculated at first, and then MATLABdate <= datenum(2012,03,09,15,09,0). And afterwards you get the colon operator for both results?
2. Is datenum(2012,03,09,14,36,0):MATLABdate evaluated as vector at first, than MATLABdate >= ... and finally the resulting logical vector used for ... <= datenum(2012,03,09,15,09,0)
Both would not satisfy your needs. You want:
ini = (MATLABdate >= datenum(2012,03,09,14,36,0));
fin = (MATLABdate <= datenum(2012,03,09,15,09,0));
tideHeight = mean(Depth(ini & fin));
Here distributed over 3 lines of code to improve the readability and avoid confusion with the operator precedence.
Another idea would be:
index1 = find(ini, 1, 'first');
index2 = find(fin, 1, 'last');
tideHeight = mean(Depth(index1:index2));
But this is less efficient.

More Answers (1)

Rebecca
Rebecca on 7 Apr 2014
Edited: Rebecca on 7 Apr 2014
That worked - thank you!
A question about the code: does the '&' symbol in tideHeight = mean(Depth(ini & fin)) indicate that it's everything from ini through to fin? That's what I was trying to use the : operator for, which is where I think I went wrong.
Also, I need to do this for dozens of different time periods. Is there a way to automate it so that I don't have to manually enter the ini and fin values every time? For example, can I make a table with the first column being ini values and the second column fin values and read that in somehow?
Thank you for your help!

Categories

Find more on Dates and Time 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!