MATLAB: In an assignment A(:) = B, the number of elements in A and B must be the same. Runge-Kutta solving PDE using Method of lines

indexingmatricesmethod of lines

Hello all,
I am getting the error,
"In an assignment A(:) = B, the number of elements in A and B must be the same."
I am confused because I am just trying to assign the i+1 index of a vector V to the ith inded of the same vector V.
V should be a 1 X 5001 vector, with N = 5000, dictated by the stepsize, h.
Any hints would be greatly appreciated!
Here is the Main—-
% Runge Kiutta code to solve Fitxhugh-Nagumo Equation
% dV/dt = f(v + veq) - f(veq) - w % Potential
% dW/dt = epsilon(v - gamma*w) % sodium gating variable
clear; clc
% constants
global D a veq h N V
a=0.139;
epsilon=0.008;
gamma=2.54;
veq=0.07;
% Define function dandles
%f_V=@(t,V,W) ((V + veq)*((V + veq)-a)*(1-(V + veq)) - veq*(veq-a)*(1-veq) - W);
fW=@(t,V,W) epsilon*(V - gamma*W);
% initial conditions
V = [didn't keep these in here... 5000 initial, floating point, conditions...];
t(1) = 0;
W(1) = -0.055;
x = linspace(0,N-1,N);
% Step size
h=0.1;
tfinal=500;
N=ceil(tfinal/h);
fprintf('"N = %d"',N);
% Update loop
for i=1:N
%update time
t(i+1)=t(i)+h;
% Update & F
k1V=F_V(t(i) ,V(i), W(i) ,i);
k1W=fW(t(i) ,V(i), W(i) );
k2V=F_V(t(i)+h/2 ,V(i)+h/2*k1V, W(i)+h/2*k1W,i);
k2W=fW(t(i)+h/2 ,V(i)+h/2*k1V, W(i)+h/2*k1W);
k3V=F_V(t(i)+h/2 ,V(i)+h/2*k2V, W(i)+h/2*k2W,i);
k3W=fW(t(i)+h/2 ,V(i)+h/2*k2V, W(i)+h/2*k2W);
k4V=F_V(t(i)+h/2 ,V(i)+h *k3V, W(i)+h *k3W,i);
k4W=fW(t(i)+h/2 ,V(i)+h *k4V, W(i)+h *k3W);
V(i+1)=V(i) + h/6*(k1V + 2*k2V + 2*k3V + k4V);
W(i+1)=W(i) + h/6*(k1W + 2*k2W + 2*k3W + k4W);
end
%plot the solution
figure(1); clf(1)
plot(t,V)
hold on
plot(t,W)
xlabel('Time')
ylabel('Populations')
legend('V','W')
set(gca,'FontSize',16)
figure(2); clf(2)
plot(V,W)
hold on
xlabel('V')
ylabel('W')
and the function for F_V, the first ODE—
function fV = f_V(t,Vi,W,i)
global D a veq N h V
dx2 = h^2;
if(i==1)
fV = D*((V(2)-V(1))/dx2)+((Vi + veq)*((Vi + veq)-a)*(1-(Vi + veq)) - veq*(veq-a)*(1-veq) - W);
elseif(i==N)
fV = D*((-V(i)+V(i-1))/dx2)+((Vi + veq)*((Vi + veq)-a)*(1-(Vi + veq)) - veq*(veq-a)*(1-veq) - W);
else
fV = D*((V(i+1)-2*V(i)+V(i-1))/dx2)+((Vi + veq)*((Vi + veq)-a)*(1-(Vi + veq)) - veq*(veq-a)*(1-veq) - W);
end
end

Best Answer

You never initialize D. By default, global variables are initialized to the empty matrix, []. Your f_V code multiplies something by this empty matrix, D, so the results it calculates are always empty. You are then trying to store that empty result into a non-empty location.
Don't use global. Pass all the values you need to the function.
Related Question