Announcement

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

  • Problem with asarray versus pointer

    Hi Statalists

    When I was working with the storage of matrices of different length, I encountered a problem with modifying the content of the matrix generated by asarray. Let take a look at the below example to see my problem.
    Code:
    A=asarray_create("real",1)
    asarray(A,1,J(3,1,1))
    asarray(A,1)[1,1]
    asarray(A,1)[1,1] = 4
    These codes are simple that I have created an 3D array called A and store a (3x1) colvector of ones for the first array. Later, I want to modify the first element of that vector to 4 by typing asarray(A,1)[1,1] = 4 and Mata returned me an error saying "Invalid subscripted lval". This is strange to me because when I typed asarray(A,1)[1,1], Mata understands correctly that I want to refer the first element of the first matrix of A, which is one.

    I have to use pointer as a workaround for my purpose and it performed well.
    Code:
    p = &J(3,1,1)
    (*p)[1,1] = 4 
    (*p)
    Can anyone explain why the first one did not work as I expected. To my limited knowledge, thing created by asarray_create is an array and that array should have the similar subscripting mechanism like the normal one. Pointer as in the second way is the address but if thing where that address refers to is array, then the whole thing (*pointer) is understood by Mata as the array.

    Thank you

  • #2
    No need for pointers. All that is necessary is that you clarify the order of operations with parentheses: replace asarray(A,1)[1,1] = 4 with (asarray(A,1))[1,1] = 4 and it works

    Code:
    . mata:
    ------------------------------------------------- mata (type end to exit) -------------------------------------------------
    : A=asarray_create("real",1)
    
    : asarray(A,1,J(3,1,1))
    
    : asarray(A,1)[1,1]
      1
    
    : (asarray(A,1))[1,1] = 4
    
    : asarray(A,1)
           1
        +-----+
      1 |  4  |
      2 |  1  |
      3 |  1  |
        +-----+
    
    : end
    Last edited by Maarten Buis; 19 Jun 2023, 02:28.
    ---------------------------------
    Maarten L. Buis
    University of Konstanz
    Department of history and sociology
    box 40
    78457 Konstanz
    Germany
    http://www.maartenbuis.nl
    ---------------------------------

    Comment


    • #3
      Thank you for your answer. It worked. I did not think of the use of parentheses for asarray.

      Comment

      Working...
      X