Modelling gas particles; "Attempted to access x(11); index out of bounds because numel(x)=10."
Show older comments
Hi, I am at the begging of trying to module gas particles currently the get a problem
Attempted to access x(11); index out of bounds because numel(x)=10.
Error in gasparticelbasic (line 20) x(i) = x(i)+velocityx*dt;
This is my current code;
figure(1) n = 10; % Number of data points x = 50*rand(n,1)-25; y = 50*rand(n,1)-25;
velocityx = 10*rand(1);
velocityy = 10*rand(1);
dt = 0.2;
for i = 1:1:50
subplot (2,1,1)
plot(x,y,'o');
axis([-25,25,-25,25]);
hold on
pause(dt);
hold off
x(i) = x(i)+velocityx*dt;
y(i) = y(i)+velocityy*dt;
end
Any help would be great. Thanks
Answers (1)
Sebastian Castro
on 17 Mar 2015
0 votes
I have two thoughts here.
1. You have an out-of-bounds indexing error because you're saying that x(i) = x(i)+velocityx*dt; , thus making the variable reference an index that hasn't yet been created. If you want to do a basic forward integration, shouldn't you try x(i+1)= x(i)+velocityx*dt; ?
This would require you to define an initial velocity x(1) , and for efficiency, to preallocate your x and y vectors with a known size ... for example x = zeros(100,1);
2. Defining the velocities with rand before the loop means that the value of velocityx and velocityy will be the same for every particle and for every iteration.
- If you want each particle to have a constant velocity for the whole duration, try generating 25 random numbers: velocityx = rand(25,1);
- Else, if you want each particle to have a different random velocity at every time step, call the rand function inside the loop so its value changes at each iteration.
- Sebastian
1 Comment
Alastair Martin
on 4 May 2015
Categories
Find more on Programming 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!