my code wont display figure

1 回表示 (過去 30 日間)
Bijaya
Bijaya 2023 年 10 月 16 日
編集済み: Drishti 2024 年 9 月 26 日
% Parameters
L = 1; % Length of the string
c = 1; % Wave speed
num_segments = 200; % Number of segments
dx = L / num_segments; % Discretization step
dt = 0.005; % Time step
num_steps = 10 / dt; % Number of time steps
% Initial wave parameters
left_wave_length = 0.15 * L;
right_wave_length = 0.25 * L;
% Initialize the wave function
x = 0:dx:L;
u = sin(pi * x / left_wave_length) + sin(2 * pi * x / right_wave_length);
% Time integration
for step = 1:num_steps
% Compute second spatial derivative using finite differences
u_xx = (u(1:end-2) - 2*u(2:end-1) + u(3:end)) / dx^2;
% Update the wave equation using finite differences
u_new = 2*u(2:end-1) - u(2:end-1) + c^2 * dt^2 * u_xx;
% Update boundary conditions
u_new1 = [0, u_new, 0];
% Update the wave function
u = u_new1;
end
% Plot at t = 0
figure;
plot(x, u);
title('Wave Equation at t = 0');
xlabel('Position [L]');
ylabel('Amplitude');
xlim([0, L]);
% Plot at t = 10 [t]
figure;
plot(x, u);
title('Wave Equation at t = 10 [t]');
xlabel('Position [L]');
ylabel('Amplitude');
xlim([0, L]);
  1 件のコメント
Torsten
Torsten 2023 年 10 月 16 日
Choose another code from the internet - this one is completely wrong.

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

回答 (1 件)

Drishti
Drishti 2024 年 9 月 26 日
編集済み: Drishti 2024 年 9 月 26 日
Hi Bijaya,
While debugging the provided code on my end, I also encountered a similar issue of ‘empty figure’.
The issue can be resolved by utilizing a variable ‘u_prev’ to store the value of wave function from the previous step.
You can refer to the implementation provided below:
% Initialize previous wave function for time-stepping
u_prev = u;
% Time integration
for step = 1:num_steps
% Compute second spatial derivative using finite differences
u_xx = (u(1:end-2) - 2*u(2:end-1) + u(3:end)) / dx^2;
% Update the wave equation using finite differences
u_new = 2*u(2:end-1) - u_prev(2:end-1) + c^2 * dt^2 * u_xx;
% Update boundary conditions
u_new1 = [0, u_new, 0];
% Update the wave functions
u_prev = u;
u = u_new1;
end
The ‘u_prev’ variable will be utilized to calculate the updated value of wave in later steps as demonstrated in the code snippet.
I hope this helps in resolving the issue.

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by