% Written by: Daniel Llamocca (2013)
% Combination of Time shift and time scale for Discrete-Time Signals:
  clear all; close all ; clc;

% Generating vector of samples:
  n = -40:40; % [-40 -19.... 40]

% Creating the input signal x[n]:
  x = sin(n/10); % 'n/10' instead of 'n' already explained
  % we have x[n] = (sin(-40/10) sin(-39/10) sin(-38/10) ... sin(40/10))  
  %   for     n  =      -40          -39        -38     ...     40

% Recall: shifting and scaling are applied over the independent variable 'n'  
  
% Time shifting:  
% We have x[n], now we want y[n] = x[n - m]
% In x[n] = sin(n/10), 'n' is replaced by 'n-m' --> y[n] = sin((n-m)/10)
  m = 10; % 'm' samples
  ya = sin((n - m)/10);
  
% Time scaling:  
  k = -2; % k = 2; k = 0.5, k = -0.5
  yb = sin((n*k/10)); % 'n' is replaced by 'n*k'

% Time shifting + time scaling (this operation is NOT commutative)
% y[n] = x[k*n - m]
  m = 10; k = -2;
  % Time shifting: x[n] --> x[n-m] = sin((n-m)/10)
  %                          'n' is replaced by 'n-m'
  % Time scaling: x[n-m] --> x[k*n-m] = sin((k*n-m)/10)
  %                           'n' is replaced by n*k
  yc = sin((n*k-m)/10);
  
% Time scaling + time shifting:  
% y[n] = x[k*(n-m)]
  % Time scaling: x[n] --> x[k*n] = sin((k*n)/10)
  %                           'n' is replaced by n*k
  % Time shifting: x[k*n] --> x[k*(n-m)] = sin((k*(n-m))/10)
  %                          'n' is replaced by 'n-m'
  
  yd = sin((k*(n-m))/10); % As it violated the 'precedence rule', this is
                          % NOT the signal we wanted.

% 'yc' is NOT equal to 'yd' --> x[k*n - m] ~= x[k*(n-m)]

% Quick verification
% y[n] = x[k*n - m]; y[0] = x[-m], y(m/k) = x[0]
% This is only true for y[n] = x[k*n - m] = ya

  figure; stem (n,x,'b.'); title ('x[n]'); grid on;
  figure; stem (n,ya,'r.'); title ('Shift: x[n-m]'); grid on;
  figure; stem (n,yb,'g.'); title ('Scale: x[k*n]'); grid on;
  figure; stem (n,yc,'k.'); title ('Shift + scale: x[k*n - m]'); grid on; % this is the CORRECT signal
  figure; stem (n,yd,'k.'); title ('Scale + shift: x[k*(n-m)]'); grid on; % this is the wrong signal
  