Waves spectrum in a string
3 次查看(过去 30 天)
显示 更早的评论
Can someone please help me with this code I don't why its not running
% Solution of wave equation for string
% based on 'Computational Physics' book by N Giordano and H Nakanishi
%
clear;
string_dimension=100;
time_loops=1500;
% Preallocate matrices for speed;
x=1/string_dimension:1/string_dimension:1;
x_scale=1:1:string_dimension;
y_next =zeros(1,string_dimension);
signal_data=zeros(1,time_loops);
elapsed_time=zeros(1,time_loops);
% Initialise string position
k=1000;
x_0=0.5;
delta_t=3.33e-5;
f_sample=1/delta_t;
initial_position=exp(-k.*(x-x_0).^2);
y_current =initial_position;
y_previous = initial_position;
initial_time=0;
time=initial_time;
for time_step = 1:time_loops;
time=time+delta_t;
[y_next]=realistic(y_current, y_previous);
y_previous=y_current;
y_current=y_next;
clf;
subplot(2,2,1);
plot(x_scale/string_dimension, y_current,'r');
title('Waves on a string - fixed ends');
xlabel('distance');
ylabel('Displacement');
axis([0 1 -1 1]);
hold on;
%drawnow;
%%%%%%%
% Record displacement at 5 percent from left end of the string for future plot
signal_data(time_step)=y_current(40);
elapsed_time(time_step)=time;
subplot(2,2,2);
% plot displacement at 5 percent from left end of the string
% using suitable scaling
plot(elapsed_time,signal_data);
title('Signal from a string');
xlabel('time (s)');
ylabel('Displacement(au)');
end;
function [y_next] = realistic(y_current, y_previous)
r=1;
M=size(y_current,2);
y_next=zeros(1,M);
i=2:1:M-1;
%This loop index takes care of the fact that the boundaries are fixed
y_next(i) = (2-2*r^2-6*7.5e-6*r^2*90)*y_current(i)-y_previous(i)+...
(r^2+4*r^2*7.5e-6*90^2)*(y_current(i+1)+y_current(i-1))-...
r^2*7.5e-6*90^2*(y_current(i+2)+y_current(i-2));
end
Thanks
0 个评论
回答(1 个)
Guillaume
2016-10-3
编辑:Guillaume
2016-10-3
There clearly is a problem with your function realistic.
Your main script assumes that y_next, y_current, and y_previous are scalar. However, as is written, your realistic function assumes they're row vectors (of length M, and with at least 3 elements)
The comment %This loop index ... is also misleading since there is no loop in realistic. i is just a plain index.
Note that since i is a vector, so is y_next(i).
Overall, I'm not clear what you're trying to achieve in the function. What is the difference between y_current(i-1) and y_previous(i). Also it looks like your y_next depends on future values ( y_current(i+1) and y_current(i+2)) which does not look right to me.
3 个评论
Guillaume
2016-10-6
I suggest you learn how to debug your program. Step through your code line by line and see if the output of each line conforms to your expectations.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 General Applications 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!