Search code examples
matlabfor-loopodedifferential-equations

Two For loops working Simultaneously ? bvp4c


I am trying to solve a differential equation system using bvp4c (boundary conditions). I am using two for loops to solve the functions of bvp4c but the problem is one for loop is done first and then only the last value is used with the iterations of the second for loop, is there a way to make them work simultaneously ? meaning the first iteration of the first for loop uses the first iteration values of the second for loop (not the last as it happens) ? thanks

function RTrajfoll(X,Y)
    clf;
    for i = 1:length(X)-1
        init = bvpinit(linspace(X(i),X(i+1),10),[0 0]);
        sol = bvp4c(@Kpath1,@bcpath,init);
        x = linspace(X(i),X(i+1),100);
        BS = deval(sol,x);
        plot(x,BS(1,:),'linewidth',2)
        axis([-2 6 -2 6])
        hold on 
    end

    function bv = bcpath(L,R)
        for j = 1:length(Y)-1
            bv = [L(1)-Y(j) R(1)-Y(j+1)];
        end
    end

end

%Differential equations dy/dx and dtheta/dx 
function dx = Kpath1(~,c)
    L = 0.12;                        
    r = 0.1;
    WL = 0.25;WR = 0.25;
    y = c(1);th = c(2); 
    dy = tan(th);
    dth = (2*((r*WR)-(r*WL)))/(L*cos(th)*((r*WR)+(r*WL)));
    dx = [dy;dth];
    pose = [y;th];
end

Solution

  • Looking at @Lutz's answer, you probably don't need a fully-fledged function for bv. You may find it more convenient to provide an anonymous function handle, in which case you won't need the third argument:

    sol = bvp4c(@Kpath1,@(L,R)[L(1)-Y(i) R(1)-Y(i+1)],init);