invert the direction of a particles in matlab

Without your information, I am going to guess how I'd do it:

part_location=rand(10,2); % 10 particles
part_direction=rand(10,2); % non-normalized direction so it has also speed
boundaries=[0,0;1 1]; % square boundary from 0 to 1; not going to use it so I dont write your whole code.


for ii=1:nsteps_simulation
    % update particle position using direction
    % do it
    part_location= ... ?
    % check if particles are inside the boundary

    inside=sum(part_location>0 && part_location<1,2)==2;

    outside=~inside;

    % now you know which particles are inside and wich outside.
    % Inverting the direction should be easy

    part_direction=...?

end

Apologise if the code is not complete, but nobody is going to write it for you! However, I hope that I have given you a clear structure of how you should design an algorithm for this. Of course, depending on your data/application you'd need to modify the structure a bit, but this is probably the most you'll get without more information or show us what you tried!