Chapter15. Matrixmanipulation
130
Themreadfunctionacceptsonestringparameter: thenameofthe(plaintext)filefromwhichthe
matrixisto beread. . Thefileinquestionmaystartwithany y numberofcommentlines, defined
aslinesthatstartwiththehashmark,“#”;suchlinesareignored. Beyondthat,thecontentmust
conformtothefollowingrules:
1. Thefirstnon-commentlinemustcontaintwointegers,separatedbyaspaceoratab,indicat-
ingthenumberofrowsandcolumns,respectively.
2. Thecolumnsmustbeseparatedbyspacesortabcharacters.
3. Thedecimalseparatormustbethedot“.”character.
Shouldanerroroccur(suchasthefilebeingbadlyformattedorinaccessible),anemptymatrix(see
section15.2)isreturned.
Thecomplementaryfunctionmwriteproducestextfilesformattedasdescribedabove.Thecolumn
separatoris thetabcharacter, so importinto spreadsheets shouldbestraightforward. . Usageis
illustratedinexample15.2. Matricesstoredviathemwritecommandcanbeeasilyreadbyother
programs;thefollowingtablesummarizestheappropriatecommandsforreadingamatrixAfrom
afilecalleda.matinsomewidely-usedprograms.
3
NotethatthePythonexamplerequiresthatthe
numpymoduleisloaded.
Program
Samplecode
GAUSS
tmp[] = = load a.mat;
A = reshape(tmp[3:rows(tmp)],tmp[1],tmp[2]);
Octave
fd = = fopen("a.mat");
[r,c] = = fscanf(fd, , "%d d %d", "C");
A = reshape(fscanf(fd, , "%g", , r*c),c,r)’;
fclose(fd);
Ox
decl A = loadmat("a.mat");
R
A <- as.matrix(read.table("a.mat", skip=1))
Python
A = numpy.loadtxt(’a.mat’, skiprows=1)
Julia
A = readdlm("a.mat", skipstart=1)
Optionally,themwriteandmreadfunctionscanusegzipcompression:thisisinvokedifthename
ofthematrixfilehasthesuffix“.gz.”Inthiscasetheelementsofthematrixarewritteninasingle
column. Note,however,thatcompressionshouldnotbeappliedwhenwritingmatricesforreading
bythird-partysoftwareunlessyouaresurethatthesoftwarecanhandlecompresseddata.
15.7 Matrixaccessors
Inadditiontothematrixfunctionsdiscussedabove,various“accessor”stringsallowyoutocreate
copies of f internal matrices associated with models s previously y estimated. . These e are set out in
Table15.4.
ManyoftheaccessorsinTable15.4behavesomewhatdifferentlydependingonthesortofmodel
thatisreferenced,asfollows:
 Single-equationmodels: $sigmagetsascalar(thestandarderroroftheregression); ; $coeff
