Just need some help plotting
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Hi, I'm trying to plot the solutions to the Forward Difference, Backward Difference, and Central difference vs time on a single plot.
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
for i = 1 : length(t)-1
Dforward(i)= (v(i+1)-v(i))/h;
end
% Backward Difference
for i=2: length(t)
Dbackward(i)= (v(i)-v(i-1))/h;
end
% Central Difference
for i= 2 : length(t)-1
Dcentral(i)= (v(i+1)-v(i-1))/(2*h);
end
This is my base code with no plotting code. I've tried different methods to plot but I run into a problem that since the length of the vectors are different for each difference it won't plot on one plot. So any suggestions or advice would be cool.
0 Commenti
Risposte (1)
Deepak
il 26 Ago 2024
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.
0 Commenti
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!