function left.m (put in a separate file called left.m)
function output=left(x)
% left.m takes an array x and shifts the elements
% one element to the left, wrapping the end value
n = length(x);
a = [x(2:n) x(1)];
output = a;
function right.m (put in a separate file called right.m)
function output=right(x)
% right.m takes an array x and shifts the elements
% one element to the right, wrapping the end value
n = length(x);
a = [x(n) x(1:(n-1))];
output = a;
script file String.m (put in a separate file called String.m)
clg
clear
x = linspace(0,10,200); % generate x-axis array
y = linspace(0,1,50); % generate positive slope portion
z = linspace(1,0,50); % generate negative slope portion
a = [y z (z-1) (y-1)] * 0.5; % create initial rightgoing phantom wave
b = a; % create initial leftgoing phantom wave
M = moviein(length(x)/6); % save space for movie
% drawing loop
count = 0; % counting variable to keep track of shifts
snap = 0; % counting variable keeps track of movie frames
cycle = length(a); % total number of times to shift
while count < cycle
a = right(a); % shift a array one element to the right
b = left(b); % shift b array one element to the left
c = a + b; % superpose the left and right phantoms
plot(x,a, ':',x,b,'--',x,c) % plot all the waves
axis([0 5 -1 1]) % fix axes to show only physical portion
pause(0.5);
hit = rem(count,6); % save every 6th frame
if (hit == 0)
snap = snap + 1; % increment frame number
M(:,snap) = getframe;
end
count = count + 1; % increment the counting variable
end
movie(M,10);
Challenge solution (put in a file called Stringplus.m)
%Stringplus.m
clear
clg
x0 = input('Enter pluck position from left end (integer percent): ');
y0 = input('Enter intial pluck amplitude: ');
x = linspace(0,10,200); % generate x-axis array
y = linspace(0,y0,x0); % generate positive slope portion
z = linspace(y0,0,100-x0); % generate negative slope portion
a = [y z (z-y0) (y-y0)] * 0.5; % create rightgoing phantom
b = a; % create initial leftgoing phantom wave
M = moviein(length(x)/7); % save space for movie
% drawing loop
count = 0; % counting variable to keep track of shifts
snap = 0; % counting variable keeps track of movie frames
cycle = length(a); % total number of times to shift
while count < cycle
a = right(a); % shift a array one element to the right
b = left(b); % shift b array one element to the left
c = a + b; % superpose the left and right phantoms
plot(x,a, ':',x,b,'--',x,c) % plot all the waves
axis([0 5 -y0 y0]) % fix axes to show only physical portion
pause(0.5);
hit = rem(count,7); % save every 7th frame
if (hit == 0)
snap = snap + 1; % increment frame number
M(:,snap) = getframe;
end
count = count + 1; % increment the counting variable
end
movie(M,10);