How can i solve for this issue with the logical flow

1 次查看(过去 30 天)
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops 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