# st: Re: How can I loop a FOR command across columns of a matrix

 From Kit Baum To statalist@hsphsun2.harvard.edu Subject st: Re: How can I loop a FOR command across columns of a matrix Date Fri, 5 Jun 2009 06:56:34 -0400

```<>
Nathan said

I have a 2 x N matrix, such as the following...

2  3  5  10  6
1  2  8  13  6

I would like to write a loop, such as foreach or forvalues, that will
take the first and second element of each column, and use them for
some operation, and then move on to subsequent columns.

```
Given that these are matrices, there is no need for an explicit loop in either Stata's matrix language or Mata (although it would certainly be easier in Mata).
```
mat f = (2,3,4,10,6\1,2,8,13,6)
mat a = f[1,1..5]'
mat b = f[2,1..5]'
// ssc install matodd
qui matewm a b c
mat r = c'
mat list r

```
You could avoid hardcoding 5 in there by using the matrix function colsof(f).
```
Kit Baum   |   Boston College Economics & DIW Berlin   |   http://ideas.repec.org/e/pba1.html
```
An Introduction to Stata Programming | http://www.stata-press.com/books/isp.html
```   An Introduction to Modern Econometrics Using Stata  |   http://www.stata-press.com/books/imeus.html

On Jun 5, 2009, at 02:33 , statalist-digest wrote:

```
```I have a 2 x N matrix, such as the following...

2  3  5  10  6
1  2  8  13  6

I would like to write a loop, such as foreach or forvalues, that will
take the first and second element of each column, and use them for
some operation, and then move on to subsequent columns.
```
```
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
```