Attempted to access a(3); index out of bounds because numel(a)=2.

1 view (last 30 days)
I try to use fminsearch to solve for coefficients of the equation below: accelerate = A*exp(B*time)*cos(C*time+D), and I get this error:
Attempted to access a(3); index out of bounds because numel(a)=2. Any one know why? help is much appreciated.
data = load('project3_accel.dat')
t = data(1:end,1);
a = data(1:end,2);
model = @(t,A,B,C,D)A.*exp(B*t).*cos(C*t+D)
fun = @(r,ti,ai) sum((ai-model(ti,r(1),r(2),r(3),r(4))).^2);
options = optimset('TolX',1e-8,'TolFun',1e-8);
r = fminsearch(fun,[-50,50],options,t,a);
A = r(1);
B = r(2);
C = r(3);
D = r(4);
St = sum((a-mean(a)).^2);
Sr = sum((a-model(t,A,B,C,D)).^2);
r_squared2 = 1-Sr/St

Accepted Answer

Star Strider
Star Strider on 28 Feb 2015
You will have to change parts of your code to accommodate this change, but this should work:
% b(1) = A, b(2) = B, b(3) = C, b(4) = D
model = @(b,t) b(1).*exp(b(2).*t).*cos(b(3).*t+b(4));
fun = @(b) sum((ai-model(b,t)).^2);
and:
b0 = [-50 0.5 0.5 50]; % Choose Good Starting Values For All 4 Parameters
r = fminsearch(fun, b0, options);
  2 Comments
Jack13
Jack13 on 28 Feb 2015
Thanks, my problem is not providing enough initial guesses.
Star Strider
Star Strider on 28 Feb 2015
My pleasure.
It was a bit more involved than that. The curve fitting functions have to have a single vector of parameters to estimate. You have to provide as many initial guesses as you have parameters to be estimated. (I consider the start values as initial parameter estimates.)
I didn’t test the code I posted because I didn’t have your data to test it on.

Sign in to comment.

More Answers (0)

Categories

Find more on Conditional Mean Models 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!