I am trying to produce a dataset that includes the autocorrelations of a variable (ret) across groups (portfolio). I am able to report the first autocorrelation(ret,lag_ret1) for each portfolio, but I can not figure out how to loop through and save the 2nd (ret, lag_ret2) and 3rd (ret, lag_ret3) autocorrelation for each portfolio.
Ultimately, I want to sum up all three correlation coefficients. So if the matrix methodology is not the most efficient way, I am open to other options.

Code:
matrix corre = J(3,3,0)
matrix list corre

forvalues port=1/3{
forvalues lag=1/3{
correlate ret lag_ret`lag' if portfolio ==`port'
matrix c=r(C)
matrix corre[`lag',`port']= c[`lag'+1,1]
}
}
matrix list corre
Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input float portfolio double ret float(lag_ret1 lag_ret2 lag_ret3)
1  .0023099415536437717 -.00009128346   -.001888566  -.0013676324
1 -.0005077351815998554   .0023099415 -.00009128346   -.001888566
1 -.0011798939152530073  -.0005077352   .0023099415 -.00009128346
1  .0018680473880964184   -.001179894  -.0005077352   .0023099415
1  .0052912740931999915   .0018680474   -.001179894  -.0005077352
1  -.002362792730488092    .005291274   .0018680474   -.001179894
1  -.004439577525402656   -.002362793    .005291274   .0018680474
1   .011633304806676608  -.0044395775   -.002362793    .005291274
2   .010083204463551768    .009573128    -.00733168    -.00981641
2  .0029652350642756235    .010083204    .009573128    -.00733168
2   .002781096110813135    .002965235    .010083204    .009573128
2 -.0004845770619188746    .002781096    .002965235    .010083204
2   .009512511099169611  -.0004845771    .002781096    .002965235
2 -.0031710873696614394     .00951251  -.0004845771    .002781096
2  .0022258799652889617  -.0031710875     .00951251  -.0004845771
2   .010312552598198174     .00222588  -.0031710875     .00951251
3  .0014073778989679012    .005959528   -.007621187  -.0040159286
3   .014511975238374511    .001407378    .005959528   -.007621187
3  -.014570034809472146    .014511975    .001407378    .005959528
3   .011700462176626132   -.014570035    .014511975    .001407378
3 -.0024378968148746276    .011700463   -.014570035    .014511975
3 -.0025385521429901322   -.002437897    .011700463   -.014570035
3  -.004463553329410612   -.002538552   -.002437897    .011700463
3    .01900731705770385  -.0044635534   -.002538552   -.002437897
end