Problem: fit function change the size of my "x" data-array.

3 views (last 30 days)
I've written the following fitting code to fit a sin curve function for different regions with different phase offset, while keeping a constan period frequency. My problem is that the fitting function changes the size of my x array to size (7), whereas I know that it has length(x)=4000;
Note: I put it all in a seperate function to clear up my main code.
function output=envelope_theory_fitting_Regionalized(x, signal)
% define anonymous function
interferometer_off_regionalfit=@(period,phase1,phase2,phase3,x) interferometer_off_regional(period,phase1,phase2,phase3,x);
% use the fitting function
output_region=fit(x,signal,interferometer_off_regionalfit,'Robust','Bisquare')%,'Lower',lb,'Upper',ub)
end
function output=interferometer_off_regional(period,phase1,phase2,phase3,x)
regions=[1,1901;1902,2307;2308,length(x)];
x1=x(regions(1,1):regions(1,2));
output1=(sin((period*x1+phase1)/2).^2);
x2=x(regions(2,1):regions(2,2));
output2=(sin((period*x2+phase2)/2).^2);
x3=x(regions(3,1):regions(3,2));
output3=(sin((period*x3+phase3)/2).^2);
output=[output1;output2;output3];
end
While stopping in debbuging mode within my fitting function I notice that length(x)=7
x=
0.1250
0.2500
0.3750
0.5000
0.6250
0.7500
0.8750
which is also the error that I retrieve in the console.
Error:Index exceeds the number of array elements (7).
Hope that anyone knows! or have encountered this problem.

Accepted Answer

Cris LaPierre
Cris LaPierre on 25 Oct 2021
Edited: Cris LaPierre on 26 Oct 2021
It appears the fit first performs a 'sanity check' of the input function using 7 values. If that passes, it then actually runs the fit on the actual input. Basically, fit was not designed to work with piecewise functions, which is essentially what you are trying to do.
I'm not sure if the results are meaningful, but one workaround is to write your code in a way that works for the sanity check as well as the actual data. Since we con't have your data, just be aware that this is untested.
output_region=fit(x,signal,@(period,phase1,phase2,phase3,x) interferometer_off_regional(period,phase1,phase2,phase3,x))%,'Lower',lb,'Upper',ub)
function output=interferometer_off_regional(period,phase1,phase2,phase3,x)
if length(x)==7
output = x;
else
regions=[1,1901;1902,2307;2308,length(x)];
x1=x(regions(1,1):regions(1,2));
output1=(sin((period*x1+phase1)/2).^2);
x2=x(regions(2,1):regions(2,2));
output2=(sin((period*x2+phase2)/2).^2);
x3=x(regions(3,1):regions(3,2));
output3=(sin((period*x3+phase3)/2).^2);
output=[output1;output2;output3];
end
end

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!