Error Message: expression or statement is incorrect

2 views (last 30 days)
I'm trying to create a code for least squares curve fitting, but when I make the function handle to be evaluated in the command window, I keep getting this error message saying that the the expression is incorrect. Below is the code I've made along with the inputs in the command window:
command window:
Running Least Squares Method...
X-Values: [0 10 20 30 40 50 60 70 80 90 100 110]
Y-Values: [3589 4132 6307 7814 11842 18072 27542 33141 44337 55002 65660 76201]
Function: (@K, r, timedat) ((popdat(1) * K ) / (popdat(1) + (K - popdat(1)*exp(-r * timedat))))
Error using LeastSqMethod (line 13)
Error: Expression or statement is incorrect--possibly unbalanced (,
{, or [.
Code:
clear
clc
%% Step 1 - Inputting Data
disp('Running Least Squares Method...');
disp(' ');
timedat = input('X-Values: '); % Array of X Values (Time)
popdat = input('Y-Values: '); % Array of F(x) Values (Population)
func = input('Function: '); % Function to be evaluated
x0 = input('Initial Guess: ');
%% Step 2 - Least Squares Fit Determination
fit = lsqcurvefit(func, x0, timedat, popdat)
%% Step 3 - Plotting Results
xrange = input('Enter X-Value Range: ');
plot(timedat,popdat,'ko',xrange,func(fit,xrange),'b-')
legend('Given Data', 'Model Fit')
xlabel('Time (Years)')
ylabel('Population')
title('Population Growth in Bryan, TX')
grid on

Accepted Answer

Guillaume
Guillaume on 15 Dec 2018
We're missing the most important part of your code, the function func that you pass to lsqcurvefit. Thankfully, it's in the error message.
The error is correct, the expression of func is incorrect. In particular, the opening bracket in the definition of the inputs should be after the @, not before, so:
func = @(K, r, timedat) ((popdat(1) * K ) / (popdat(1) + (K - popdat(1)*exp(-r * timedat))))
  4 Comments
Christopher
Christopher on 20 Dec 2018
Thank you very much for the input. My program was able to get to the plot, though it keeps running into this message: I
nitial point is a local minimum.
Optimization completed because the size of the gradient at the initial point
is less than the default value of the optimality tolerance.
<stopping criteria details>
and when it plots I just get a straight line instead of a fit. The logistic model I need to find K and r for is:
I can't get it to show well in Latex but that last term is e raised to the -rt.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!