Regression fit a inverse cos wave into a dataset

2 views (last 30 days)
Hi, I have a datset of a scatter plot (as shown below) which is supposed to resemble a tuning curve. I want to fit an inverse cosine curve onto this dataset . My x variable are angles range [0,360] with size 2154x1 double and my y variable is frequency of size 2154x1 double. Part of the values of my y variable can be seen here:
I know there are some answers on the forum and I have tried the following code attempting to customise it slightly to my needs, however I constantly am getting the error and not be able to see any curves on my scatter plot:
"Exiting: Maximum number of iterations has been exceeded
- increase MaxIter option.
Current function value: NaN "
I tried fixing the error using this line of code i found on the forum but I am still not able to see any curve:
options = optimset('MaxFunEvals',1000);
[p,fminres] = fminsearch(fun,pguess,options)
The code I have been referencing for this task is here:
yu = max(y);
yl = min(y);
yr = (yu-yl); % Range of ‘y’
yz = y-yu+(yr/2);
zx = x(yz(:) .* circshift(yz(:),[1 0]) <= 0); % Find zero-crossings
per = 2*mean(diff(zx)); % Estimate period
ym = mean(y); % Estimate offset
fit = @(b,x) b(1).*(sin(2*x./b(2) + 2*pi/b(3))) + b(4); % Function to fit
fcn = @(b) sum((fit(b,x) - y).^2); % Least-Squares cost function
s = fminsearch(fcn, [yr; per; -1; ym]); % Minimise Least-Squares
xp = linspace(min(x),max(x));
plot(xp,fit(s,xp), 'r')
hold on
scatter(x,y, 'b')
hold off
grid
I am really new to matlab so apologies if i have asked the question incorrectly

Answers (1)

Milan Bansal
Milan Bansal on 29 Sep 2023
Hi,
As per my understanding you are facing an error while trying to fit an inverse cosine wave to your dataset.
The given error occurs when the maximum iteration allowed in "fminsearch" are exceeded. Set the value of "MaxIter" and "MaxFunEvals" in the optimization options for "fminsearch" function as shown in the code below to resolve the issue.
options = optimset('MaxFunEvals', 1E7, 'MaxIter', 1E7);
Refer to the below MathWorks documentation link to learn more about setting optimization options in "fminsearch".
Refer to the MathWorks documentation link to learn more about "fminsearch" function.
Hope it helps!

Categories

Find more on Get Started with Curve Fitting Toolbox in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!