I'm trying to make an animation of a travelling sine wave (amplitude vs. position) would anyon here happen to know how to do so?
2 Answers
$\begingroup$
$\endgroup$
A very simple example
#include <iostream>
#include <cmath> // sin
#include <fstream> //ofstream
#include <sstream> //stringstream
#include <string> //string
#include <cstring> //c_str
#define PI 3.14159265
// Modifies the elements in an array to five an evenly spaced number of points
// Along the specified interval (from b to a)
void linspace(double a, double b, double c, double * array){
double delta =(b-a)/(c-1);
for (int i=0; i<c; ++i){
array[i]= i*delta;
}
}
int main(int argc, char * argv[]){
double c=1.;
double x=0;
double u[90];
for (int i=0; i<90; ++i){ u[i] = 0.; } // Initalize array
double a=0., b=10.;
linspace(a, b, 90, u);
std::string file ="datsin"; // Output file name
for (int i=0; i<90; ++i){
std::ostringstream oss;
oss << "datsin" << i;
std::ofstream out(oss.str().c_str());
for (int t=0; t<=360; ++t){
out << t<<'\t'<< sin(u[i]+(t*PI/180)) <<'\n';
}
out.close();
}
}
This will output the spatial coordiates of the wave at each moment in a series of files starting with "datsinX" where X will be a number from 0 to 89 in this case. In order to now make an animation one can use the following gnuplot script:
set terminal gif animate delay 10
set output "animate.gif"
set yrange[-1:1]
set xrange[0:400]
n=90
i=0
load "plot.gnuplot"
set output
which in this case, will in turn call the script "plot.gnuplot"
plot 'datsin'.i w p ps 2 title sprintf("t=%i",i)
i=i+1
if (i < n) reread
pause 3
and will produce a gif called "animation.gif"
$\begingroup$
$\endgroup$
1
In Mathematica:
Animate[Plot[Sin[x + t], {x, -5, 5}], {t, 0, 10}]
-
$\begingroup$ This question was oriented towards implementation of algorithms, not so muh the answer $\endgroup$ Commented Feb 22, 2015 at 13:58
vidObj = VideoWriter('sine.avi'); open(vidObj); x = linspace(0,2*pi); for t=linspace(1,10), plot(x,sin(x-t)); writeVideo(vidObj,getframe); end, close(vidObj);
$\endgroup$