1

I have two data sets and if I plot them then they appear like sin waves as you can see below

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.

User1551892
  • 3,236
  • 8
  • 32
  • 52

1 Answers1

1

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
enter image description here

Shai
  • 111,146
  • 38
  • 238
  • 371
  • I have a comment about this line ( plot( circshift( green(:), round(delta) ), '--r', 'LineWidth', 1.5 );) – User1551892 Jul 16 '14 at 10:09
  • 1
    @User1551892 what is your comment? – Shai Jul 16 '14 at 10:31
  • sorry, I thought that I did not submit my commit somehow I did it. you are not using the original x-axis values and due to which both curves are 100% overlapping. However, if you use the fixed x-axis then parts of curves will not overlap. Its plotting related issue. Thanks a lot for explaining the solution in a nice way. I was confused how to use numeric values in fminsearch function. – User1551892 Jul 16 '14 at 22:58