From: matlaberboy on
I have written some code to align two timeseries (I am using the matlab timeseries object), so regression and other cause-effect analysis can be carried out.

The problem is I have used a for loop. This is making the code very slow (given the timeseries are large, > 1e5 observations).

I have used the profiler and found a few ways to speed the code up. However, I suspect that the function could be written using logical indexing so that it is a lot quicker, and thus removing the need for the loop. Can anyone help with this?

I copy my two attempts at the code below and also the results from a profiler run:

cce_fit_A.m is faster than cce_fit_B.m

Many Thanks!

ts3 = cce_fit_A(ts1,ts2)
%% Are they already fitted?
if(isequal(ts1.time, ts2.time))
ts3 = ts1;
return;
end
time1 = get(ts1, 'time');
data1 = get(ts1, 'data');
time2 = get(ts2, 'time');
nLen = length(time2);
ts3Data = NaN(nLen,1);

for i = 1: nLen

idx = find(time1 <= time2(i), 1,'last');

if(isempty(idx))
ts3Data(i,1) = NaN;
else
ts3Data(i,1) = data1(idx);
end

clear idx;
end
ts3 = timeseries(ts3Data, time2, 'Name', ts1.name);
end


ts3 = cce_fit_B(ts1,ts2)
%% Are they already fitted?
if(isequal(ts1.time, ts2.time))
ts3 = ts1;
return;
end
time1 = get(ts1, 'time');
data1 = get(ts1, 'data');
time2 = get(ts2, 'time');
nLen = length(time2);
ts3DataB= NaN(nLen,1);

for i = 1: nLen

idx2 = data1(time1 <= time2(i));

if(isempty(idx2))
ts3DataB(i,1) = NaN;
else
ts3DataB(i,1) = idx2(end);
end

clear idx2;
end
ts3 = timeseries(ts3DataB, time2, 'Name', ts1.name);
end
From: Steven Lord on

"matlaberboy " <matlaberboy(a)gmail.NOSPAM.com> wrote in message
news:hrp507$ma1$1(a)fred.mathworks.com...
>I have written some code to align two timeseries (I am using the matlab
>timeseries object), so regression and other cause-effect analysis can be
>carried out.

If by "align" you mean interpolate so that they contain data at the same
times, take the UNION of the times and then use INTERP1.

--
Steve Lord
slord(a)mathworks.com
comp.soft-sys.matlab (CSSM) FAQ: http://matlabwiki.mathworks.com/MATLAB_FAQ


 | 
Pages: 1
Prev: model to M-file
Next: photovoltaic modelling