How do I construct matrices of multiple variables and plot a graph

1 回表示 (過去 30 日間)
Alfred
Alfred 2024 年 7 月 23 日
コメント済み: Alfred 2024 年 7 月 25 日
I am a beginner to MATLAB.
I tried but I'm getting errors.
Anybody, kindly help. Thank you.
Equations dx/dt=-2x
dy/dt=2x
Initial condition: x(t=0)=100
y(t=0)=0
tspan=[0 3];
x0=100;
y0=0;
dzdt = (dxdt dydt);
Invalid expression. Check for missing multiplication operator, missing or unbalanced delimiters, or other syntax error. To construct matrices, use brackets instead of parentheses.
[tSol, zSol]=ode45(@odefun,tspan,x0);
plot(tSol, zSol);
function dzdt=odefun(t,z)
x = z(1);
y = z(2);
dxdt = -2*x;
dydt = 2*x;
dzdt = [dxdt;dydt];
end

採用された回答

Hassaan
Hassaan 2024 年 7 月 23 日
% Define the time span and initial conditions
tspan = [0 3];
z0 = [100; 0]; % Initial conditions for x and y, combined into a single column vector
% Call the ODE solver
[tSol, zSol] = ode45(@odefun, tspan, z0);
% Plot the solutions for x and y over time
figure; % Open a new figure window
hold on; % Keep the plot for adding both x and y
plot(tSol, zSol(:,1), 'b-', 'LineWidth', 2); % Plot x with a thicker blue line
plot(tSol, zSol(:,2), 'r--', 'LineWidth', 2); % Plot y with a thicker red dashed line
xlabel('Time t', 'FontSize', 12, 'FontWeight', 'bold');
ylabel('Solutions x and y', 'FontSize', 12, 'FontWeight', 'bold');
title('Solutions to the differential equations dx/dt = -2x and dy/dt = 2x', 'FontSize', 14, 'FontWeight', 'bold');
legend('x(t)', 'y(t)');
grid on; % Turn on grid
set(gca, 'FontSize', 10); % Set the font size for axes
hold off; % Release the plot hold
% Define the system of differential equations
function dzdt = odefun(t, z)
x = z(1);
y = z(2);
dxdt = -2 * x;
dydt = 2 * x;
dzdt = [dxdt; dydt];
end
  8 件のコメント
Torsten
Torsten 2024 年 7 月 24 日
zSol has two columns: the first is x over time, the second is y over time.
Alfred
Alfred 2024 年 7 月 25 日
okay. Thank you

サインインしてコメントする。

その他の回答 (1 件)

Torsten
Torsten 2024 年 7 月 23 日
tspan=[0 3];
x0=100;
y0=0;
z0=[x0;y0];
[tSol, zSol]=ode45(@odefun,tspan,z0);
plot(tSol, zSol);
function dzdt=odefun(t,z)
x = z(1);
y = z(2);
dxdt = -2*x;
dydt = 2*x;
dzdt = [dxdt;dydt];
end
  1 件のコメント
Alfred
Alfred 2024 年 7 月 23 日
Thank you very much @Torsten. Your answer is helpful

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

タグ

製品


リリース

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by