MATLAB: Index exceeds the number of array elements (1).

#linear motionindexphysics

Trying to come up with a function that accepts:
Initial Velocity, Final Velocity, X(position), Time, and Displacement using If statements to help solve for the missing values, and I get the "Index exceeds the number of array elements(1)" problem…
Do I have I have to make an array in order for this to work? or is there any other way around it? Thank you.
function[ini_v,fin_v,accl,ini_x,fin_x,time,disp_x]=One_Dimensional_Motion_Solver(ini_v,fin_v,accl,ini_x,fin_x,time,disp_x)
%We will use a set of nested if statements in order to properly tackle One
%Dimensional Physics Problems
%Lets find acceleration if its not given
if accl==0 && disp_x==0
accl_value = (fin_v - ini_v)/time;
accl = accl_value;
elseif fin_v==0
accl_value = (2*disp_x-2*ini_v)/time;
accl = accl_value;
else
(fin_v^2-ini_v^2)/2*disp_x;
end
%Now we're looking for Final Position
if fin_x==0 && accl==0
value_x = ini_x + ini_v*time + 1/2*time^2;
fin_x = value_x;
else fin_x==0
value_x = (fin_v^2 - ini_v^2)/2*accl+ini_x;
fin_x = value_x;
end
%Now we're looking for Displacement
if disp_x==0
if accl ==0
disp_value = 1/2*(ini_v + fin_v)*time;
disp_x = disp_value;
end
else
disp_value = (fin_v^2 - ini_v^2)/2*accl;
disp_x = disp_value;
end
%Now we're looking for Final Velocity
if time==0
fin_v = 1/2*(fin_v + ini_v);
if fin_v==0
fin_v = sqrt(ini_v^2 + 2*accl*disp_x);
else
fin_v = ini_v + accl(time);
end
else
fin_v = ini_v + accl(time)
end
end

Best Answer

What is size(accl) on input?
I notice you have if time==0 so your code expects the possibility of time being 0. But if it is 0 then your calculations of accl_value would involve division by 0.
if accl==0 && disp_x==0
That suggests that accl is a scalar, but later you using accl(time) which would be indexing by time. If time was not 1 then you would be trying to index a scalar at a location that was outside of bounds.