% Define the parameters of the problem
L = 80; % length of the string (cm)
mu = 0.0125; % linear mass density of the string (g/cm)
T = 40000; % tension in the string (g)
c = sqrt(T/mu); % speed of the wave (cm/s)
x0 = 20; % initial displacement point (cm)
y0 = 0.6; % initial displacement (cm)
Ax = 10; % spatial step size (cm)
At = 0.000179; % time step size (s)
N = L/Ax + 1; % number of spatial grid points
M = 2*N; % number of time steps (2 cycles)
% Initialize the arrays
y = zeros(N, M); % y(x, t) array
x = linspace(0, L, N); % x array
% Set the initial conditions
y(:, 1) = x.*(y0/x0); % linear displacement profile
y(x0/Ax + 1, 1) = y0; % initial displacement point
% Use the finite difference method to approximate the wave equation
for n = 2:M
for i = 2:N-1
y(i,n) = 2*y(i, n-1) -y(i, n-2)+ (c*At/Ax)^2*(y(i+1, n-1)-2*y(i,n-1)+ y(i-1,n-1));
end
% Apply boundary conditions
y(1, n) = y(2, n);
y(N, n) = y(N-1, n);
end
Index in position 2 is invalid. Array indices must be positive integers or logical values.
% Plot the results
t = linspace(0, M*At, M);
figure;
plot(x, y(:, 1), 'b-', x, y(:, M), 'r-');
xlabel('Position (cm)');
ylabel('Displacement (cm)');
legend('t = 0', 't = 2 cycles');
title('Vibration of Banjo String');
% Calculate the frequency of vibration
cycle_time = 2*M*At; % time for 2 cycles
frequency = 1/cycle_time; % frequency in cycles/sec
disp(['Frequency of vibration: ' num2str(frequency) ' cycles/sec']);

 채택된 답변

Torsten
Torsten 2023년 6월 12일
이동: Torsten 2023년 6월 12일

0 개 추천

y(i,n) = 2*y(i, n-1) -y(i, n-2)+ (c*At/Ax)^2*(y(i+1, n-1)-2*y(i,n-1)+ y(i-1,n-1));
For n = 2 and i = 2, you try to access y(2,0) which throws an error.

댓글 수: 3

Nuha Krir
Nuha Krir 2023년 6월 12일
it doesn't work
Walter Roberson
Walter Roberson 2023년 6월 12일
You have
for n = 2:M
for i = 2:N-1
y(i,n) = 2*y(i, n-1) -y(i, n-2)+ (c*At/Ax)^2*(y(i+1, n-1)-2*y(i,n-1)+ y(i-1,n-1));
end
When n == 2 then n-2 is 0 so you would be trying to access y(i, 0) which is not valid in MATLAB.
There are two possibilities:
  1. That your y update code is incorrect; Or
  2. That your n needs to start at 3.
Nuha Krir
Nuha Krir 2023년 6월 13일
Thanks alot

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

질문:

2023년 6월 12일

댓글:

2023년 6월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by