How to plot slope fields?
古いコメントを表示
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 件)
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');
カテゴリ
ヘルプ センター および File Exchange で Line Plots についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
