MATLAB Finding q501 for Difference Equation: Solving with Matlab

AI Thread Summary
The discussion centers on solving the difference equation qn = qn-1 - 0.001 * q2n-2 for n ≥ 2, with initial conditions q0 = 1 and q1 = 2, using MATLAB. The original script provided by the user contains errors in indexing and loop initialization. The correct approach involves initializing the loop from n = 3 to 502 and properly indexing the array with q(n) instead of q_n. The suggested correction ensures that the calculations for q(n) are based on the previous two values, adhering to MATLAB's one-based indexing system. This adjustment is crucial for obtaining the correct results from the script.
roam
Messages
1,265
Reaction score
12
I want to find q501 for the difference equation:

qn=qn-1 - 0.001 q2n-2
n≥2,
q0=1,
q1=2

I thought it's easier to do this on Matlab & I tried to write a script file for this problem:

Code:
k=0.001
q(1)=1
q(2)=2
for n=1:502
    q_n=q_n-1-k*(q_n-2)^2
end

I don't know why my code isn't working/giving the right answer. Does anyone know what's the problem with this script?
 
Physics news on Phys.org
You are not indexing the array in the right way
Element n of a vector q is written q(n) in Matlab (with the first element having index 1, not zero as in some other programming languages).

Try
Code:
k=0.001
q(1)=1
q(2)=2
for n=3:502
    q(n)=q(n-1)-1-k*q(n-2)^2
end
 

Similar threads

Back
Top