Search code examples
matlabcycle

Index out of bounds (MATLAB)


Iam trying to get the value for p(4) (sorry for this)

The equation is looking like this: 4800+p1+p2*z/1000+p3*e^(-p4*z/1000)

I keep getting this error: Attempted to access p(4); index out of bounds because numel(p)=3.

Error in waves (line 32) xy1 = 4800+5.6596+14.5820/1000*xs+257.4318*exp(-p(4)/1000);

How can i change the "bounds" in numel or is there any else i can do to fix this problem?

The code

z = [0.0; 500; 1000; 1500; 2000; 2500; 3000; 3500; 4000; 5000; 6000; 7000; 8000; 9000; 10000; 11000; 12000];
y = [5050 4980 4930 4890 4870 4865 4860 4860 4865 4875 4885 4905 4920 4935 4950 4970 4990]'-4800 ;
A = [ones(numel(z),1) z./1000 exp(-z./1000)];
p = A\y;
norm(p);
y = y+4800;

xs = 0:1:12000;
xy = 4800+5.6596+14.5820/1000*xs+257.4318*exp(-p(4)/1000);
subplot(2,2,4), plot(z,y,'o')
hold on
subplot(2,2,4), plot(xs,xy);
title('p4')

Edit:::::::

I had this first, where p4 had a start guess(value) (p4=1), i then put the p1,p2,p3 results in a new file to try to solve p4, thats the code above.

z = [0.0; 500; 1000; 1500; 2000; 2500; 3000; 3500; 4000; 5000; 6000; 7000; 8000; 9000; 10000; 11000; 12000];
y = [5050 4980 4930 4890 4870 4865 4860 4860 4865 4875 4885 4905 4920 4935 4950 4970 4990]'-4800 ;
A = [ones(numel(z),1) z./1000 exp(-z./1000)];
p = A\y;
norm(p);
y = y+4800;

xs = 0:1:12000;
xy = 4800+p(1)+p(2)/1000*xs+p(3)*exp(-xs/1000);
subplot(2,2,1), plot(z,y,'o')
hold on
subplot(2,2,1), plot(xs,xy);
title('p1,p2,p3')

Solution

  • Armed with the knowledge that you are trying to fit the model described here:

    https://math.stackexchange.com/questions/214797/soundwaves-under-the-water

    i.e. f(z) = 4800 + p1 + p2*z/1000 + p3*exp(-z*p4/1000)

    The problem is this it is a non linear equation, so you cannot simply use the MATLAB backslash operator. You will need to do what the answer suggests and look into using lsqnonlin in optimzation toolbox or fit a custom equation in Curve Fitting Toolbox.

    Personally, I am biased towards Curve Fitting Toolbox, and I would do the following with cftool:

    enter image description here

    Here we can see that the coefficient estimates are:

       p1 =      -20.21  (-29.34, -11.08)
       p2 =       17.34  (16.31, 18.36)
       p3 =       272.9  (263.3, 282.5)
       p4 =      0.7528  (0.6964, 0.8092)
    

    Bear in mind that I have quite loose lower and upper bounds. If you wanted to make sure that p1 was always positive, you could do that by setting the lower bound to zero.