Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.


Math Forum » Discussions » Software » comp.soft-sys.math.mathematica

Topic: How to speed up this inner loop?
Replies: 0  

Advanced Search

Back to Topic List Back to Topic List  
Ralph Dratman

Posts: 62
Registered: 5/13/11
How to speed up this inner loop?
Posted: Oct 1, 2012 2:19 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

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}}]




Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.