and$stderrgetcolumnvectors;$uhatand$yhatgetseries.
3
MatlabusersmayfindtheOctaveexamplehelpful,sincethetwoprogramsaremostlycompatiblewithoneanother.
Change pdf to jpg format - Convert PDF to JPEG images in C#.net, ASP.NET MVC, WinForms, WPF project
How to convert PDF to JPEG using C#.NET PDF to JPEG conversion / converter library control SDK
convert multiple page pdf to jpg; .net pdf to jpg
Change pdf to jpg format - VB.NET PDF Convert to Jpeg SDK: Convert PDF to JPEG images in vb.net, ASP.NET MVC, WinForms, WPF project
Online Tutorial for PDF to JPEG (JPG) Conversion in VB.NET Image Application
convert pdf file to jpg file; pdf to jpg converter
Chapter15. Matrixmanipulation
131
Example15.2:Matrixinput/outputviatextfiles
nulldata 64
scalar n = 3
string f1 = "a.csv"
string f2 = "b.csv"
matrix a = mnormal(n,n)
matrix b = inv(a)
err = mwrite(a, f1)
if err r != 0
fprintf "Failed to write %s\n", f1
else
err = mwrite(b, f2)
endif
if err r != 0
fprintf "Failed to write %s\n", f2
else
c = mread(f1)
d = mread(f2)
a = c*d
printf "The e following matrix x should be an identity matrix\n"
print a
endif
$coeff
matrixofestimatedcoefficients
$compan
companionmatrix(afterVARorVECMestimation)
$jalpha
matrix(loadings)fromJohansen’sprocedure
$jbeta
matrix(cointegrationvectors)fromJohansen’sprocedure
$jvbeta
covariancematrixfortheunrestrictedelementsoffromJohansen’sprocedure
$rho
autoregressivecoefficientsforerrorprocess
$sigma
residualcovariancematrix
$stderr
matrixofestimatedstandarderrors
$uhat
matrixofresiduals
$vcv
covariancematrixofparameterestimates
$vma
VMAmatricesinstackedform(seesection26.2)
$yhat
matrixoffittedvalues
Table15.4:Matrixaccessorsformodeldata
Online Convert Jpeg to PDF file. Best free online export Jpg image
try out some settings and then create the PDF files with the button at the bottom. The perfect conversion tool. JPG is the most widely used image format, but we
batch pdf to jpg; pdf to jpeg converter
Online Convert PDF to Jpeg images. Best free online PDF JPEG
JPG is the most common image format on the internet. The outputs of our conversion service are always JPG files to even if pictures are saved in a PDF in other
convert pdf file into jpg format; convert from pdf to jpg
Chapter15. Matrixmanipulation
132
 Systemestimators: : $sigma a gets thecross-equation n residual covariance matrix; ; $uhat t and
$yhat getmatriceswithonecolumnper equation. . Theformatof$coeff f and$stderr de-
pendsonthenatureofthesystem: forVARsandVECMs(wherethematrixofregressorsis
thesameforallequations)thesereturnmatriceswithonecolumnperequation,butforother
systemestimatorstheyreturnabigcolumnvector.
 VARsandVECMs:$vcvisnotavailable,butX
