How to speed up this inner loop?
- To: mathgroup at smc.vnet.net
- Subject: [mg128266] How to speed up this inner loop?
- From: Ralph Dratman <ralph.dratman at gmail.com>
- Date: Mon, 1 Oct 2012 02:23:46 -0400 (EDT)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- Delivered-to: l-mathgroup@wolfram.com
- Delivered-to: mathgroup-newout@smc.vnet.net
- Delivered-to: mathgroup-newsend@smc.vnet.net
Can someone suggest how I might optimize the For loop below for speed?
I can think of various optimizations to try, but I would like to see
what an experienced coder would do before trying to reinvent something
well known.
This is tested code, which accomplishes the basics of what I want, but
which needs to run faster.
Using Compile would be fine, but I don't yet understand how to set it
up properly.
As an aside, I found the details of calling ListConvolve difficult to
grasp from the documentation.
Thank you in advance.
Ralph Dratman
---------------------------------
(* Size of arrays *)
xSize = ySize = 40;
(* The mass at a location, not used yet. *)
mfunc[x_, y_] := 1.0;
(* Initial conditions are products of eigenfunctions in x and y. *)
zpos = Table[
Sin[3 (x/(xSize + 1)) Pi] Sin[2 (y/(ySize + 1)) Pi], {y,
ySize}, {x, xSize}];
(* Zero initial velocity. *)
zvel = Table[0, {y, ySize}, {x, xSize}];
(* Mass does not vary here but may later vary with position via mfunc.*)
m = Table[1., {y, ySize}, {x, xSize}];
(* Spring constant when viewing this as an array of coupled oscillators. *)
k = .05;
damp = .001;
dt = .1;
(* Discrete second derivative in PDE interpretation; *)
(* spring coupling arrangement in coupled oscillator view. *)
convKernel = {{0., 1., 0.}, {1., -4., 1.}, {0., 1., 0.}};
timeEvolve[cycles_] := Module[{},
For[i = 1, i <= cycles, i++,
zpos = zpos + zvel dt;
zvel = (1.-damp) zvel + (k/m) ListConvolve[convKernel, zpos, {{2, 2},
{2, 2}}, 0.] dt
];
Print@ListPlot3D[zpos, PlotRange -> {-1., 1.}, ImageSize -> {200}]];
Table[timeEvolve[cycles], {cycles, {0, 120, 150, 500, 600}}]