How to plot slope fields?

2 次查看(过去 30 天)
leonnn
leonnn 2015-12-1
回答: Jinal 2024-6-19
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.)

回答(1 个)

Jinal
Jinal 2024-6-19
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');

类别

Help CenterFile Exchange 中查找有关 Histograms 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by