I use matrix list
to show a matrix P
that I have in a program:
P[1,6]
c1 c2 c3 c4 c5 c6
r1 0 0 0 0 0 0
I expect the el()
function to return the i,j
element of my matrix P
and I am trying to display
this value (i.e. to print "0") using:
noi: di el(P,1,1)
However, Stata 15.1 comes back at me with:
- noi: di el(P,1,1)
type mismatch
Why is this happening?
EDIT:
Reduced to a simple program:
program define MyProgram
matrix P = J(1,6,0)
noi: matrix list P
noi: di el(P,1,1)
end
And the resulting output:
MyProgram
P[1,6]
c1 c2 c3 c4 c5 c6
r1 0 0 0 0 0 0
type mismatch
r(109);
As i said in my comment, you did not tell us that this was part of an ado
file. Sometimes error messages like the one you report arise from conflicts between variables with the same names.
At first, this appears to be a bug:
. clear
. set obs 1
number of observations (_N) was 0, now 1
.
. generate P = 0
.
. program define MyProgram
1. matrix P = J(1,6,0)
2. noi matrix list P
3. noi di el(P,1,1)
4. end
.
. MyProgram
P[1,6]
c1 c2 c3 c4 c5 c6
r1 0 0 0 0 0 0
type mismatch
r(109);
Indeed, if you get rid of the variable P
, it works as expected:
. drop P
.
. MyProgram
P[1,6]
c1 c2 c3 c4 c5 c6
r1 0 0 0 0 0 0
0
However, appearances can be deceiving. As the Stata manual states:
"...A matrix might have the same name as a variable in the dataset, and if it does, Stata might appear confused when evaluating an expression (an exp). When the names conflict, Stata uses the rule that it always takes the data-variable interpretation..."
Thus, when evaluating expressions, one must override this behaviour by explicitly telling Stata that it is dealing with a matrix. This can be done using the matrix()
function.
In this case, line 3 in MyProgram
should change to:
noi: di el(matrix(P),1,1)