Question

The code in question is here:

function k = whileloop(odefun,args)
    ...
    while (sign(costheta) == originalsign)
        y=y(:) + odefun(0,y(:),vars,param)*(dt); % Line 4
        costheta = dot(y-normpt,normvec);
        k = k + 1;
    end
    ...
end

and to clarify, odefun is F1.m, an m-file of mine. I pass it into the function that contains this while-loop. It's something like whileloop(@F1,args). Line 4 in the code-block above is the Euler method.

The reason I'm using a while-loop is because I want to trigger upon the vector "y" crossing a plane defined by a point, "normpt", and the vector normal to the plane, "normvec".

Is there an easy change to this code that will speed it up dramatically? Should I attempt learning how to make mex files instead (for a speed increase)?

Edit:

Here is a rushed attempt at an example of what one could try to test with. I have not debugged this. It is to give you an idea:

%Save the following 3 lines in an m-file named "F1.m"
function ydot = F1(placeholder1,y,placeholder2,placeholder3)
    ydot = y/10;
end

%Run the following:
dt = 1.5e-12 %I do not know about this. You will have to experiment.
y0 = [.1,.1,.1];
normpt = [3,3,3];
normvec = [1,1,1];
originalsign = sign(dot(y0-normpt,normvec));
costheta = originalsign;
y = y0;
k = 0;
while (sign(costheta) == originalsign)
    y=y(:) + F1(0,y(:),0,0)*(dt); % Line 4
    costheta = dot(y-normpt,normvec);
    k = k + 1;
end
disp(k);

dt should be sufficiently small that it takes hundreds of thousands of iterations to trigger.

Assume I must use the Euler method. I have a stochastic differential equation with state-dependent noise if you are curious as to why I tell you to take such an assumption.

Was it helpful?

Solution

I would focus on your actual ODE integration. The fewer steps you have to take, the faster the loop will run. I would only worry about the speed of the sign check after you've optimized the actual integration method.

It looks like you're using the first-order explicit Euler method. Have you tried a higher-order integrator or an implicit method? Often you can increase the time step significantly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top