Announcement

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

  • Extract an element from a structure?

    Dear all,
    I write a function with the return of a structure. How can I extract the elements of the structure in another function? See the example below. Function aaa returns a struct my. I use function aaa in function bbb, and put its return in q. Then I want to extract the element a of structure q and store it in ccc. When I run the code, Stata reports errors as follows. Is there any way to extract an element from a structure?



    ------------------------------------------
    mata mata clear
    mata

    struct mypoint {
    real vector a
    real vector b
    }
    end

    mata
    function aaa(real vector a, real vector b)
    {
    struct mypoint scalar my
    my.a=b
    my.b=a
    return(my)
    }
    end

    mata
    function bbb(real vector a, real vector b)

    {
    q=aaa(a,b)
    ccc=q.a
    return(ccc)
    }

    end


    --------------------------------------

    : function bbb(real vector a, real vector b)
    >
    > {
    > q=aaa(a,b)
    > ccc=q.a
    type mismatch: exp.exp: transmorphic found where struct expected
    r(3000);

    : return(ccc)
    'return' found where almost anything else expected
    r(3000);

    : }
    expression invalid
    r(3000);
    Last edited by Caike Du; 25 Aug 2017, 04:05.

  • #2
    Try putting
    Code:
    struct mypoint scalar q
    just before the line
    Code:
    q = aaa(a, b)
    .

    Actually, I recommend explicitly declaring all of your variables (and function return datatypes) as a habit. Use
    Code:
    mata set matastrict on
    to help with that.

    Comment


    • #3
      Originally posted by Joseph Coveney View Post
      Try putting
      Code:
      struct mypoint scalar q
      just before the line
      Code:
      q = aaa(a, b)
      .

      Actually, I recommend explicitly declaring all of your variables (and function return datatypes) as a habit. Use
      Code:
      mata set matastrict on
      to help with that.
      It works. Thanks very much!

      Comment

      Working...
      X