Implementing Difference Equation in MATLAB

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 6K views
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.