MATLAB: Help!!! I keep getting error message “Array indices must be positive integers or logical values.”

arrayfor loop

Hi this is my code for calcualting the forward difference of the following array.
t= [0 20 40 60 80 100 120 140 160 180 200 220 240 260 280 300 320 340 360 380 400 420 440 460 480 500 520];
v= [0 139 298 433 685 1026 1279 1373 1490 1634 1800 1986 2191 2417 2651 2915 3303 3516 3860 4216 4630 5092 5612 6184 6760 7327 7581];
h=20;
for i = 1:length(t);
Dforward(i)= v(t(i)+h)-v(t(i))/h;
end
I believe my problem is the code keeps calcualting beyond the boundries of my array, and I'm not sure what todo to fix it. Please any advice would be great

Best Answer

Perhaps you mean this:
t = [0 20 40 60 80 100 120 140 160 180 200 220 240 260 280 300 320 340 360 380 400 420 440 460 480 500 520];
v = [0 139 298 433 685 1026 1279 1373 1490 1634 1800 1986 2191 2417 2651 2915 3303 3516 3860 4216 4630 5092 5612 6184 6760 7327 7581];
for k = 1 : length(t) - 1
h = t(k + 1) - t(k);
Dforward(k)= (v(k+1) - v(k)) / h;
end
% Plot original signal
subplot(2, 1, 1);
plot(t, v, 'b.-', 'MarkerSize', 30, 'LineWidth', 2);
grid on
xlabel('t', 'FontSize', 20);
ylabel('v', 'FontSize', 20);
title('v vs. t', 'FontSize', 20);
% Plot Dforward.
subplot(2, 1, 2);
plot(t(1:end-1), Dforward, 'b.-', 'MarkerSize', 30, 'LineWidth', 2);
grid on
xlabel('t', 'FontSize', 20);
ylabel('Dforward', 'FontSize', 20);
title('Dforward vs. t', 'FontSize', 20);