function val = timeidx(varargin)
%TIMEIDX returns numeric index given time string.
% D = TIMEIDX(T) returns index value in relative days which is suitable for
% DATENUM math. To work in hours multiply by 24, for seconds multiply
% by 24*3600, etc. T can be a time string (DD:HH:MM:SS) where DD, HH
% and MM are incrementally optional and SS can include a decimal
% fraction. For multiple time values T must be a cell array of strings.
% The result is the same size/shape but type DOUBLE.
%
% D = TIMEIDX(T1,T2) returns a range of values. T1 and T2 are individual
% time strings (as above) and the result is a 1x2 DOUBLE array.
%
% N = TIMEIDX(...,FS) instead returns index values in sample units relative
% to the beginning of a record where FS is samples/second. Sample
% values are rounded to integer values. Time 0 corresponds to sample 1.
%
%Example 1: operation times out after 5 minutes
% t2 = now+timeidx('5:00')*24*3600;
% while ~done && now<t2
% %wait for something else to happen
% end
% if ~done
% error('Operation failed to complete in 5 minutes')
% end
%
%Example 2: specify portion of WAV file to read
% range = timeidx('2.5','1:02.5',Fs); %1 minute after 2.5 second delay
% x = wavread('myfile.wav',range);
%
%See also DATENUM, DATESTR
% Copyright 2008-2010 The MathWorks, Inc.
%defensive programming
error(nargchk(1,3,nargin))
error(nargoutchk(0,1,nargout))
[timeString,Fs] = ParseInputs(varargin{:});
%convert time string(s) to datenum value(s)
if iscell(timeString) %array
val = zeros(size(timeString));
for k=1:numel(timeString) %each time
val(k) = StringToDays(timeString{k});
end
else %scalar
val = StringToDays(timeString);
end
%optionally convert datenums to sample indices
if ~isempty(Fs) %Fs specified
val = round(val*(24*60*60)*Fs)+1;
end
%----------------------------------------------------------------------
function timeVal = StringToDays(timeString)
multipliers = [1 60 60^2 24*60^2]./(24*60^2); %SS MM HH DD
parts = fliplr(regexp(timeString,':','split')); %SS MM HH DD
if numel(parts)>numel(multipliers)
error('Too many parts')
end
timeVal = 0;
for k=1:numel(parts)
timeVal = timeVal + str2double(parts{k})*multipliers(k);
end
%----------------------------------------------------------------------
function [t,Fs] = ParseInputs(varargin)
t = varargin{1}; %arg1 must be T1
if nargin>1 %arg2 could be T2 or FS
if isa(varargin{2},'double')
Fs = varargin{2};
elseif isa(varargin{2},'char')
t = varargin(1:2);
else %logic flaw
error(['Expected DOUBLE or CHAR not ',upper(class(varargin{2}))])
end
end
if nargin>2 %arg3 must be FS
if isa(varargin{3},'double')
Fs = varargin{3};
else %logic flaw
error(['Expected DOUBLE not ',upper(class(varargin{2}))])
end
end
if ~exist('Fs','var')
Fs = '';
end