Announcement

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

  • Error in arithmetic operation when defining matrix elements

    Hello, I'm new to Mata, and would like to define each element of a large matrix by simple arithmetic operations and some conditional statements. However, I've been getting an error in the arithmetic operations. I don't seem to find a similar example elsewhere - it's possible that it's a simple omission on some basic declarations. Can someone help?

    I've copy-pasted a table of variables onto Stata, and used the following command to put into mata:

    putmata *, replace

    // this then made sure that mata got various vectors each named after a variable, e.g., tower[3] = 120 indicates that the 3rd element (observation) under the variable 'tower' is 120.

    mata:
    n = st_nobs() //gave the correct number of observations - so mata has got the vectors

    W = J(n,n,0) //here I defined a new n x n matrix (no errors)
    tower[3] //yields the exact entry in the 3rd observation under variable 'tower'

    //When I tried to copy-paste the following (and the copy-pasting technique of mine may also be a problem):

    for (i=1; i<=n; i++) {
    for (j=1; j<=n; i++) {
    if (tower[i] == tower[j] & i != j) {Wdrft[i,j] =1}
    }
    }

    I get the "invalid expression" error.
    Any suggestions on what I should do?

    Thank you so much for your help.




  • #2
    Originally posted by Terry Fan View Post
    for (i=1; i<=n; i++) {
    for (j=1; j<=n; i++) {
    if (tower[i] == tower[j] & i != j) {Wdrft[i,j] =1}
    }
    }

    I get the "invalid expression" error.
    Any suggestions on what I should do?
    Maybe change i to j in the inner loop. Also try removing the redundant open and closed braces before and after the assignment statement on the conditional line; otherwise, put the assignment statement on a separate line.
    Code:
    for (i=1; i<=n; i++) {
        for (j=1; j<=n; j++) {
            if (tower[i] == tower[j] & i != j) Wdrft[i,j] = 1
        }
    }
    
    // or
    
    for (i=1; i<=n; i++) {
        for (j=1; j<=n; j++) {
            if (tower[i] == tower[j] & i != j) {
                Wdrft[i,j] = 1
            }
        }
    }

    Comment

    Working...
    X