Hi @Hudson Harrell, from my understanding, you have three arrays named “Dforward”, “Dbackward”, and “Dcentral”, and you want to plot them against the “time” vector in a single plot.
To do this, we need to modify our “time” vector and create three different “time” vectors for each output array. These three “time” vectors will be the same length as the output arrays. Now, we can plot all these three vectors in a single plot since the length of each “time” vector is same as its corresponding output vector.
Below is the MATLAB code that addresses this task:
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]; % time
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]; % velocity
h = 20;
% Forward Difference
Dforward = zeros(1, length(t)-1);
for i = 1:length(t)-1
Dforward(i) = (v(i+1) - v(i)) / h;
end
t_forward = t(1:end-1); % Time vector for forward difference
% Backward Difference
Dbackward = zeros(1, length(t)-1);
for i = 2:length(t)
Dbackward(i-1) = (v(i) - v(i-1)) / h;
end
t_backward = t(2:end); % Time vector for backward difference
% Central Difference
Dcentral = zeros(1, length(t)-2);
for i = 2:length(t)-1
Dcentral(i-1) = (v(i+1) - v(i-1)) / (2*h);
end
t_central = t(2:end-1); % Time vector for central difference
% Plotting
figure;
hold on;
plot(t_forward, Dforward, 'r-', 'DisplayName', 'Forward Difference');
plot(t_backward, Dbackward, 'b-', 'DisplayName', 'Backward Difference');
plot(t_central, Dcentral, 'g-', 'DisplayName', 'Central Difference');
hold off;
xlabel('Time');
ylabel('Difference');
title('Difference Methods vs Time');
legend show;
grid on;
Attaching the documentation of plot function in MATLAB for reference:
I hope this resolves the issue.