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

1 回表示 (過去 30 日間)
Liam Hoyle
Liam Hoyle 2021 年 12 月 9 日
編集済み: James Tursa 2021 年 12 月 12 日
% 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.

採用された回答

James Tursa
James Tursa 2021 年 12 月 9 日
編集済み: James Tursa 2021 年 12 月 12 日
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 件のコメント
Liam Hoyle
Liam Hoyle 2021 年 12 月 9 日
Thanks so much!!!
I was halfway done the problem using my calculator, but the code is wayyy faster (:
James Tursa
James Tursa 2021 年 12 月 9 日
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

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by