Chapter 9
Special functions in genr
9.1 Introduction
The genr command provides aflexible means of defining new variables. It is documented in the
Gretl Command Reference. Thischapter offersamore expansive discussionofsome ofthespecial
functionsavailableviagenr andsome ofthe finerpointsofthecommand.
9.2 Long-run variance
Asis wellknown,the variance ofthe averageofT randomvariables x
1
;x
2
;:::;x
T
withequalvari-
ance 
2
equals 
2
=T ifthe dataare uncorrelated. Inthiscase,the sample variance ofx
t
over the
samplesize provides aconsistentestimator.
If, however, there is serial correlation among the x
t
s, the variance of
¯
X  T 1
P
T
t1
x
t
must be
estimated differently. One ofthe most widelyused statistics for this purpose is anonparametric
kernelestimatorwiththe Bartlettkerneldefinedas
2
k T
1
TX k
tk
2
4
Xk
i k
w
i
x
t
¯
Xx
t i
¯
X
3
5
;
(9.1)
wheretheintegerkisknownasthewindowsizeandthew
i
termsaretheso-calledBartlettweights,
defined as w
i
 1 
jij
k1
. It can be shown that, for k large enough,
ˆ
!
2
k=T yields a consistent
estimatorofthevarianceof
¯
X.
Gretl implements this estimator by means of the function lrvar(), which takes two arguments:
theserieswhoselong-runvariancemustbe estimatedandthescalark. Ifkisnegative,thepopular
choiceT1=3 isused.
9.3 Cumulative densities and p-values
Thetwofunctionscdfandpvalueprovidecomplementarymeansofexaminingvaluesfromseveral
probabilitydistributions: thestandardnormal,Student’st,
2
,F,gamma,andbinomial. Thesyntax
ofthese functionsissetoutintheGretlCommandReference;here weexpandonsome subtleties.
The cumulative density function or CDF for a random variable is the integral of the variable’s
density from its lower limit (typically either  1 or 0) to any specified value x. The p-value (at
least theone-tailed, right-hand p-value as returned by the pvaluefunction)is the complementary
probability,theintegralfromx tothe upper limitofthedistribution,typically1.
Inprinciple, therefore, there isno needfortwo distinctfunctions: givenaCDFvaluep
0
youcould
easily find the corresponding p-value as 1 p
0
(or vice versa). In practice, with finite-precision
computer arithmetic, the two functions are not redundant. This requires alittle explanation. In
gretl, as in most statistical programs, floating point numbers are represented as “doubles” —
double-precisionvaluesthattypicallyhave astorage size ofeightbytesor 64 bits. Since there are
only so many bits available, only so many floating-point numbers canbe represented: doubles do
notmodeltherealline. Typicallydoublescanrepresentnumbersovertherange(roughly)1:7977
10308, butonlyto about15 digitsofprecision.
70
Convert pdf document to powerpoint - control SDK system:C# Create PDF from PowerPoint Library to convert pptx, ppt to PDF in C#.net, ASP.NET MVC, WinForms, WPF
Online C# Tutorial for Creating PDF from Microsoft PowerPoint Presentation
www.rasteredge.com
Convert pdf document to powerpoint - control SDK system:VB.NET Create PDF from PowerPoint Library to convert pptx, ppt to PDF in vb.net, ASP.NET MVC, WinForms, WPF
VB.NET Tutorial for Export PDF file from Microsoft Office PowerPoint
www.rasteredge.com
Chapter9. Specialfunctionsin genr
71
Suppose you’re interestedinthe lefttailofthe 
2
distributionwith 50 degrees of freedom: you’d
like to knowtheCDFvalue for x0:9. Take alookatthefollowinginteractive session:
? genr p1 = cdf(X, 50, 0.9)
Generated scalar p1 (ID 2) = 8.94977e-35
? genr p2 = pvalue(X, 50, 0.9)
Generated scalar p2 (ID 3) = 1
? genr test = 1 - p2
Generated scalar test (ID 4) = 0
The cdf functionhas producedan accurate value, but the pvalue function givesan answer of1,
fromwhichitisnotpossible toretrieve theanswerto the CDFquestion. Thismayseemsurprising
atfirst,butconsider:ifthevalueofp1aboveiscorrect,thenthecorrectvalueforp2is1 8:94977
10
35
. Butthere’s no way that value can be represented as a double: thatwould require over 30
digitsofprecision.
Of course this isan extreme example. If the x inquestion isnottoo far offinto one or other tail
ofthe distribution,the cdf andpvalue functionswillinfact produce complementaryanswers,as
shownbelow:
? genr p1 = cdf(X, 50, 30)
Generated scalar p1 (ID 2) = 0.0111648
? genr p2 = pvalue(X, 50, 30)
Generated scalar p2 (ID 3) = 0.988835
? genr test = 1 - p2
Generated scalar test (ID 4) = 0.0111648
Butthe moralisthatifyouwanttoexamineextreme values youshould be carefulinselecting the
functionyou need, inthe knowledge thatvaluesvery close to zero canbe representedas doubles
while values verycloseto 1cannot.
9.4 Retrieving internal variables
The genr command provides a means of retrieving various values calculated by the program in
the course ofestimatingmodelsor testinghypotheses. The variables that canbe retrievedinthis
way are listedintheGretl Command Reference; here we sayabitmoreaboutthespecialvariables
$testand$pvalue.
These variables hold, respectively, the value of the last test statistic calculated using an explicit
testing commandandthe p-value for thatteststatistic. If nosuchtesthas beenperformed atthe
time when these variables are referenced, theywillproduce the missing value code. The “explicit
testingcommands”thatwork inthiswayareasfollows: add (jointtestforthe significance ofvari-
ablesaddedtoamodel);adf(AugmentedDickey–Fullertest,seebelow);arch(testforARCH);chow
(Chowtestfor astructuralbreak); coeffsum(testforthe sumofspecifiedcoefficients);cusum (the
Harvey–Collier t-statistic); kpss (KPSS stationarity test, no p-value available); lmtest (see below);
meantest (test for difference of means); omit (joint test for the significance of variables omitted
froma model); reset (Ramsey’s RESET); restrict (generallinear restriction); runs (runs testfor
randomness); testuhat (test for normality of residual); and vartest (test for difference of vari-
ances). Inmost cases both a$test and a$pvalue are stored; the exceptionis the KPSStest, for
whichap-value isnotcurrentlyavailable.
Animportantpointtonoticeaboutthismechanismisthattheinternalvariables$testand$pvalue
areover-writteneachtime oneofthetestslistedaboveisperformed. Ifyouwanttoreferencethese
values,youmustdosoatthecorrectpointinthe sequenceofgretlcommands.
Arelatedpointisthatsomeofthetestcommandsgenerate,bydefault,morethanoneteststatistic
and p-value; inthesecasesonlythelastvaluesarestored. Togetproper controlover theretrieval
of values via$test and$pvalue youshould formulate the test command insuch awaythat the
resultisunambiguous. Thiscommentappliesinparticular tothe adfandlmtestcommands.
control SDK system:Online Convert PowerPoint to PDF file. Best free online export
try to make it as easy as possible to convert your PPTX C#.NET project, Microsoft Office like Word, Excel, and PowerPoint can be converted to PDF document.
www.rasteredge.com
control SDK system:RasterEdge XDoc.PowerPoint for .NET - SDK for PowerPoint Document
Convert. Convert PowerPoint to PDF. Convert PowerPoint to Png, Gif, Bitmap Convert PowerPoint to ODP/ ODP to PowerPoint. Document & Page Process.
www.rasteredge.com
Chapter9. Specialfunctionsin genr
72
 By default, the adf command generates three variants of the Dickey–Fuller test: one based
