Q:

Find distance of one graph from another in matlab

I have two curves in Matlab.
Curve A:
x1 = [128 192   256 384 512 704 1024 1472 2048 2880 4096 5824 8192 11584 16384 23168];
y1 = [0.62 0.51 0.43 0.35 0.3 0.26 0.22 0.18 0.15 0.13 0.11 0.09 0.08 0.06 0.05 0.05];

Curve B:
x2 = [16 24 32 48 64 88 128 184 256 360 512 728 1024 1448 2048 2896];
y2 = [1.94 1.54 1.33 1.15 0.97 0.86 0.71 0.59 0.5 0.42 0.36 0.3 0.25 0.21 0.18 0.15];

After drawing both curves (x-axis exponentially) in the same plot:
semilogx(x1,y1,'-o')
hold on
semilogx(x2,y2,'-o')

I have found that B curve is above A curve. But I want to shift B to the left so that B curve overlaps A curve. So the question is, what amount (right to left) I need to shift B curve to overlap A curve?
Some clue: Maybe need to count the vertical distance (for all match points) from B to A (interpolation) and square the distance and sum them all up and find the value of Alpha. How can I do it in Matlab?

A:

We can find the desired shift by first finding what values of x2 would move the curve B exactly on top of curve A. This can be achieved by resampling curve A at points corresponding to the y-coordinates of the points in curve B. The following code illustrates this.
Since you plot the x-axis in log-domain, I assume that you want to shift log10(x2). So the x-points on your shifted curve be will be log10(x2) + shift instead of log10(x2 + shift).
% find the subset of y2 which is within the range of y1
idxCommonB = find((y2 <= max(y1)) & (y2 >= min(y1)));
y2c = y2(idxCommonB);
x2c = x2(idxCommonB);

% for each point on curve B, find a new x2 that would move the point on
% curve A
% We use interp1 function for resample the curve. This function requires
% all the points in the domain to be unique. So find the unique elements in
% y1.
[y1_unique,iUnique] = unique(y1);
x2c_desired = interp1(y1_unique, x1(iUnique), y2c, 'linear');

% find the average distance between the desired and given curves
x2_logshift = mean(log10(x2c_desired) - log10(x2c));

% Display the result
fprintf('Required shift in log10(x2) is %f.\n', x2_logshift);
% Required shift in log10(x2) is -0.126954.    

% plot to verify the estimate
figure;
plot(log10(x1),y1,'-o')
hold on
plot(log10(x2),y2,'-o')
plot(log10(x2)+x2_logshift,y2,':*')
grid on;
legend({'A', 'B', 'Shifted B'});
set(gca, 'FontSize', 12);

