as building blocks for a vectorized implementation. And in some cases, functions such as movmean, which computes a moving windowed mean, provide exactly the calculation that's needed.
Still, some sequential operations cannot be vectorized, and some non-sequential operations involve a computation on each element that is so complicated that it is not convenient to vectorize it. In those cases, it may be necessary to do the calculation by looping over each element.
Under the hood, element-wise subscripting to access or assign to elements of a datetime array is more complex than the analogous subscripting on, for example, a numeric array. Therefore, in some cases, the performance of an element-wise loop over a datetime array will not be acceptable. Typically, these cases involve simple operations on each element. In those cases, it's possible to make a lossless conversion to a numeric type before the loop, use that in the loop body, and then convert back. This assumes that the element-wise operations are simple enough to be done with a raw numeric value.
One choice would be to use a Posix time representation:p1 = posixtime(d1);
for i = 1:length(p1)
p2(i) = ...
end
d2 = datetime(p2,'convertFrom','posixtime');
However, your first option for performance should always be to try to vectorize your code.