This idea is probably well known to serious Mata programmers, but I've recently come across what appears to be a valuable (valuable to me, at least) use of pointer matrixes. Specifically, when defining a function one might wish to return a variety of results of different types and dimensions. Using a pointer matrix to store these results and then return them as a function's return seems generally workable. Here's a simple example
Code:
capture mata mata drop returnpointer()
mata
function returnpointer() {
pointer matrix p
string matrix ss,ls
real matrix sr,lr
p=J(4,1,NULL)
ss="a","b"
ls="a","b","c"
sr=1,2
lr=1,2,3,4
p[1]=&ss
p[2]=&ls
p[3]=&sr
p[4]=&lr
return(p)
}
for (j=1;j<=4;j++) {
*returnpointer()[j]
}
end
which gives this output
Code:
:
: for (j=1;j<=4;j++) {
> *returnpointer()[j]
> }
1 2
+---------+
1 | a b |
+---------+
1 2 3
+-------------+
1 | a b c |
+-------------+
1 2
+---------+
1 | 1 2 |
+---------+
1 2 3 4
+-----------------+
1 | 1 2 3 4 |
+-----------------+
:
What I'm wondering is whether the pointer experts among you see any obvious concerns with using such an approach OR whether there are more-straightforward strategies that would accomplish the same objective. Thanks in advance for any wisdom you might pass along.
0 Response to Returning pointer matrixes in functions
Post a Comment