Implementing Difference Equation in MATLAB

Click For Summary
SUMMARY

This discussion focuses on implementing the difference equation y[n] = x[n] - x[n-1] in MATLAB, addressing the challenge of negative indexing. Users provided three effective methods to circumvent MATLAB's limitation with negative indices. The solutions include initializing y[1] separately, defining x[-1] outside of loops, and utilizing vector operations to compute y directly. Each method is accompanied by MATLAB code snippets for practical implementation.

PREREQUISITES
  • Understanding of difference equations
  • Familiarity with MATLAB syntax and functions
  • Basic knowledge of vector operations in MATLAB
  • Experience with plotting in MATLAB
NEXT STEPS
  • Explore MATLAB vectorization techniques for performance optimization
  • Learn about MATLAB's array indexing and manipulation
  • Investigate advanced plotting functions in MATLAB for data visualization
  • Study the implementation of other difference equations in MATLAB
USEFUL FOR

MATLAB users, engineers, and students interested in digital signal processing and numerical methods who need to implement difference equations without encountering indexing issues.

raheequlmakhtoom
Messages
1
Reaction score
0
please help me to implement this difference equation in MATLAB?

y[n]=x[n]-x[n-1];

matlab is not supportin -ve index...
 
Physics news on Phys.org
raheequlmakhtoom said:
please help me to implement this difference equation in MATLAB?

y[n]=x[n]-x[n-1];

matlab is not supportin -ve index...

Matlab doesn't like negative indexes as you seem to have noticed. But there are at least three easy ways to get around this.
Code:
clear

n = [0:100]; N = length(n);
x = cos(n/25);

% option 1
y1(1) = x(1) - cos(-1/25); %compute y(1) first
for i = 2:N
    y1(i) = x(i)-x(i-1);
end
figure;plot(n,y1,n,x)

% option 2
x0 = cos(-1/25); %define x(-1) outside loop
for i = 1:N
    y2(i) = x(i) - x0;
    x0 = x(i);
end
figure;plot(n,y2,n,x)

% option 3
n2 = [-1:99]; % use vectors instead of loop
xn = cos(n/25);
xn_minus_one = cos(n2/25);
y3 = xn-xn_minus_one;
figure;plot(n,y3,n,xn)
If you want to use a loop, you can loop over i=2:N and define y(1) outside of the loop.

Another option is to loop from i=1:N and define x(n-1) as x0 and update it at each step, that way you never try to acces x(-1).

If you don't want to use a loop, you can just create vectors for x[n] and x[n-1] over a big range of n, and just compute y by subtracting those long vectors.
 

Similar threads

  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 11 ·
Replies
11
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 0 ·
Replies
0
Views
2K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 32 ·
2
Replies
32
Views
5K
Replies
2
Views
2K