Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Multiply variables by a vector

    Hi experts,

    I have a data set that contains 10 variables and 10000 observations. I have a 10X1 vector, which I save as matrix B. Is there a command that can help me multiply the 10000 X 10 dataset by the 10 X 1 vector B? It would be like the multiplication of matrix 10000 x 10 by vector 10 x 1, and I want the product, i.e. a new vector 10000 x 1, to be a new variable for the 10000 observations.
    Last edited by shem shen; 23 Oct 2018, 19:53.

  • #2
    You could probably do the multiplication in Stata but Mata is preferable for larger matrices.

    Code:
    clear
    matrix B= J(10,1,0.5)
    
    set obs 10000
    set seed 2018
    forvalues i=1/10{
    gen var`i'= runiformint(1, 100)
    }
    
    mata
    D= st_data(., .)
    B= st_matrix("B")
    DB= D*B
    st_matrix("DB", DB)
    end
    
    *Save the matrix as a dataset
    svmat DB
    Result:

    Code:
    . list DB1 in 1/10, clean
    
             DB1  
      1.   283.5  
      2.     321  
      3.     197  
      4.   276.5  
      5.     310  
      6.     299  
      7.   338.5  
      8.   316.5  
      9.   255.5  
     10.     299

    Comment


    • #3
      Andrew Musau


      Good solution, but I'd change two things: use st_view to avoid copying data, and preallocate the result variable to simply use st_store.

      Code:
      clear
      matrix B=J(10,1,0.5)
      
      set obs 10000
      set seed 2018
      forvalues i=1/10 {
          gen var`i'=runiformint(1, 100)
      }
      
      gen result=.
      mata
      st_view(D=., ., "var*")
      B = st_matrix("B")
      st_store(., "result", D*B)
      end

      Comment


      • #4
        Thanks Jean-Claude Arbaut. I am a Mata novice, so it's great to learn some more efficient coding from you,

        Comment


        • #5
          Thank you Andrew and Jean-Claude for your quick reply! Problem solved!

          Comment

          Working...
          X