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에서 Title에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by