I have two data sets and if I plot them then they appear like sin waves as you can see
I want to move one curve in order to overlap on other one. I want to using fminsearch to find a shift to minimize their difference. I have numerical data and I am not getting how to use fminsearch with available information.
Suppose you have two data sets as vectors of n
elements red
and blue
each is an n
-by-1 vector.
Then, given an integer shift delta
you can use circshift
to shift one of the signals:
shifted = circshift( red, delta );
Now you can use this to define your objective function in fminsearch
:
delta = fminsearch( @( x ) sum( ( blue(:) - circshift( red(:), round(x) ) ).^2 ), 20 );
Note that fminsearch
heavily depends on the initial value x0
, changing this value may have significant effect on the quality of the recovered delta
.
Here's an example
th = 0:.01:2*pi;
blue = sin( th ); % orig signal
green = sin( th + .5 ); % shifted signal
delta = fminsearch( @( x ) sum( ( blue(:) - circshift( green(:), round(x) ) ).^2 ), 20 );
% display results
figure;
plot( [blue;green]', 'LineWidth', 2 );
hold all;
plot( circshift( green(:), round(delta) ), '--r', 'LineWidth', 1.5 );
legend({'orig signal','shifted signal','after recovering \delta'});
The recovered value of delta
in this example is 50
,
and the output is