index exceeds the number of array elements?

1 view (last 30 days)
i keep getting the "index exceeds the number of array elements" error on my code it worked fine when i set the step size to 40 but when i change it to 20 i get the error.
close all
clear all
clc
X=0:20:520;
F=[0 139 298 433 685 1026 1279 1373 1490 1634 1800 1986 2417 2651 2915 3303 3516 3860 4216 4630 5092 5612 6184 6760 7327 7581];
h=X(2)-X(1);
n=length(X);
xForward=X(1:n-1);
dFForward=(F(2:n)-F(1:n-1))/h;
xBackward=X(2:end);
dFBackward=(F(2:n)-F(1:n-1))/h;
xCenteral=X (2:n-1);
dFCentral=(F(3:n)-F(1:n-2))/(2*h);
hold all
figure(1);plot (xCenteral,dFCentral,'r' )
figure(1);plot (xForward,dFForward, 'k')
figure(1);plot (xBackward,dFBackward,'g')
legend ('centeral','Forward','Backward')
title('NUMERICAL DIFFERENCING USING STEP SIZE 20s')
xlabel ('Time')
ylabel ('Acceleration')
grid
clear;
clear;
  2 Comments
Yazan
Yazan on 11 Aug 2021
The number of elements in the vector F is one less than that of the vector X. Fix that.
jacob booth
jacob booth on 11 Aug 2021
thanks i had just skiped a number when inputing them

Sign in to comment.

Accepted Answer

Dave B
Dave B on 11 Aug 2021
Edited: Dave B on 11 Aug 2021
The line of code: dFForward=(F(2:n)-F(1:n-1))/h; looks for F ranging from 2:n. n is 27, length(F) is 26. You've requested the 27th element of a 26 element array.
X=0:20:520;
F=[0 139 298 433 685 1026 1279 1373 1490 1634 1800 1986 2417 2651 2915 3303 3516 3860 4216 4630 5092 5612 6184 6760 7327 7581];
n=length(X)
n = 27
disp(length(F))
26

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!