on aregressionincluding aconstant, one using aconstant and linear trend, andone using a
constantandaquadratic trend. Whenyouwishtoreference$testor$pvalueinconnection
with this command, you can control the variant that is recorded by using one of the flags
--nc,--c,--ct or --cttwithadf.
 By default, the lmtest command (which must follow an OLS regression) performs several
diagnostic tests on the regression in question. To control what is recorded in $test and
$pvalue youshould limitthe testusingoneofthe flags --logs, --autocorr, --squaresor
--white.
Asanaidinworkingwithvaluesretrievedusing$testand$pvalue,thenatureofthetesttowhich
thesevalues relateiswrittenintothedescriptive labelfor the generatedvariable. Youcanreadthe
labelforthevariableusingthelabelcommand(withjustoneargument,thenameofthe variable),
to check that you have retrievedthe right value. The following interactive sessionillustrates this
point.
? adf 4 x1 --c
Augmented Dickey-Fuller tests, order 4, for x1
sample size 59
unit-root null hypothesis: a = 1
test with constant
model: (1 - L)y = b0 + (a-1)*y(-1) + ... + e
estimated value of (a - 1): -0.216889
test statistic: t = -1.83491
asymptotic p-value 0.3638
P-values based on MacKinnon (JAE, 1996)
? genr pv = $pvalue
Generated scalar pv (ID 13) = 0.363844
? label pv
pv=Dickey-Fuller pvalue (scalar)
9.5 The discrete Fourier transform
ThediscreteFouriertransformcanbebestthoughtofasalinear,invertibletransformofacomplex
vector. Hence,ifxisann-dimensionalvectorwhose k-thelementisx
k
a
k
ib
k
,thenthe output
ofthe discreteFouriertransformisavectorfFx whosek-thelementis
f
k
nX 1
j0
e
i!j;k
x
j
where !j;k 2i
jk
n
. Since the transformationisinvertible, the vector x canbe recoveredfrom
fviathe so-calledinversetransform
x
k
1
n
nX 1
j0
e
i!j;k
f
j
:
The Fourier transform is used in many diverse situations on account of this key property: the
convolutionoftwovectorscanbeperformedefficientlybymultiplyingtheelementsoftheirFourier
transforms andinvertingthe result. If
z
k
Xn
j1
x
j
y
k j
;
then
FzFxFy:
control SDK system:VB.NET PDF Convert to HTML SDK: Convert PDF to html files in vb.
Embed zoom setting (fit page, fit width). Free library for .NET framework. Why do we need to convert PDF document to HTML webpage using VB.NET programming code?
www.rasteredge.com
control SDK system:C# PDF Convert to HTML SDK: Convert PDF to html files in C#.net
How to Use C#.NET Demo Code to Convert PDF Document to HTML5 Files in C#.NET Class. Add necessary references: RasterEdge.Imaging.Basic.dll.
www.rasteredge.com
Chapter9. Specialfunctionsin genr
73
Thatis,Fz
k
Fx
k
Fy
k
.
For computingthe Fourier transform,gretl usesthe external libraryfftw3: seeFrigoandJohnson
(2005). This guarantees extreme speed and accuracy. In fact, the CPU time needed to perform
thetransform is Onlogn for anyn. This is whythe arrayofnumericaltechniquesemployed in
fftw3iscommonlyknownastheFast Fourier Transform.
Gretlprovidestwomatrixfunctions
1
forperformingtheFouriertransformanditsinverse: fftand
ffti. In fact, gretl’s implementation of the Fourier transformis somewhat more specialized: the
inputtothefftfunctionisunderstoodtobereal. Conversely,fftitakesacomplexargumentand
delivers arealresult. For example:
x1 = { 1 ; 2 ; 3 }
# perform the transform
f = fft(a)
# perform the inverse transform
x2 = ffti(f)
yields
x
1
2
6
6
4
1
2
3
3
7
7
5
f 
2
6
6
4
6
0
1:5
0:866
1:5  0:866
3
7
7
5
x
2
2
6
6
4
1
2
3
3
7
7
5
where thefirstcolumn off holds therealpartandthe secondholdsthe complexpart. Ingeneral,
if the inputto fft has n columns, the output has 2n columns, where the realpartsare stored in
the odd columns andthe complex parts in the even ones. Should itbe necessaryto compute the
Fourier transform on several vectors with the same number of elements, it is numerically more
efficienttogrouptheminto amatrixratherthaninvokingfftforeachvector separately.
Asanexample,consider themultiplicationoftwopolynomials:
ax 
10:5x
bx 
10:3x 0:8x
2
cxaxbx 
10:8x 0:65x
2
0:4x
3
The coefficients of the polynomial cx are the convolution of the coefficients of ax andbx;
thefollowinggretlcodefragmentillustrateshowtocompute thecoefficients ofcx:
# define the two polynomials
a = { 1, 0.5, 0, 0 }’
b = { 1, 0.3, -0.8, 0 }’
# perform the transforms
fa = fft(a)
fb = fft(b)
# complex-multiply the two transforms
fc = cmult(fa, fb)
# compute the coefficients of c via the inverse transform
c = ffti(fc)
Maximum efficiency would have been achieved bygroupinga and b into a matrix. The computa-
tionaladvantageis so littlein this case thatthe exerciseis abit silly,butthe followingalternative
maybepreferableforalarge number ofrows/columns:
# define the two polynomials
a = { 1 ; 0.5; 0 ; 0 }
b = { 1 ; 0.3 ; -0.8 ; 0 }
1
Seechapter15.
control SDK system:VB.NET PDF Convert to Word SDK: Convert PDF to Word library in vb.
Convert PDF document to DOC and DOCX formats in Visual Basic .NET project. using RasterEdge.XDoc.PDF; Convert PDF to Word Document in VB.NET Demo Code.
www.rasteredge.com
control SDK system:C# PDF Converter Library SDK to convert PDF to other file formats
NET. How to Use C#.NET XDoc.PDF Component to Convert PDF Document to Various Document and Image Forms in Visual C# .NET Application.
www.rasteredge.com
Chapter9. Specialfunctionsin genr
74
# perform the transforms jointly
f = fft(a ~ b)
# complex-multiply the two transforms
fc = cmult(f[,1:2], f[,3:4])
# compute the coefficients of c via the inverse transform
c = ffti(fc)
Traditionally, the Fouriertransformineconometrics has beenmostlyused in time-series analysis,
the periodogram being the best known example. Example script9.1 shows how to compute the
periodogramofatime seriesviathefft function.
Example9.1:PeriodogramviatheFouriertransform
nulldata 50
# generate an AR(1) process
series e = normal()
series x = 0
x = 0.9*x(-1) + e
# compute the periodogram
scale = 2*pi*$nobs
X = { x }
F = fft(X)
S = sumr(F.^2)
S = S[2:($nobs/2)+1]/scale
omega = seq(1,($nobs/2))’ .* (2*pi/$nobs)
omega = omega ~ S
# compare the built-in command
pergm x
print omega
control SDK system:VB.NET PDF Convert to Jpeg SDK: Convert PDF to JPEG images in vb.
Convert Word to PDF; Convert Excel to PDF; Convert PowerPoint to PDF; Convert Image to PDF; Convert Jpeg to PDF; Merge PDF Files; Split PDF Document; Remove Password
www.rasteredge.com
control SDK system:VB.NET PDF Convert to Tiff SDK: Convert PDF to tiff images in vb.
VB.NET PDF - Convert PDF to TIFF Using VB in VB.NET. Free VB.NET Guide to Render and Convert PDF Document to TIFF in Visual Basic Class.
www.rasteredge.com
Chapter 10
Gretl data types
10.1 Introduction
Gretloffersthe followingdatatypes:
scalar
holds asinglenumericalvalue
series
holdsnnumericalvalues,wherenisthenumberofobservationsinthe current
dataset
matrix
holds arectangulararrayofnumericalvalues,ofanydimensions
list
holds theID numbersofasetofseries
string
holds anarrayofcharacters
bundle
holds avariable numberofobjectsofvarioustypes
array
holds avariable numberofobjectsofagiventype
The“numericalvalues” mentionedabove are alldouble-precisionfloatingpointnumbers.
In this chapter we give a run-down of the basic characteristics of each of these types and also
explaintheir“life cycle” (creation,modificationanddestruction). The listandmatrixtypes, whose
usesare relativelycomplex,are discussedatgreater lengthinthe followingtwochapters.
10.2 Series
Webeginwiththeseriestype,whichistheoldestandinasensethemostbasictypeingretl. When
youopenadatafile inthe gretlGUI, whatyousee inthe mainwindoware the ID numbers, names
(anddescriptions,ifavailable)ofthe seriesreadfromthe file. Allthe seriesexistingatanypointin
agretlsessionare ofthe samelength, althoughsome mayhave missing values. The variables that
canbe added viathe itemsunder the Addmenuinthe mainwindow(logs,squaresandso on)are
alsoseries.
For a gretl session to contain any series, a common series length must be established. This is
usuallyachieved by opening a data file, or importing aseries from adatabase, in which case the
length is set by the firstimport. Butone canalso use the nulldata command, which takes as it
single argumentthe desiredlength,apositive integer.
Eachserieshasthese basicattributes: anIDnumber,aname,andofcourse nnumericalvalues. In
additionaseriesmayhaveadescription(whichisshowninthemainwindowandisalsoaccessible
viathe labelscommand),a“displayname”foruseingraphs, arecordofthecompactionmethod
usedinreducingthevariable’sfrequency(fortime-seriesdataonly)andaflagmarkingthevariable
as discrete. Theseattributescanbe editedinthe GUI bychoosingEdit Attributes (eitherunder the
Variablemenuorviaright-click),orbymeansofthesetinfocommand.
Inthe contextofmostcommandsyouareabletoreference seriesbynameorbyIDnumberasyou
wish. Themainexceptionisthedefinitionormodificationofvariablesviaaformula;hereyoumust
usenamessinceID numberswouldgetconfusedwithnumericalconstants.
NotethatseriesIDnumbersarealwaysconsecutive,andtheIDnumberforagivenserieswillchange
if you delete a lower-numberedseries. In some contexts, where gretl is liable to get confused by
suchchanges,deletionoflow-numberedseries is disallowed.
75
control SDK system:C# powerpoint - Convert PowerPoint to PDF in C#.NET
C# Demo: Convert PowerPoint to PDF Document. Add references: RasterEdge.Imaging. Basic.dll. RasterEdge.XDoc.Office.Inner.Common.dll. RasterEdge.Imaging.Drawing.dll
www.rasteredge.com
Chapter10. Gretl datatypes
76
Discreteseries
Itispossible tomarkvariablesoftheseriestype asdiscrete. Themeaningandusesofthisfacility
are explainedinchapter11.
10.3 Scalars
The scalar type is relatively simple: just aconvenientnamedholder for asingle numerical value.
Scalars have none of the additional attributes pertaining to series, do not have ID numbers, and
must be referenced by name. A common use of scalar variables is to record information made
available by gretl commands for further processing, as in scalar s2 = $sigmaˆ2 to record the
square ofthe standarderrorofthe regressionfollowinganestimationcommandsuchasols.
Youcandefineandwork withscalarsingretlwithouthavinganydatasetinplace.
Inthe gretlGUI, scalar variables can be inspectedand their values edited viathe “Icon view” (see
theViewmenuinthe mainwindow).
10.4 Matrices
Matricesingretlwork muchasinothermathematicalsoftware (e.g. MATLAB,Octave). Like scalars
they have no ID numbers and must be referenced by name, and they can be used without any
dataset inplace. Matrixindexing is 1-based: the top-left elementofmatrix A is A[1,1]. Matrices
are discussed at length in chapter 15; advanced users of gretl will want to study this chapter in
detail.
Matriceshavetwooptionalattributebeyondtheirnumericalcontent: theymayhavecolumnand/or
row names attached; these are displayed when the matrix is printed. See the colnames and
rownamesfunctionsfordetails.
InthegretlGUI,matricescanbe inspected,analysedandeditedviathe Icon view itemunder the
View menuinthemainwindow: eachcurrentlydefinedmatrixisrepresentedbyanicon.
10.5 Lists
As withmatrices, lists meritan explicationof their own(see chapter14). Briefly, namedlists can
(and should!) be used to make command scripts less verbose and repetitious, and more easily
modifiable. SincelistsareinfactlistsofseriesID numberstheycanbeusedonlywhenadatasetis
inplace.
InthegretlGUI,namedlistscanbe inspectedandeditedundertheDatamenuinthemainwindow,
viatheitemDefineoreditlist.
10.6 Strings
String variables may be used for labeling, or for constructing commands. They are discussed in
chapter14. Theymustbe referencedbyname;theycanbe definedinthe absenceofadataset.
Suchvariablescanbe createdandmodifiedviathecommand-lineinthe gretlconsoleorviascript;
thereisno meansofediting themviathe gretlGUI.
10.7 Bundles
Abundle is acontainer or wrapper for various sorts of objects—specifically, scalars, series, ma-
trices, strings, arrays andbundles. (Yes, abundle cancontainother bundles). A bundle takes the
formofa hashtable or associative array: eachitemplaced inthe bundle is associated with akey
Chapter10. Gretl datatypes
77
whichcanusedto retrieve itsubsequently. Webeginbyexplainingthe mechanicsofbundles then
offer somethoughtsonwhattheyaregoodfor.
Touseabundleyoufirsteither“declare” it,asin
bundle foo
or defineanemptybundle usingthenull keyword:
bundle foo = null
These two formulations are basically equivalent, in that they both create an empty bundle. The
difference is that the second variant may be reused—if a bundle named foo already exists the
effectisto emptyit—whilethefirstmayonlybeusedonceinagivengretlsession;itisanerrorto
declare avariable thatalreadyexists.
Toaddanobjecttoabundleyouassigntoacompoundleft-handvalue: thenameofthebundlefol-
lowedbythe key. Twoformsofsyntaxare acceptableinthiscontext. The currentlyrecommended
syntaxisbundlename.key;thatis,thenameofthebundlefollowedbyadot,thenthekey. Boththe
bundle nameandthekeymustbe validgretlidentifiers.1 Forexample,the statement
foo.matrix1 = m
addsanobject called m (presumablyamatrix) to bundle foounder the keymatrix1. The original
syntax(andthe onlyformsupportedprior toversion1.9.12 ofgretl)requiresthatthe keybe given
as aquotedstringliteralenclosedinsquarebrackets,asin
foo["matrix1"] = m
While the old syntax is still acceptable, we suggest that it be used only if you wish to preserve
compatibilitywithgretlversion1.9.11(December,2012)orearlier.
Togetanitemoutofabundle,againuse thenameofthebundle followedbythe key,asin
matrix bm = foo.matrix1
# or using the old notation
matrix bm = foo["matrix1"]
Notethatthekeyidentifyinganobjectwithinagivenbundle is necessarilyunique. Ifyoureuse an
existing keyin a newassignment, the effectis to replace the object which was previously stored
under the givenkey. Itisnotrequired thatthe type of the replacement object isthe same as that
ofthe original.
Alsonotethatwhenyouaddanobjecttoabundle,whatinfacthappensisthatthebundleacquires
acopyofthe object. The external object retains its ownidentityandis unaffectedif the bundled
objectisreplacedbyanother. Considerthe followingscriptfragment:
bundle foo
matrix m = I(3)
foo.mykey = m
scalar x = 20
foo.mykey = x
Afterthe above commandsarecompletedbundlefoodoesnotcontainamatrixundermykey, but
theoriginalmatrixmisstillingoodhealth.
To delete anobjectfromabundleusethe deletecommand, withthe bundle/keycombination,as
in
1
Asareminder: 31charactersmaximum,startingwithaletterandcomposedofjustletters,numbersorunderscore.
Chapter10. Gretl datatypes
78
delete foo.mykey
Thisdestroysthe objectassociatedwiththekeyandremovesthekeyfromthe hashtable.
Todeterminewhetherabundlecontainsanobjectassociatedwithagivenkey,usetheinbundle()
function.Thistakestwo arguments: thenameofthebundleandthekeystring.Thevaluereturned
bythisfunctionisaninteger whichcodes for thetype ofthe object(0 forno match,1for scalar,2
for series,3 formatrix,4 for string,5forbundle and6 forarray). The functiontypestr()maybe
usedtogetthestringcorrespondingtothiscode. Forexample:
scalar type = inbundle(foo, x)
if type == 0
print "x: no such object"
else
printf "x is of type %s\n", typestr(type)
endif
Besides adding, accessing, replacing and deleting individual items, the other operations that are
supportedfor bundlesare union,printinganddeletion. Asregardsunion,ifbundlesb1andb2are
definedyoucansay
bundle b3 = b1 + b2
tocreate anewbundle thatis the unionof the two others. The algorithmis: create anewbundle
that is a copy of b1, then add any items from b2 whose keys are notalready presentin the new
bundle. (This means that bundle union is not commutative if the bundles have one or more key
stringsincommon.)
Ifbisabundleandyousayprint b,yougetalistingofthebundle’s keysalongwiththe types of
thecorrespondingobjects,asin
? print b
bundle b:
x (scalar)
mat (matrix)
inside (bundle)
Whatarebundlesgoodfor?
Bundles are unlikely to be of interest in the context of standalone gretl scripts, but they can be
veryuseful inthe contextofcomplex function packageswhere agooddealofinformationhas to
be passed around betweenthe componentfunctions. Insteadofusinga lengthylist of individual
arguments, functionA canbundle up the required data and pass it to functions B and C, where
relevantinformationcanbeextractedviaamnemonickey.
Inthiscontextbundlesshouldbepassedin“pointer”form(seechapter13)asillustratedinthe fol-
lowingtrivialexample,whereabundleiscreatedatonelevelthenfilledoutbyaseparatefunction.
# modification of bundle (pointer) by user function
function void fill_out_bundle (bundle *b)
b.mat =
I(3)
b.str = "foo"
b.x = 32
end function
bundle my_bundle
fill_out_bundle(&my_bundle)
Chapter10. Gretl datatypes
79
The bundle type can also be used to advantage as the returnvalue from a packaged function, in
cases where a package writer wants to give the user the option of accessing various results. In
thegretlGUI,functionpackagesthatreturnabundle are treatedspecially: the outputwindowthat
displays the printed results acquires amenu showing the bundleditems (their names and types),
fromwhichthe user can save itemsof interest. For example, a functionpackage thatestimates a
model might return a bundle containing a vector of parameter estimates, a residual series and a
covariance matrixfor theparameterestimates,amongotherpossibilities.
Asarefinementto supportthe use ofbundlesasafunctionreturntype,thesetnotefunctioncan
be used to add abriefexplanatorynote to abundleditem—such notes willthenbe shownin the
GUImenu. This functiontakesthree arguments: thename ofabundle, akeystring, andthe note.
For example
setnote(b, "vcv", "covariance matrix")
Afterthis,the objectunder thekeyvcv inbundle bwillbe shownas “covariance matrix” inaGUI
menu.
10.8 Arrays
The gretl array type was developedinsummer 2014 andis firstdocumentedingretl1.10. Arrays
are intended for scripting use only: they have no GUI representation and they’re unlikely ever
to acquire one.
2
Since this type is arelative newcomer there are at present relatively few built-in
functionsthattakearraysasargumentsorthatreturnarrays;furtherdevelopmentcanbeexpected.
Agretlarrayis,as youmightexpect, acontainer whichcanholdzero or more objectsofacertain
type,indexedbyconsecutive integersstartingat1. Itisone-dimensional.Thistypeisimplemented
byaquite “generic” back-end. Thetypesofobjectthatcanbe putintoarraysare strings,matrices,
bundlesandlists; agivenarraycanholdonlyoneofthesetypes.
Of gretl’s “primary” types,then, neither scalarsnor seriesare supportedbythe arraymechanism.
There would be little point in supporting arrays of scalars as such since the matrix type already
plays thatrole,andmore flexibly. Asforseries,theyhave aspecialstatusaselementsofadataset
(whichisinasensean“arrayofseries” already)andinadditionwehavethe listtype whichalready
functionsasasortofarrayforsubsetsoftheseries inadataset.
Creatinganarray
Anarraycanbebroughtintoexistenceinanyoffourways: baredeclaration,assignmentfromnull,
or usingoneofthefunctions array() or defarray(). Ineachcaseone ofthe specifictype-words
strings,matrices,bundles orlists mustbeused. Here are someexamples:
# make an empty array of strings
strings S
# make an empty array of matrices
matrices M = null
# make an array with space for four bundles
bundles B = array(4)
# make an array with three specified strings
strings P = defarray("foo", "bar", "baz")
The“baredeclaration”formandthe“= null”formhavethesameeffectofcreatinganemptyarray,
but the second canbe used in contexts where bare declaration is not allowed (and itcanalso be
usedtodestroythecontentofanexisting arrayand reduce itto size zero). The array()function
2
However,it’spossibletosavearrays“invisibly”inthecontextofaGUIsession,byvirtueofthefactthattheycanbe
packedintobundles(seebelow),andbundlescanbesavedaspartofa“session”.
Documents you may be interested
Documents you may be interested