Announcement

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

  • mata function and loading data from excel

    Hello,
    This is one of my first attempt to create a mata function... And this is also my first post here.
    I have several xlsx files with data from 2000 to 2014. I am doing some mata operations from these different sets. I am stuck at the very beginning of my code... As I cannot create a function that returns the matrix I want:

    Code:
    mata: mata drop test()
    mata
    real matrix test(scalar year)  //the output will be a matrix so I type "real matrix"
    {
    real matrix Z 
    real scalar N, K, I, C
    N = 42
    K = 20
    I = 2
    C = 5
    b=xl() // excel file loaded tool
    b.load_book("2014_m2.xlsx") // i identify the workbook from where i want to import 
    b.set_sheet("sheet1") // i identify the spreadsheet
    Z=b.get_number((4,4+N*K*I-1),(4,4+N*K*I-1)) //import the matrix
    return(Z)
    }
    end
    mata: test(2014)
    However, the code returns the following error:
    type mismatch: exp.exp: transmorphic found where struct expected
    r(3000);
    just after b.load_book("2014_m2.xlsx")
    Code:
    : real matrix test(scalar year) 
    > {
    > real matrix Z
    > real scalar N, K, I, C
    > N = 42
    > K = 20
    > I = 2
    > C = 5
    > b=xl()
    > b.load_book("2014_m2.xlsx")
    type mismatch:  exp.exp:  transmorphic found where struct expected
    r(3000);

    I do not understand what I am doing wrong here... When I try to directly import the data, it works perfectly but as soon as I introduce these peaces of code in a matrix... Error! I would appreciate a lot some guidances.

    Thank you very much,

    Charles.

  • #2
    I get that error often, it took me a while to understand...

    Anyways, you are doing two things wrong:

    1. make your second line "mata:" instead of "mata". Note the colon!!!

    2. You are declaring every variable except for b. Add a declaration for b and it should work:

    class xl scalar b

    (The error occurs because when b is not declared, stata assumes is of type transmorphic. But then when you say b.load_book it thinks it's a structure (not even a class) and complains. I get why the error occurs, and it kinda sorta makes sense, but still annoying)

    Comment


    • #3
      Dear Sergio,
      I just tested it and indeed it worked perfectly well. Thank you very much.

      Charles

      Comment

      Working...
      X