Function Error: Array indices must be positive integers or logical values.

1 view (last 30 days)
% Inputs
m = 1.327E20; %gravitational parameter of central body
ri = 1.51E11; %inner radius in meters
ro = 5.77E10; %outer radius in meters
%Helper Equations
R = (ro)/(ri);
a = ((ro)+(ri))/2;
%Delta V Equation
v(ro,ri) = (sqrt(m/(ri)))*((1/sqrt(R))-((sqrt(2)*(1-R))/(sqrt(R(a+R))))-1);
Array indices must be positive integers or logical values.
fprintf('\n Delta V = %g m', v(ro,ri))
I'm trying to solve for a lengthy homework problem by using MATLAB and I keep getting this error. I've solved with the initial conditions to be sure that I'm using a valid equation. The eqaution is supposed to be:
I have a feeling that my missuse of parenthesis is causing this issue. I'm getting confused about the array error because I'm a beginner.

Accepted Answer

James Tursa
James Tursa on 9 Dec 2021
Edited: James Tursa on 12 Dec 2021
When you have parentheses appear on the left hand side of an assignment like this:
v(ro,ri) = (sqrt(m/(ri)))*((1/sqrt(R))-((sqrt(2)*(1-R))/(sqrt(R(a+R))))-1);
then MATLAB thinks you are trying to index into a variable called v. And since ro and ri are not positive integers, you get the error. Also this line has a typo with a missing * so you will get the same error because of that.
Instead, what you want to do is calculate v directly:
v = (sqrt(m/ri))*(1/sqrt(R)-((sqrt(2)*(1-R))/(sqrt(R*(a+R))))-1);
And then just print v in your printf statement:
fprintf('\n Delta V = %g \n', v)
  2 Comments
Liam Hoyle
Liam Hoyle on 9 Dec 2021
Thanks so much!!!
I was halfway done the problem using my calculator, but the code is wayyy faster (:
James Tursa
James Tursa on 9 Dec 2021
Note that if you wanted a function to calculate v, you could create a file called deltav.m (or some other name of your choosing) with the following code:
% deltav calculates delta velocity for the orbit problem blah blah blah
function v = deltav(m,ri,ro)
R = ro / ri;
a = (ro + ri) / 2;
v = (sqrt(m/ri))*(1/sqrt(R)-((sqrt(2)*(1-R))/(sqrt(R*(a+R))))-1);
end

Sign in to comment.

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!