Finding q501 for Difference Equation: Solving with Matlab

Click For Summary
SUMMARY

The discussion focuses on solving the difference equation qn = qn-1 - 0.001 * q2n-2 using MATLAB. The user initially attempted to implement the solution with incorrect array indexing, leading to errors in the output. The correct MATLAB script involves initializing the first two elements of the array and iterating from n=3 to n=502, ensuring proper indexing with q(n) instead of q_n. The corrected code successfully computes the desired values for the sequence.

PREREQUISITES
  • Understanding of difference equations and their formulations.
  • Familiarity with MATLAB programming, specifically array indexing.
  • Basic knowledge of loops and conditional statements in MATLAB.
  • Experience with numerical methods for solving iterative equations.
NEXT STEPS
  • Review MATLAB array indexing and its implications for programming.
  • Learn about difference equations and their applications in numerical analysis.
  • Explore MATLAB's built-in functions for solving iterative problems.
  • Investigate debugging techniques in MATLAB to troubleshoot code errors effectively.
USEFUL FOR

Mathematics students, MATLAB programmers, and anyone interested in solving difference equations using numerical methods.

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

  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 5 ·
Replies
5
Views
4K
Replies
6
Views
4K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 6 ·
Replies
6
Views
4K