MATLAB: Problem with integrating a piece-wise function

cumsumpiece-wise function

Hello everybody,
I've been trying to integrate a piece-wise function using cumsum and for loop, but this doesn't work correctly. Mathematically/Physically, the problem is defined as follows: I have a charge density rho(x) vs. coordinate x between x_min and x_max across 2 materials with different dielectric permittivities eps1 and eps2.
For a uniform media (1 material) I find an electric field E by summing up rho(x)/eps over small intervals dx:
x =x_min:dx:x_max;
rho = @(x) rho_A*[heaviside(x-x_min)-heaviside(x-x_max)]
E=cumsum(rho(x(k))/eps_r)*dx;
That works fine. However, with 2 materials when I use for loop and if else statement to assign different eps to the 2 media, namely:
x =x_min:dx:x_max;
for k = 1:length(x)
if x(k)<=0;
eps_r=10;
rho = @(x) rho_A*(heaviside(x-x_min)-heaviside(x-x_max));
E(k)=cumsum(rho(x(k))/eps_r)*dx;
else
eps_r=15;
rho = @(x) rho_A*(heaviside(x-x_min)-heaviside(x-x_max));
E(k)=cumsum(rho(x(k))/eps_r)*dx;
end
end
That doesn't work correctly – cumsum doesn't sums up rho(x)/eps*dx over x =x_min:dx:x_max, but instead mimics the charge density distribution rho(x). I guess I am not using the right tools for the job. Please help to solve the problem.
Many thanks

Best Answer

You’re not assigning different values for ‘eps’:
eps_r=15; % <- ‘eps_r’ Here
rho = @(x) rho_A*(heaviside(x-x_min)-heaviside(x-x_max));
E(k)=cumsum(rho(x(k))/eps)*dx; % <- ‘eps’ Here
Also, please do not use ‘eps’ as a variable name. It is the name of a built-in MATLAB function, so if you want to use it as a function later in your code, you will not be able to. This is called ‘overshadowing’, and it is best not to do it. The solution is to rename your ‘eps’ variable to ‘epsln’ or something that makes sense in the context of your problem.