1. You dont have to write a loop to get difference values. Just do diff(D). Or, before you do rec2_Wopt(1) = rec2_Wopt(1) + sum(RecP), create a D2(count,:) = rec2_Wopt(1)/Trial (not sure if I understood what you are doing, so check it. The point is, just save the D vector before you do a cumulative sum inside the loop).
2.You will have to wrap the entire code inside another loop and need to create a 3-dimensional matrix for D, where, in the third dimension you will store the D matrix at every iteration. Then, you will be doing D(count,:,iter) = ... where iter runs from 1:20000
Preallocate memory for D if you use such big loops. Also check if loops are avoidable and if you can do it by vector ops.