Announcement

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

  • Declaration for an unknown number of variables

    Hi, I am recently writing a function in Mata.
    In the function, I have to first declare a set of variables.
    However, the problem is that the number of variables depends on the data I will use.

    For example, if we use an imaginary data, say dt1, then we have to write
    Code:
    : void my_fun() {
            real colvector var1, var2, var3
            .
            .
            .
    }
    But, if we use another imaginary data set, say dt2, then we have to specify
    Code:
    : void my_fun() {
            real colvector var1, var2, var3, var4, var5, var6, var7
            .
            .
            .
    }
    In addition, we cannot predict what data will be used between dt1 and dt2, but we can know whether dt1 is being used or dt2 is being used before the function is executed.
    That is, we can add a diagnostic tool, for instance,
    Code:
    if (max(my_var) == 3) {
            printf("this is dt1")
    } else if (max(my_var) == 7) {
            printf("this is dt2")
    }
    In this case, how can I declare the variable flexibly?

  • #2
    Because the variables in your example are all real colvectors, you could declare a single real matrix.
    Code:
    void function my_function() {
        real matrix V
        V = J(<vector length>, st_nvars(), .)
        . . .
    }
    It would be awkward if the individual vector lengths differed, though. And you'd have to be careful that you're addressing the correct column of it when you go to use it later.

    As an alternative, maybe you could put each of your variables in some kind of container, such as a pointer, struct or object, that itself can be organized into a variable-length vector. Among those, perhaps the easiest is a struct, so something along the following lines.
    Code:
    struct ColVectorVar {
        real colvector var
    }
    
    void function my_function() {
    
        struct ColVectorVar vector V
        V = ColVectorVar(st_nvar())
    
        V[1].var . . . // instead of var1
        V[2].var . . . // instead of var2 etc.
        . . .
    }
    Also, consider that your function is trying to do too much, and that it might be better to break it up into two or more cooperating functions, each with a more manageable task that no longer requires having to declare an unknown numbers of variables.

    Comment


    • #3
      Joseph Coveney Thank you for the kind answer. I think, as you said, using pointer could be the best option in my specific problem. Thank you so much!

      Comment

      Working...
      X