How to plot slope fields?
16 views (last 30 days)
Show older comments
Plot a line of slope f(t, y) at each point (t, y) in the grid defined by tspan, yspan and gridStep. In other words, make an array of t values from tspan(1) to tspan(2) and incremented by gridStep, and also an array of y values from yspan(1) to yspan(2) and incremented by gridStep, and plot a line of slope odefun(t(i),y(j)) at each point (t(i),y(j)). (Note that the line should have length at most equal to gridStep.)
0 Comments
Answers (1)
Jinal
on 19 Jun 2024
To implement your usecase, you can use nested loops to iterate over the t and y values and plot a line segment at each point.
Adding a sample code snippet below:
% Define the grid parameters
tspan = [0 1]; % Range of t values
yspan = [0 1]; % Range of y values
gridStep = 0.1; % Step size
% Define the function f(t, y)
odefun = @(t, y) t + y;
% Create arrays of t and y values
t = tspan(1):gridStep:tspan(2);
y = yspan(1):gridStep:yspan(2);
% Plot the lines of slope f(t, y)
hold on
for i = 1:length(t)
for j = 1:length(y)
slope = odefun(t(i), y(j));
line([t(i)-gridStep/2 t(i)+gridStep/2], [y(j)-gridStep/2*slope y(j)+gridStep/2*slope]);
end
end
hold off
% Set axis limits
xlim(tspan);
ylim(yspan);
% Add labels and title
xlabel('t');
ylabel('y');
0 Comments
See Also
Categories
Find more on Title in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!