1

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
2
  • Are X and Y the same length. I.e., are for i = 1:length(X)-1 and for j = 1:length(Y)-1 supposed to correspond to each other? Commented Apr 25, 2017 at 18:43
  • yes, both X and Y are the same length Commented Apr 27, 2017 at 19:40

2 Answers 2

1

The observed behavior is exactly the expected behavior, you assign repeatedly to bv, the return value is the last assigned value.

You will need to pass the index i to the boundary condition function, either as a parameter

  sol = bvp4c(@Kpath1,@(L,R)bcpath(L,R,i),init);

with

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

or by redefining bcpath in every iteration, using the index as global variable,

      for i = 1:length(X)-1
        function bv = bcpath(L,R)
          bv = [L(1)-Y(i) R(1)-Y(i+1)];
        end
        init = bvpinit(linspace(X(i),X(i+1),10),[0 0]);
        sol = bvp4c(@Kpath1,@bcpath,init);
...
0
0

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.