Given that Mathematica has a wide range of functions I would like to know if there is a better way to make this loop using Mathematica.
Do[If[Abs[xp[[i]] - xg[[j]]] <= dx, \[Rho][[j]] =\[Rho][[j]] - carga*(1 - (Abs[xp[[i]] - xg[[j]]])/dx)/dx, 0] , {i, 1, np}, {j, 1, ng + 1}];
Basically I am comparing the position i of vector xp with the position j of vector xg. If the condition is verified then I use the iterator j to calculate the function [Rho] of j.
My question is if Mathematica doesn’t have a better way to do this operation that would take less time to run. Like some built in function or smarter method to do operations between vectors?
Here is a snippet of my code if anyone need better context to understand.
eps = 8.85*10^(-12);
q = 80;
m = 50;
L = 2;
nparticles = 2000;
ngrid = 200;
vth = 2;
u = 1;
dx = L/ngrid;
rho = Compile[{{xp, _Real, 1}, {xg, _Real,
1}, {carga, _Real}, {np, _Real}, {ng, _Real}, {dx, _Real}},
n = ng + 1;
ρ = Table[carga*np/(dx*ng), n];
ρ[[ng + 1]] = 0;
Do[If[Abs[xp[[i]] - xg[[j]]] <=
dx, ρ[[j]] = ρ[[j]] -
carga*(1 - (Abs[xp[[i]] - xg[[j]]])/dx)/dx; r += 1, 0] , {i, 1,
np}, {j, 1, ng + 1}];
ρ[[1]] = ρ[[1]] + ρ[[ng + 1]];]
x = RandomVariate[UniformDistribution[{0, L}], nparticles];
r = 0;
xgrid = Range[0, L, dx] // N;
rho[x, xgrid, q, nparticles, ngrid, dx]; // AbsoluteTiming
r