0

My question is similar to this question about creating a lag variable. All I need to do is to implement this code in Matlab.

For instance let's say we have the following two vectors in Matlab:

ID =[2;2;2;2;3;3;5;5]
Pur=[0;1;2;3;1;2;4;5]
[ID,Pur]
ans =

 2     0
 2     1
 2     2
 2     3
 3     1
 3     2
 5     4
 5     5

I am looking for a way to lag the Purchase variable for each ID. To get something like:

ans =

2     NA
2     0
2     1
2     2
3     NA
3     1
5     NA
5     4

Would appreciate your help.

Community
  • 1
  • 1
AliCivil
  • 2,003
  • 6
  • 28
  • 43
  • Please show what you have tried, and what haven't work, and what confuses you. SO is not a coding service. Also, please expand a little on the characteristics of your data, for example, would the ID's would always be grouped and sorted, or could their locations be randomized? – Noel Segura Meraz Jan 18 '17 at 07:40

1 Answers1

0

Here is a way I found for this:

ID =[2;2;2;2;3;3;5;5]
Pur=[0;1;2;3;1;2;4;5]

[uniqueValues,~,uniqueIndex] = unique(ID)

n = numel(uniqueValues);  

shop_sess = accumarray(uniqueIndex,1);

shop_sess_cum=cumsum(shop_sess)
shop_sess_r=[0;shop_sess_cum2(1:length(shop_sess_cum)-1)]

lagPur=[]

for i=1:n
shop_sess_r_i=shop_sess_r(i)    
shop_sess_i=shop_sess_cum(i)
temp=Pur(shop_sess_r_i+1:shop_sess_i)
lagtemp=lagmatrix(temp,1)
lagPur=[lagPur;lagtemp]
end
AliCivil
  • 2,003
  • 6
  • 28
  • 43