Alexis
Alexis

Reputation: 854

How to use loops with Mata

I want to implement a one-line command within a for loop in Mata. However, I get an error even with the most simple commands. Take the simple command to display a value:

mata: i = 2
mata: i^2
. 4

But if I try to put this squared variable command into a loop, thus:

mata: for (i=1; i<=3; i++) { i^2 }

I get the following result:

invalid expression
r(3000);

when I would expect to see something like:

. 1
. 4
. 9

What am I missing?

Upvotes: 0

Views: 4527

Answers (1)

Roberto Ferrer
Roberto Ferrer

Reputation: 11102

The manual for [M2] for states one-liners have no braces: for (exp1; exp2; exp3) stmt.

clear all
set more off

mata: for (i=1; i<=3; i++) i^2 

// invoke Mata mode
mata

for (i=1; i<=3; i++) {
    i^2 
}

// end Mata mode
end

stmt stands for statement.

Upvotes: 2

Related Questions