2
votes

This is a follow up question related to how to find out the scaling factors to match two curves in matlab? I use the following code to figure out the scaling factors to match two curves

function err = sqrError(coeffs, x1, y1, x2, y2)
   y2sampledInx1 = interp1(coeffs(1)*x2,y2,x1);
   err = sum((coeffs(2)*y2sampledInx1-y1).^2);
end

and I used fmincon to optimize the result.

options = optimset('Algorithm','active-set','MaxFunEvals',10000,'TolCon',1e-7)
A0(1)=1; A0(2)=1; LBA1=0.1; UBA1=5; LBA2=0.1; UBA2=5;
LB=[LBA1 LBA2]; UB=[UBA1 UBA2];
coeffs = fmincon(@(c) sqrError(c,x1, y1, x2, y2),A0,[],[],[],[],LB,UB,[],options);

when I test with my data with the function,

x1=[-0.3 -0.24 -0.18 -0.12 -0.06 0 0.06 0.12 0.18 0.24 0.3 0.36 0.42 0.48 0.54 0.6 0.66 0.72 0.78 0.84 0.9 0.96 1.02 1.08 1.14 1.2 1.26 1.32 1.38 1.44 1.5 1.56 1.62 1.68 1.74 1.8 1.86 1.92 1.98 2.04 ] y1=[0.00 0.00 0.00 0.01 0.03 0.09 0.13 0.14 0.14 0.16 0.20 0.22 0.26 0.34 0.41 0.52 0.62 0.72 0.81 0.91 0.95 0.99 0.98 0.96 0.90 0.82 0.74 0.66 0.58 0.52 0.47 0.40 0.36 0.32 0.27 0.22 0.19 0.15 0.12 0.10 ];

x2=[-0.3 -0.24 -0.18 -0.12 -0.06 0 0.06 0.12 0.18 0.24 0.3 0.36 0.42 0.48 0.54 0.6 0.66 0.72 0.78 0.84 0.9 0.96 1.02 1.08 1.14 1.2 1.26 1.32 1.38 1.44 1.5 1.56 1.62 1.68 1.74 1.8 1.86 1.92 1.98 2.04 ]; y2=[0.00 0.00 0.00 0.00 0.05 0.15 0.15 0.13 0.11 0.11 0.13 0.18 0.24 0.33 0.43 0.54 0.66 0.76 0.84 0.90 0.93 0.94 0.94 0.91 0.87 0.81 0.75 0.69 0.63 0.55 0.49 0.43 0.37 0.32 0.27 0.23 0.19 0.16 0.13 0.10 ];

The error message shows up as follows:

??? Error using ==> interp1 at 172 NaN is not an appropriate value for X.

Error in ==> sqrError at 2 y2sampledInx1 = interp1(coeffs(1)*x2,y2,x1);

Error in ==> @(c)sqrError(c,x1,y1,x2,y2)

Error in ==> nlconst at 805 f = feval(funfcn{3},x,varargin{:});

Error in ==> fmincon at 758 [X,FVAL,LAMBDA,EXITFLAG,OUTPUT,GRAD,HESSIAN]=...

Error in ==>coeffs = fmincon(@(c) sqrError(c,x1, y1, x2, y2),A0,[],[],[],[],LB,UB,[],options);

What is wrong in the code and how should I get around with it. Thanks for the help.

1

1 Answers

2
votes

Your scaling is likely pushing the interpolated axis out of range of the x-axis of the data. i.e.

x1 < min(x2*coeffs(1)) or x1 > max(x2*coeffs(1)) for at least one x1 and the value of coeffs(1) chosen by the fitting algorithm

You can fix this by giving an extrapolation value for data outside the range. Alternately, you can use extrapolation to guess at these values. So try one of these

y2sampledInx1 = interp1(coeffs(1)*x2,y2,x1,'Linear', 'Extrap');
y2sampledInx1 = interp1(coeffs(1)*x2,y2,x1,'Linear', Inf);
y2sampledInx1 = interp1(coeffs(1)*x2,y2,x1,'Linear', 1E18); %if Inf messes with the algorithm