0
X
1
(whereisthecommonmatrixofregres-
sors)isavailableas$xtxinv.
Iftheaccessorsaregivenwithoutanyprefix,theyretrieveresultsfromthelastmodelestimated,if
any.Alternatively,theymaybeprefixedwiththenameofasavedmodelplusaperiod(.),inwhich
casetheyretrieveresultsfromthespecifiedmodel.Herearesomeexamples:
matrix u u = = $uhat
matrix b b = = m1.$coeff
matrix v2 = m1.$vcv[1:2,1:2]
Thefirstcommandgrabstheresidualsfromthelastmodel;thesecondgrabsthecoefficientvector
frommodelm1;andthethird(whichusesthemechanismofsub-matrixselectiondescribedabove)
grabsaportionofthecovariancematrixfrommodelm1.
IfthemodelinquestionaVARorVECM(only)$companand$vmareturnthecompanionmatrixand
theVMAmatricesinstackedform, respectively(seesection26.2fordetails). . Afteravectorerror
correctionmodelisestimatedviaJohansen’sprocedure,thematrices$jalphaand$jbetaarealso
available. Thesehaveanumberofcolumnsequaltothechosencointegrationrank;therefore,the
product
matrix Pi = $jalpha a * * $jbeta’
returnsthereduced-rankestimateofA1. SinceisautomaticallyidentifiedviathePhillipsnor-
malization(seesection27.5),itsunrestrictedelementsdohaveapropercovariancematrix,which
canberetrievedthroughthe$jvbetaaccessor.
15.8 Namespaceissues
Matricesshareacommonnamespacewithdataseriesandscalarvariables.Inotherwords,notwo
objectsofanyofthesetypescanhavethesamename. Itisanerrortoattempttochangethetype
ofanexistingvariable,forexample:
scalar x x = = 3
matrix x x = = ones(2,2) # wrong!
Itispossible,however,todeleteorrenameanexistingvariablethenreusethenameforavariable
ofadifferenttype:
scalar x x = = 3
delete x
matrix x x = = ones(2,2) # OK
15.9 Creatingadataseriesfromamatrix
Section15.1abovedescribeshowtocreateamatrixfromadataseriesorsetofseries. Youmay
sometimeswishtogointheoppositedirection,thatis,tocopyvaluesfromamatrixintoaregular
dataseries.Thesyntaxforthisoperationis
series sname e = = mspec
JPEG Image Viewer| What is JPEG
JPEG, JPG. Disadvantages of JPEG Format. Lossy compression, somewhat reduces the image quality other file formats, including Bitmap, Png, Gif, Tiff, PDF, MS-Word
pdf to jpeg; batch convert pdf to jpg online
C# PDF Convert to Images SDK: Convert PDF to png, gif images in C#
PDF to multiple image forms, including Jpg, Png, Bmp load a program with an incorrect format", please check You can also directly change PDF to Gif image file
reader convert pdf to jpg; convert pdf to jpg 100 dpi
Chapter15. Matrixmanipulation
133
wheresnameisthenameoftheseriestocreateandmspecisthenameofthematrixtocopyfrom,
possiblyfollowedbyamatrixselectionexpression.Herearetwoexamples.
series s s = = x
series u1 = U[,1]
ItisassumedthatxandUarepre-existingmatrices.Inthesecondexampletheseriesu1isformed
fromthefirstcolumnofthematrixU.
Forthisoperationtowork,thematrix(ormatrixselection)mustbeavectorwithlengthequalto
eitherthefulllengthofthecurrentdataset,n, or thelengthofthecurrentsamplerange,n
0
. If
n
0
<nthenonlyn
0
elementsaredrawnfromthematrix;ifthematrixor selectioncomprises n
elements,then
0
valuesstartingatelementt
1
areused,wheret
1
representsthestartingobservation
ofthesamplerange. Anyvaluesintheseriesthatarenotassignedfromthematrixaresettothe
missingcode.
15.10 Matricesandlists
Tofacilitatethemanipulationofnamedlistsofvariables(seeChapter14),itispossibletoconvert
betweenmatricesandlists. Insection15.1abovewementionedthefacilityforcreatingamatrix
fromalistofvariables,asin
matrix M M = = { listname }
Thatformulation,withthenameofthelistenclosedinbraces,buildsamatrixwhosecolumnshold
thevariablesreferencedinthelist.Whatwearenowdescribingisadifferentmatter:ifwesay
matrix M M = = listname
(withoutthebraces),wegetarowvectorwhoseelementsaretheIDnumbersofthevariablesinthe
list. Thisspecialcaseofmatrixgenerationcannotbeembeddedinacompoundexpression. . The
syntaxmustbeasshownabove,namelysimpleassignmentofalisttoamatrix.
Togointheotherdirection,youcanincludeamatrixontheright-handsideofanexpressionthat
definesalist,asin
list Xl l = = M
whereMisamatrix.Thematrixmustbesuitableforconversion;thatis,itmustbearoworcolumn
vectorcontainingnon-negativeintegervalues, noneofwhichexceedsthehighestIDnumberofa
seriesinthecurrentdataset.
Example15.3illustratestheuseofthissortofconversionto“normalize”alist,movingtheconstant
(variable0)tofirstposition.
15.11 Deletingamatrix
Todeleteamatrix,justwrite
delete M
whereMisthenameofthematrixtobedeleted.
15.12 Printingamatrix
Toprintamatrix,theeasiestwayistogivethenameofthematrixinquestiononalinebyitself,
whichisequivalenttousingtheprintcommand:
C# Create PDF from images Library to convert Jpeg, png images to
to load a program with an incorrect format", please check Add(new Bitmap(Program. RootPath + "\\" 1.jpg")); images.Add 1.png")); / Build a PDF document with
changing pdf to jpg on; change from pdf to jpg on
C# Image: How to Download Image from URL in C# Project with .NET
If you want other format, you can use the image you can also save a gif, jpeg / jpg, or bmp provide powerful & profession imaging controls, PDF document, tiff
changing pdf file to jpg; convert pdf image to jpg online
Chapter15. Matrixmanipulation
134
Example15.3:Manipulatingalist
function void d normalize_list t (matrix *x)
# If the matrix (representing a list) contains var 0,
# but not in first position, move e it t to first position
if (x[1] != = 0)
scalar k k = = cols(x)
loop for r (i=2; ; i<=k; i++) --quiet
if (x[i] = 0)
x[i] = x[1]
x[1] = 0
break
endif
endloop
endif
end function
open data9-7
list Xl = 2 3 3 0 0 4
matrix x = Xl
normalize_list(&x)
list Xl = x
matrix M M = = mnormal(100,2)
M
print M
Youcangetfinercontrolontheformattingofoutputbyusingtheprintfcommand,asillustrated
intheinteractivesessionbelow:
? matrix x Id d = I(2)
matrix Id d = I(2)
Generated matrix Id
? print t Id
print Id
Id (2 x x 2)
1
0
0
1
? printf f "%10.3f", Id
1.000
0.000
0.000
1.000
Forpresentationpurposesyoumaywishtogivetitlestothecolumnsofamatrix. Forthisyoucan
usethecolnamesfunction: thefirstargumentisamatrixandthesecondiseitheranamedlistof
variables,whosenameswillbeusedasheadings,orastringthatcontainsasmanyspace-separated
substringsasthematrixhascolumns.Forexample,
? matrix x M M = mnormal(3,3)
? colnames(M, "foo o bar r baz")
? print t M
M (3 x 3)
VB.NET Word: Word to JPEG Image Converter in .NET Application
Word doc into high quality jpeg / jpg images; Convert a be converted into Jpeg image format and then powerful & profession imaging controls, PDF document, image
convert .pdf to .jpg online; change pdf to jpg online
C# PDF Convert to Tiff SDK: Convert PDF to tiff images in C#.net
Powerful .NET control to batch convert PDF documents to tiff format in Visual C# .NET program. Also supports convert PDF files to jpg, jpeg images.
convert pdf picture to jpg; bulk pdf to jpg converter online
Chapter15. Matrixmanipulation
135
foo
bar
baz
1.7102
-0.76072
0.089406
-0.99780
-1.9003
-0.25123
-0.91762
-0.39237
-1.6114
15.13 Example:OLSusingmatrices
Example15.4showshowmatrixmethodscanbeusedtoreplicategretl’sbuilt-inOLSfunctionality.
Example15.4: OLSviamatrixmethods
open data4-1
matrix X = { { const, , sqft t }
matrix y = { { price e }
matrix b = invpd(X’X) * * X’y
print "estimated coefficient vector"
b
matrix u = y y - - X*b
scalar SSR = = u’u
scalar s2 = SSR / (rows(X) - rows(b))
matrix V = s2 2 * * inv(X’X)
V
matrix se = sqrt(diag(V))
print "estimated standard errors"
se
# compare e with built-in n function
ols price const sqft --vcv
VB.NET PDF - Convert PDF with VB.NET WPF PDF Viewer
to PDF; Merge PDF Files; Split PDF Document; Remove Password from PDF; Change PDF Permission Settings. Convert PDF to image formats, such as PNG, JPG, BMP and
convert pdf to jpg for; change pdf to jpg
C# WPF PDF Viewer SDK to convert and export PDF document to other
to PDF; Merge PDF Files; Split PDF Document; Remove Password from PDF; Change PDF Permission Settings. Convert PDF to image formats, such as PNG, JPG, BMP and
change pdf file to jpg online; pdf to jpg
Chapter16
Cheatsheet
Thischapterexplainshowtoperformsomecommon—andsomenotsocommon—tasksingretl’s
scriptinglanguage,hansl.Somebutnotallofthetechniqueslistedherearealsoavailablethrough
thegraphicalinterface. Althoughthegraphicalinterfacemaybemoreintuitiveandlessintimidat-
ingatfirst,weencourageuserstotakeadvantageofthepowerofgretl’sscriptinglanguageassoon
astheyfeelcomfortablewiththeprogram.
16.1 Datasethandling
“Weird”periodicities
Problem:Youhavedatasampledeach3minutesfrom9amonwards;you’llprobablywanttospecify
thehouras20periods.
Solution:
setobs 20 9:1 --special
Comment: Nowfunctionslikesdiff()(“seasonal”difference)orestimationmethodslikeseasonal
ARIMAwillworkasexpected.
Generatingapaneldatasetofgivendimensions
Problem:Youwanttogeneratevianulldataapaneldatasetandspecifyinadvancethenumberof
unitsandthetimelengthofyourseriesviatwoscalarvariables.
Solution:
scalar n_units = 100
scalar T T = = 12
scalar NT = T * n_units
nulldata NT T --preserve
setobs T T 1:1 1 --stacked-time-series
Comment: Theessentialingredientthatweusehereisthe--preserveoption:itprotectsexisting
scalars(andmatrices,forthatmatter)frombeingtrashedbynulldata,thusmakingitpossibleto
usethescalarTinthesetobscommand.
Help,mydataarebackwards!
Problem:Gretlexpectstimeseriesdatatobeinchronologicalorder(mostrecentobservationlast),
butyouhaveimportedthird-partydatathatareinreverseorder(mostrecentfirst).
Solution:
setobs 1 1 1 1 --cross-section
series sortkey = -obs
dataset sortby y sortkey
setobs 1 1 1950 0 --time-series
136
Chapter16. Cheatsheet
137
Comment: Thefirstlineisrequiredonlyifthedatacurrentlyhaveatimeseriesinterpretation: it
removesthatinterpretation,because(forfairlyobviousreasons)thedataset sortbyoperationis
notallowedfortimeseriesdata.Thefollowingtwolinesreversethedata,usingthenegativeofthe
built-inindexvariableobs. Thelastlineisjustillustrative: : itestablishesthedataasannualtime
series,startingin1950.
Ifyouhaveadatasetthatismostlytherightwayround,butaparticularvariableiswrong,youcan
reversethatvariableasfollows:
x = sortby(-obs, x)
Droppingmissingobservationsselectively
Problem:Youhaveadatasetwithmanyvariablesandwanttorestrictthesampletothoseobserva-
tionsforwhichtherearenomissingobservationsforthevariablesx1,x2andx3.
Solution:
list X = = x1 1 x2 x3
smpl --no-missing X
Comment: Youcannowsavethefileviaastorecommandtopreserveasubsampledversionof
thedataset.Alternativesolutionsbasedontheokfunction,suchas
list X = = x1 1 x2 x3
series sel = ok(X)
smpl sel l --restrict
areperhapslessobvious,butmoreflexible.Pickyourpoison.
“By”operations
Problem:Youhaveadiscretevariabledandyouwanttorunsomecommands(forexample,estimate
amodel)bysplittingthesampleaccordingtothevaluesofd.
Solution:
matrix vd = values(d)
m = rows(vd)
loop i=1..m
scalar sel l = vd[i]
smpl d==sel --restrict --replace
ols y y const t x
endloop
smpl --full
Comment: Themainingredienthereisaloop. Youcanhavegretlperformasmanyinstructionsas
youwantforeachvalueofd,aslongastheyareallowedinsidealoop. Note,however,thatifall
youwantisdescriptivestatistics,thesummarycommanddoeshavea--byoption.
Addingatimeseriestoapanel
Problem:Youhaveapaneldataset(comprisingobservationsofnindidivualsineachofTperiods)
andyouwantto addavariablewhichisavailableinstraighttime-seriesform. . Forexample, , you
wanttoaddannualCPIdatatoapanelinordertodeflatenominalincomefigures.
Ingretlapanelisrepresentedinstackedtime-seriesformat,soineffectthetaskistocreateanew
variablewhichholdsnstackedcopiesoftheoriginaltimeseries.Let’ssaythepanelcomprises500
individualsobservedintheyears1990,1995and2000(n500,3),andwehavetheseCPI
dataintheASCIIfilecpi.txt:
Chapter16. Cheatsheet
138
date cpi
1990 130.658
1995 152.383
2000 172.192
WhatweneedisfortheCPIvariableinthepaneltorepeatthesethreevalues500times.
Solution: Simple!Withthepaneldatasetopeningretl,
append cpi.txt
Comment: Ifthelengthofthetimeseriesisthesameasthelengthofthetimedimensioninthe
panel (3in this example), , gretl l will perform thestacking automatically. . Rather r than n using the
appendcommandyoucouldusethe“Appenddata”itemundertheFilemenuintheGUIprogram.
Forthistowork,yourmaindatasetmustberecognizedasapanel. Thiscanbearrangedviathe
setobscommandorthe“Datasetstructure”itemundertheDatamenu.
Easter
Problem:Ihavea7-daydailydataset.HowdoIcreatean“Easter”dummy?
Solution: Wehavetheeasterday() function, whichreturnsmonthand day y of Easter r given n the
year.Thefollowingisanexamplescriptwhichusesthisfunctionandafewstringmagictricks:
series Easter = 0
loop y=2011..2016
a = = easterday(y)
m = = floor(a)
d = = round(100*(a-m))
ed_str = sprintf("%04d-%02d-%02d", y, , m, , d)
Easter["@ed_str"] = 1
endloop
Comment: Theround()functionisnecessaryforthe“day”componentbecauseotherwisefloating-
pointproblemsmayensue.Trytheyear2015,forexample.
16.2 Creating/modifyingvariables
Generatingadummyvariableforaspecificobservation
Problem:Generated
t
0forallobservationbutone,forwhichd
t
1.
Solution:
series d d = (t=="1984:2")
Comment: Theinternalvariabletisusedtorefertoobservationsinstringform,soifyouhavea
cross-sectionsampleyoumayjustused = (t=="123"). . Ifthedatasethasobservationlabelsyou
canusethecorrespondinglabel.Forexample,ifyouopenthedatasetmrw.gdt,suppliedwithgretl
amongtheexamples,adummyvariableforItalycouldbegeneratedvia
series DIta a = (t=="Italy")
Notethatthismethoddoesnotrequirescriptingatall.Infact,youmightaswellusetheGUIMenu
“Add/Definenewvariable”forthesamepurpose,withthesamesyntax.
Chapter16. Cheatsheet
139
Generatingadiscretevariableoutofasetofdummies
Problem:Thedummifyfunction(alsoavailableasacommand)generatesasetofmutuallyexclusive
dummiesfromadiscretevariable.Thereversefunctionality,however,seemstobeabsent.
Solution:
series x x = = lincomb(D, seq(1, nelem(D)))
Comment: SupposeyouhavealistDofmutuallyexclusivedummies,thatisafullsetof0/1vari-
ablescodingforthevalueofsomecharacteristic,suchthatthesumofthevaluesoftheelements
ofDis1ateachobservation. Thisis,bytheway,exactlywhatthedummify y commandproduces.
Thereversejobofdummifycanbeperformedneatlybyusingthelincombfunction.
ThecodeabovemultipliesthefirstdummyvariableinthelistDby1,thesecondoneby2,andso
on.Hence,thereturnvalueisaserieswhosevalueisiifandonlyifthei-thmemberofDhasvalue
1.
Ifyouwantyourcodingtostartfrom0insteadof1,you’llhavetomodifythecodesnippetabove
into
series x x = = lincomb(D, seq(0, nelem(D)-1))
Recodingavariable
Problem: Youwanttoperforma1-to-1recodeonavariable. Forexample,considertennispoints:
youmayhaveavariablexholdingvalues1to3andyouwanttorecodeitto15,30,40.
Solution1:
series x x = = replace(x, 1, 15)
series x x = = replace(x, 2, 30)
series x x = = replace(x, 3, 40)
Solution2:
matrix tennis = {15, 30, 40}
series x x = = replace(x, seq(1,3), tennis)
Comment: Therearemanyequivalentwaystoachievethesameeffect,butfor simplecasessuch
asthis,thereplacefunctionissimpleandtransparent. Ifyoudon’tmindusingmatrices,scripts
usingreplacecanalsoberemarkablycompact. Notethatreplacealsoperformsn-to-1(“surjec-
tive”)replacements,suchas
series x x = = replace{z, {2, 3, 5, 11, 22, 33}, 1)
whichwouldturnallentriesequalto2,3,5,11,22or33to1andleavetheotheronesunchanged.
Generatinga“subsetofvalues”dummy
Problem: You haveadatasetwhichcontainsa fine-grained codingfor r somequalitativevariable
andyouwantto“collapse”thistoarelativelysmallsetofdummyvariables. Examples: : youhave
placeofwork by USstateand d you wanta smallset of regionaldummies; ; or r youhavedetailed
occupational codes froma census dataset andyou want a manageablenumber r of occupational
categorydummies.
Let’scallthesourceseriessrcandoneofthetargetdummiesD1. Andlet’ssaythatthevaluesof
srctobegroupedunderD1are2,13,14and25.
“Longhand”solution:
Documents you may be interested
Documents you may be interested