I have attatched my code and thte function that it calls. I am trying to get it to timestep through the steps but it tells me the array is too large and I have hit a barrier in trying to figure it out so any assistance would be appreciated.

2 commentaires

Jan
Jan le 10 Mai 2018
Modifié(e) : Jan le 10 Mai 2018
Please post a copy of the complete error message. This is much better than a rough rephrasing, which let the readers guess, in which line the error occurs.
Devon Romine
Devon Romine le 10 Mai 2018
Index exceeds array bounds.
Error in hard_sphere (line 22) x(i+1)=x(i)+velocities_fun(x)*dt; Sorry about that

Connectez-vous pour commenter.

 Réponse acceptée

Jan
Jan le 10 Mai 2018
Modifié(e) : Jan le 10 Mai 2018
I guess, the problem is that you overwrite x, y and z in each iteration:
x = zeros(length(t),1);
y = zeros(length(t),1);
z = zeros(length(t),1);
for i=1:length(t)-1
x=r.*sin(theta).*cos(phi); % Here x is overwritten by a 20x1 vector!
y=r.*sin(theta).*sin(phi);
z=r.*cos(theta);
x(i+1)=x(i)+velocities_fun(x)*dt; % This fails for i=21
y(i+1)=y(i)+velocities_fun(y)*dt;
z(i+1)=y(i)+velocities_fun(z)*dt;
end
Use another variable:
x = zeros(length(t),1);
y = zeros(length(t),1);
z = zeros(length(t),1);
% This does not depend on the loop counter, so move it before the loop:
xc = r .* sin(theta) .* cos(phi);
yc = r .* sin(theta) .* sin(phi);
zc = r .* cos(theta);
for i = 1:length(t)-1
x(i+1) = x(i) + velocities_fun(xc) * dt;
y(i+1) = y(i) + velocities_fun(yc) * dt;
z(i+1) = y(i) + velocities_fun(zc) * dt;
end
Do you see, that some spaces around the operators improve the readability?
By the way: You use the first output of velocities_fun only, and no inputs. So you can simplify it to:
function V = velocities_fun()
V = normrnd(1,1);
end
But then creating xc, yc, zc is not useful at all.

3 commentaires

Devon Romine
Devon Romine le 10 Mai 2018
And this will create random velocities for each of the 20 points for (x,y,z)? Because I am trying to give 20 random points random velocities.
Jan
Jan le 10 Mai 2018
Please explain, which 20 points you mean. The purpose of the code is not clear.
Devon Romine
Devon Romine le 10 Mai 2018
Before the time step there are 20 points generated by the random r, phi, and theta that are distributed throughout the sphere. What I am trying to do is have 20 separate points inside the sphere move at random velocities so I can simulate collisions with them, sorry I am not very good at explaining it.

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by