Dear all,
I'm running iteration in Mata until the difference between the sum of previous weight matrix and current weight matrix is close zero. Then, I want to stop the iteration and extract the weight matrix using
.
However, I don't want to write all the repeated process in my code chunk- I want to simplify this code.
.
That is, each diff becomes zero (or close to zero) I would like to stop the looping. For actual data, I did this 40 times, writing the same code 40 times.
Many thanks in advance!
Kind regards,
Kim
I'm running iteration in Mata until the difference between the sum of previous weight matrix and current weight matrix is close zero. Then, I want to stop the iteration and extract the weight matrix using
Code:
st_matrix("weight", weight)
However, I don't want to write all the repeated process in my code chunk- I want to simplify this code.
Code:
clear mata mata ind_cat = 0,1,1,0\0,1,1,0\1,0,1,0\0,1,0,1\1,0,0,1 weight = J(5,3,1) cons = 8,4,6,6\2,8,4,6\7,4,3,8 ind_agg = J(3,4,1) A=rows(ind_cat) B=rows(cons) C=cols(cons) weight = J(A,B,1) w1 = sum(weight) ind_agg = J(B,C,1) sum_ind_cat = colsum(ind_cat) mat_ind_cat= J(B,C,1) ind_agg0= sum_ind_cat:*mat_ind_cat ind_agg1=J(B,C,1) for (j=1;j<=B;j++) { for (i=1;i<=C;i++) { index= select( 1::rows(ind_cat) ,ind_cat[., i]) weight[index,j] = weight[index,j] * cons[j, i]/ ind_agg0[j,i] ind_agg1[j,] = colsum(ind_cat:*weight[,j]) weight[index,j] = weight[index,j]* cons[j , i] / ind_agg1[j,i] w2= sum(weight) } } weight = weight for (j=1;j<=B;j++) { for (i=1;i<=C;i++) { index= select( 1::rows(ind_cat) ,ind_cat[., i]) weight[index,j] = weight[index,j] * cons[j, i]/ ind_agg0[j,i] ind_agg1[j,] = colsum(ind_cat:*weight[,j]) weight[index,j] = weight[index,j]* cons[j , i] / ind_agg1[j,i] w3 = sum(weight) } } weight = weight //this is important for (j=1;j<=B;j++) { for (i=1;i<=C;i++) { index= select( 1::rows(ind_cat) ,ind_cat[., i]) weight[index,j] = weight[index,j] * cons[j, i]/ ind_agg0[j,i] ind_agg1[j,] = colsum(ind_cat:*weight[,j]) weight[index,j] = weight[index,j]* cons[j , i] / ind_agg1[j,i] w4 = sum(weight) } //weight1 = weight } weight = weight //this is important for (j=1;j<=B;j++) { for (i=1;i<=C;i++) { index= select( 1::rows(ind_cat) ,ind_cat[., i]) weight[index,j] = weight[index,j] * cons[j, i]/ ind_agg0[j,i] ind_agg1[j,] = colsum(ind_cat:*weight[,j]) weight[index,j] = weight[index,j]* cons[j , i] / ind_agg1[j,i] w5 = sum(weight) } } diff1 = w2 -w1 diff2 = w3- w2 diff3 = w4 - w3 diff4 = w5 - w4 diff1 diff2 diff3 diff4 end
That is, each diff becomes zero (or close to zero) I would like to stop the looping. For actual data, I did this 40 times, writing the same code 40 times.
Many thanks in advance!
Kind regards,
Kim
Comment