MATLAB: Two For loops working Simultaneously ?? bvp4c

controldifferential equationserrorfor looploopMATLABodeparallel computingparforwhile loop

I am 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

Best Answer

the answer from stackoverflow 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);
...