How can i solve for this issue with the logical flow

1 回表示 (過去 30 日間)
Mark Loui
Mark Loui 2021 年 5 月 6 日
コメント済み: Mark Loui 2021 年 5 月 6 日
n=length(q);
coef=k*dt/dr;
q_new=zeros(n,1);
q(0)=0;
% for i=1:n+1
% q_new(i)=q(i)+(coef*(q(i+1)-(2*q(i))+q(i-1)));
% end
for i=1:n+1
term1=(q(i+1)*((r(i+1)+dr)/r(i)*dr));
term2=2*q(i)*(1/dr);
term3=q(i-1)*((r(i)-dr)/r(i)*dr);
qnew(i)=q(i)+(coef*(term1-term2+term3));
q_new=qnew(i);
end
Can someone please help me with this i cant seem to make it work, what can i do to make the the error of logical go away?
Array indices must be positive integers or logical values: %This is the error show

採用された回答

Chad Greene
Chad Greene 2021 年 5 月 6 日
I think the error is here:
term3=q(i-1)*((r(i)-dr)/r(i)*dr);
The first time through the loop, i=1, meaning i-1=0. There is no zeroth element of q. Which element of q are you trying to access?
  3 件のコメント
Chad Greene
Chad Greene 2021 年 5 月 6 日
If q(0) = 0, then q(i-1)*((r(i)-dr)/r(i)*dr) will equal zero whenever i=1. Therefore I suggest
if i==1
term3=0;
else
term3=q(i-1)*((r(i)-dr)/r(i)*dr);
end
Mark Loui
Mark Loui 2021 年 5 月 6 日
Hmm sounds good, i try and see thanks

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by