MATLAB: Need help time stepping this system

spheretimestep

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.

Best Answer

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.