Define three row vectors, A = (1,2,3) B = (10,20,30,40) C = (100,200,300,400,500)
I want to construct a new matrix D which will be a have 3x4x5 = 60 elements and contains the averages of these elements as illustrated below:
D =
(1+10+100)/3, (1+10+200)/3,…, (1+10+ 500)/3 \
(1+20+100)/3, (1+20+200)/3,…, (1+20+ 500)/3 \
(1+30+100)/3, (1+30+200)/3,…, (1+30+ 500)/3 \
(1+40+100)/3, (2+40+200)/3,…, (2+40+ 500)/3 \
(2+10+100)/3, (2+10+200)/3,…, (2+10+ 500)/3 \
(2+20+100)/3, (2+20+200)/3,…, (2+20+ 500)/3 \
(2+30+100)/3, (2+30+200)/3,…, (2+30+ 500)/3 \
(2+40+100)/3, (2+40+200)/3,…, (2+40+ 500)/3 \
(3+10+100)/3, (3+10+200)/3,…, (3+10+ 500)/3 \
(3+20+100)/3, (3+20+200)/3,…, (3+20+ 500)/3 \
(3+30+100)/3, (3+30+200)/3,…, (3+30+ 500)/3 \
(3+40+100)/3, (3+40+200)/3,…, (3+40+ 500)/3 \
The way it is set up in this example it will be a 12x5 matrix, but I am fine if it is a 1X60 vector or 60X1 vector.
How to do this efficiently in Mata? I am new to Mata and I had this running in Stata using multiple forval
loops (in this case, there would be 3 forval
loops). But this becomes very time consuming as I have up to 8 row vectors and about 120 elements in each of them.
I figured that I can use for
loops in Mata and it will be much faster, but I believe if I can do this as a matrix manipulation instead of using for
loops then it will be even faster. The problem is I am having a hard time visualizing how to write such a program (or if it's even possible) and any help would be highly appreciated.
120^8 = 4.300e+16
elements. Mata can hold a maximum of2147483647*2147483647 = 4.612e+18
elements, so you're within the theoretical limit. But memory requirements to hold your matrix (assuming the final result is a row vector) is approx.1*(120^8)*8 = 3.440e+17
bytes, which equal 320374965 Gigabytes. (Seehelp [M-1] limits
.) Am I missing something or am I doing the math incorrectly? This looks really difficult. – Roberto Ferrer