problem with integrating a piece-wise function

1 view (last 30 days)
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

Accepted Answer

Star Strider
Star Strider on 9 Feb 2016
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.
  9 Comments
Star Strider
Star Strider on 11 Feb 2016
Thank you. That’s far from my areas of expertise, so I’ll do my best to understand it and see if I can get it in a form that would use integral, since it is superior to numerically integrating vectors. I can’t promise anything, though.
Anton Velychko
Anton Velychko on 11 Feb 2016
Certainly, I do not expect any promises, you've already done me a great favour. :-) Please let me know if anything is unclear or confusing. Thank you.

Sign in to comment.

More Answers (0)

Categories

Find more on Categorical Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!