Announcement

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

  • Replacing part of a matrix without looping element by element

    Is there an efficient way to replace a sub-matrix within a matrix with another matrix? I know I can do it by looping element by element but this is not very efficient.
    Code:
    matrix A = J(20,4,.) // matrix of missing values
    matrix B = (1,2 \ 3,4 \ 5,6 \ 7,8 \ 9,10) // smaller matrix
    * and I want to do something like
    matrix A[10..14,2..3] = B
    * which gives
    * 14 invalid name
    * r(198);
    * I know I can do it element by element as follows but 
    * this is not very efficient with big matrices
    local rowcount = 1
    forval row = 10/14 {
         local colcount = 1
         forval col = 2/3 {
              matrix A[`row',`col'] = B[`rowcount',`colcount']
              local ++colcount
         }
         local ++rowcount
    }

  • #2
    Code:
    matrix A[10,2] = B
    http://www.stata.com/help.cgi?matrix+substitution

    Comment


    • #3
      Use Mata:

      Code:
       
      . mata 
      ------------------------------------------------- mata (type end to exit) --------------
      : A = J(20,4,.) 
      
      : B = (1,2 \ 3,4 \ 5,6 \ 7,8 \ 9,10) 
      
      : A[|10,1 \14, 2|] = B
      
      : A 
               1    2    3    4
           +---------------------+
         1 |   .    .    .    .  |
         2 |   .    .    .    .  |
         3 |   .    .    .    .  |
         4 |   .    .    .    .  |
         5 |   .    .    .    .  |
         6 |   .    .    .    .  |
         7 |   .    .    .    .  |
         8 |   .    .    .    .  |
         9 |   .    .    .    .  |
        10 |   1    2    .    .  |
        11 |   3    4    .    .  |
        12 |   5    6    .    .  |
        13 |   7    8    .    .  |
        14 |   9   10    .    .  |
        15 |   .    .    .    .  |
        16 |   .    .    .    .  |
        17 |   .    .    .    .  |
        18 |   .    .    .    .  |
        19 |   .    .    .    .  |
        20 |   .    .    .    .  |
           +---------------------+
      
      : end

      Comment


      • #4
        Thanks to both -- both solutions work.

        Comment


        • #5
          Amusingly, at least to me, I had forgotten about Stata's indulgence here, as pointed out by Christophe: I am now more used to Mata for this kind of thing.

          Comment


          • #6
            Thanks Nick. I thought for a moment I had missed something . That being said Mata is far more powerful when it comes to work with matrices

            Comment

            Working...
            X