How can i solve for this issue with the logical flow

1 view (last 30 days)
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

Accepted Answer

Chad Greene
Chad Greene on 6 May 2021
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 Comments
Chad Greene
Chad Greene on 6 May 2021
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

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!