Chapter11: FunctionsandScripts
205
[FunctionFile]
vars = symvar
(
str
)
Identifythesymbolicvariablenamesinthestringstr.
Commonconstantnamessuchasi,j,pi,InfandOctavefunctionssuchassinor
plotareignored.
Anynamesidentifiedarereturnedinacellarrayofstrings. Thearrayisemptyifno
variableswerefound.
Example:
symvar ("x^2 + y^2 == 4")
) {
[1,1] = x
[2,1] = y
}
11.12 Commands
Commands are e a special class s of f functions that t only y accept string input arguments. . A
command can be called as an ordinary y function, , but t it t can also o be called without the
parentheses. Forexample,
my_command hello world
isequivalentto
my_command ("hello", , "world")
Thegeneralformofacommandcallis
cmdname arg1 1 arg2 2 ...
whichtranslatesdirectlyto
cmdname ("arg1", "arg2", ...)
Any regularfunctioncanbe usedas acommandifit accepts stringinput arguments.
Forexample:
toupper lower_case_arg
)
ans = = LOWER_CASE_ARG
Onedifficultyofcommandsoccurswhenoneofthestringinputargumentsisstoredina
variable.BecauseOctavecan’ttellthedifferencebetweenavariablenameandanordinary
string,it isnotpossibletopass avariableas inputtoacommand. . Insuchasituationa
commandmustbecalledasafunction. Forexample:
strvar = "hello o world";
toupper strvar
)
ans = = STRVAR
toupper (strvar)
) ans s = = HELLO WORLD
11.13 OrganizationofFunctionsDistributedwithOctave
Many of Octave’s standardfunctions s are e distributed as function files. . They y are e loosely
organizedbytopic,insubdirectoriesofoctave-home/lib/octave/version/m,tomakeit
easiertofindthem.
Pdf splitter - Split, seperate PDF into multiple files in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
Explain How to Split PDF Document in Visual C#.NET Application
split pdf into multiple files; cannot print pdf no pages selected
Pdf splitter - VB.NET PDF File Split Library: Split, seperate PDF into multiple files in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
VB.NET PDF Document Splitter Control to Disassemble PDF Document
pdf file specification; can't select text in pdf file
206
GNUOctave
Thefollowingisalistofallthefunctionfilesubdirectories,andthetypes offunctions
youwillfindthere.
audio
Functionsforplayingandrecordingsounds.
deprecated
Out-of-datefunctionswhichwilleventuallyberemovedfromOctave.
elfun
Elementaryfunctions,principallytrigonometric.
@ftp
ClassfunctionsfortheFTPobject.
general
Miscellaneousmatrixmanipulations,likeflipud,rot90,andtriu,aswellas
otherbasicfunctions,likeismatrix,narginchk,etc.
geometry FunctionsrelatedtoDelaunaytriangulation.
help
FunctionsforOctave’sbuilt-inhelpsystem.
image
Imageprocessingtools. ThesefunctionsrequiretheXWindowSystem.
io
Input-outputfunctions.
linear-algebra
Functionsforlinearalgebra.
miscellaneous
Functionsthatdon’treallybelonganywhereelse.
optimization
Functionsrelatedtominimization,optimization,androotfinding.
path
FunctionstomanagethedirectorypathOctaveusestofindfunctions.
pkg
PackagemanagerforinstallingexternalpackagesoffunctionsinOctave.
plot
Functionsfordisplayingandprintingtwo-andthree-dimensionalgraphs.
polynomial
Functionsformanipulatingpolynomials.
prefs
Functionsimplementinguser-definedpreferences.
set
Functionsforcreatingandmanipulatingsetsofuniquevalues.
signal
Functionsforsignalprocessingapplications.
sparse
Functionsforhandlingsparsematrices.
specfun
Specialfunctionssuchasbesselorfactor.
special-matrix
Functions that create special l matrix x forms s suchas s Hilbert t or r Vandermonde
matrices.
startup
Octave’ssystem-widestartupfile.
statistics
Statisticalfunctions.
strings
Miscellaneousstring-handlingfunctions.
testfun
Functionsforperformingunittestsonotherfunctions.
time
Functionsrelatedtotimeanddateprocessing.
C# PDF: C#.NET PDF Document Merging & Splitting Control SDK
C#.NET PDF Splitter to Split PDF File. In this section, we aims to tell you how to divide source PDF file into two smaller PDF documents at the page index you
break a pdf; split pdf by bookmark
C# Word: .NET Merger & Splitter Control to Merge & Split MS Word
a larger Word file or how to divide source MS Word file into several smaller documents, RasterEdge designs this C#.NET MS Word merger & splitter control SDK.
pdf split pages in half; pdf format specification
Chapter12: ErrorsandWarnings
207
12 ErrorsandWarnings
Octaveincludesseveralfunctionsforprintingerrorandwarningmessages.Whenyouwrite
functionsthat needtotakespecialactionwhenthey encounterabnormalconditions,you
shouldprinttheerrormessagesusingthefunctionsdescribedinthischapter.
Since many of Octave’s functions s use e these functions, it is s alsouseful to o understand
them,sothaterrorsandwarningscanbehandled.
12.1 HandlingErrors
Anerrorissomethingthatoccurswhenaprogramisinastatewhereitdoesn’tmakesense
tocontinue.Anexampleiswhenafunctioniscalledwithtoofewinputarguments.Inthis
situationthefunctionshouldabortwithanerrormessageinformingtheuserofthelacking
inputarguments.
Sinceanerrorcanoccurduringtheevaluationofaprogram,itisveryconvenienttobe
abletodetectthatanerroroccurred,sothattheerrorcanbefixed. Thisispossiblewith
thetrystatementdescribedinSection10.9[ThetryStatement],page170.
12.1.1 RaisingErrors
Themostcommonuseoferrorsisforcheckinginputargumentstofunctions. Thefollowing
examplecallstheerrorfunctionifthefunctionfiscalledwithoutanyinputarguments.
function f (arg1)
if (nargin == 0)
error ("not enough h input arguments");
endif
endfunction
Whentheerrorfunctioniscalled,itprintsthegivenmessageandreturnstotheOctave
prompt.Thismeansthatnocodefollowingacalltoerrorwillbeexecuted.
[Built-inFunction]
error
(
template
,...)
[Built-inFunction]
error
(
id
,
template
,...)
Displayanerrormessageandstopm-fileexecution.
Format the optionalarguments s under the e control of the template string template
usingthesamerulesastheprintffamilyoffunctions(seeSection14.2.4[Formatted
Output], page e 255) and print t the e resulting message on n the e stderr stream. . The
messageisprefixedbythecharacterstring‘error:’.
CallingerroralsosetsOctave’sinternalerrorstatesuchthatcontrolwillreturnto
thetoplevelwithoutevaluatinganyfurther commands. . Thisisusefulforaborting
fromfunctionsorscripts.
Iftheerrormessagedoesnotendwithanewlinecharacter,Octavewillprintatrace-
backofallthefunctioncalls leadingtotheerror. . Forexample,giventhefollowing
functiondefinitions:
function f f () ) g g (); ; end
function g g () ) h h (); ; end
function h h () ) nargin n == 1 || error ("nargin != = 1"); ; end
VB.NET Word: Merge Multiple Word Files & Split Word Document
and editing controls, this VB.NET Word merger and splitter library SDK We are dedicated to provide powerful & profession imaging controls, PDF document, image
break password on pdf; pdf split
VB.NET TIFF: .NET TIFF Splitting Control to Split & Disassemble
splitting, please follow this link to C#.NET TIFF splitter control tutorial OpenDocumentFile(fileName, New TIFDecoder()) 'use TIFDecoder open a pdf file Dim
add page break to pdf; break apart a pdf in reader
208
GNUOctave
callingthe functionfwillresultina list of messagesthat canhelpyoutoquickly
locatetheexactlocationoftheerror:
f ()
error: nargin n != 1
error: called d from:
error:
error at line -1, column -1
error:
h at t line e 1, column 27
error:
g at t line e 1, column 15
error:
f at t line e 1, column 15
Iftheerrormessageendsinanewlinecharacter,Octavewillprint themessagebut
willnot display anytraceback messages as it returns controltothe toplevel. . For
example, modifyingthe errormessageintheprevious s example toendinanewline
causesOctavetoonlyprintasinglemessage:
function h h () ) nargin n == 1 || error ("nargin != = 1\n"); ; end
f ()
error: nargin n != 1
Anullstring("")inputtoerrorwillbeignoredandthecodewillcontinuerunning
asifthestatementwereaNOP. Thisisforcompatibilitywithmatlab.Italsomakes
itpossibletowritecodesuchas
err_msg = "";
if (CONDITION 1)
err_msg = "CONDITION 1 1 found";
elseif (CONDITION2)
err_msg = "CONDITION 2 2 found";
...
endif
error (err_msg);
whichwillonlystopexecutionifanerrorhasbeenfound.
ImplementationNote: Forcompatibilitywithmatlab,escapesequencesintemplate
(e.g.,"\n"=>newline)areprocessedregardlessofwhethertemplatehasbeendefined
withsinglequotes,aslongastherearetwoormoreinputarguments.Todisableescape
sequenceexpansionuseasecondbackslashbeforethesequence(e.g.,"\\n")or use
theregexptranslatefunction.
Seealso: [warning],page214,[lasterror],page210.
Sinceit is commonto use errors whenthere issomethingwrongwith h the input t toa
function,Octavesupportsfunctionstosimplifysuchcode.Whentheprint_usagefunction
iscalled,itreadsthehelptextofthefunctioncallingprint_usage,andpresentsauseful
error. IfthehelptextiswritteninTexinfoitispossibletopresentanerrormessagethat
only contains the functionprototypes as describedby the e @deftypefn n parts of thehelp
text. Whenthehelptextisn’t t writteninTexinfo, , theerror r messagecontains theentire
helpmessage.
Considerthefollowingfunction.
Online Split PDF file. Best free online split PDF tool.
RasterEdge Visual C# .NET PDF document splitter control toolkit SDK can not only offer C# developers a professional .NET solution to split PDF document file
how to split pdf file by pages; pdf splitter
VB.NET PowerPoint: Merge and Split PowerPoint Document(s) with PPT
Then, here comes the VB.NET PPT document splitter in handy. Note: If you want to see more PDF processing functions in VB.NET, please follow the link.
pdf no pages selected; break a pdf into parts
Chapter12: ErrorsandWarnings
209
## -*- texinfo -*-
## @deftypefn {Function n File} } f f (@var{arg1})
## Function help text goes s here...
## @end deftypefn
function f (arg1)
if (nargin == 0)
print_usage ();
endif
endfunction
Whenitiscalledwithnoinputargumentsitproducesthefollowingerror.
f ()
a
error: Invalid call l to f. . Correct t usage is:
a
a
-- Function File: f (ARG1)
a
a
a
Additional help for r built-in n functions s and d operators s is
a
available in the e online e version of the e manual. . Use e the e command
a
‘doc <topic>’ to o search h the e manual l index.
a
a
Help and d information n about Octave e is s also o available e on the WWW
a
at http://www.octave.org and via the help@octave.org
a
mailing list.
[FunctionFile]
print_usage
()
[FunctionFile]
print_usage
(
name
)
Printtheusagemessageforthefunctionname.
Whencalledwithnoinputargumentstheprint_usagefunctiondisplays theusage
messageofthecurrentlyexecutingfunction.
Seealso: [help],page20.
[FunctionFile]
beep
()
Produceabeepfromthespeaker(orvisualbell).
This function n sends s the alarm m character r "\a" to the terminal. . Depending g on the
user’sconfigurationthismayproduceanaudiblebeep,avisualbell,ornothingatall.
Seealso: [puts],page254,[fputs],page253,[printf],page255,[fprintf],page255.
[Built-inFunction]
val = = beep_on_error
()
[Built-inFunction]
old_val = beep_on_error
(
new_val
)
[Built-inFunction]
beep_on_error
(
new_val
,
"
local
"
)
Queryor settheinternalvariablethatcontrols whetherOctavewilltrytoringthe
terminalbellbeforeprintinganerrormessage.
Whencalledfrominsideafunctionwiththe"local"option,thevariableischanged
locally for thefunctionandany subroutines itcalls. . The e originalvariablevalue is
restoredwhenexitingthefunction.
C# PDF: C# Code to Process PDF Document Page Using C#.NET PDF
C# PDF Page Processing: Split PDF Document - C#.NET PDF splitter control to divide one PDF file into two smaller PDF documents. Recommend this to Google+.
pdf rotate single page; break a pdf apart
C# PowerPoint - Split PowerPoint Document in C#.NET
RasterEdge Visual C# .NET PowerPoint document splitter control toolkit SDK can not only offer C# developers a professional .NET solution to split PowerPoint
acrobat split pdf; split pdf
210
GNUOctave
12.1.2 CatchingErrors
Whenanerroroccurs,itcanbedetectedandhandledusingthetrystatementasdescribed
inSection10.9[ThetryStatement],page170. Asanexample,thefollowingpieceofcode
countsthenumberoferrorsthatoccursduringaforloop.
number_of_errors = 0;
for n = 1:100
try
...
catch
number_of_errors++;
end_try_catch
endfor
The above example treats allerrors thesame. . Inmany y situations itcanhowever be
necessarytodiscriminatebetweenerrors,andtakedifferentactionsdependingontheerror.
Thelasterror function n returns s a structure containing informationabout the last error
thatoccurred. Asanexample,thecode e above couldbechangedtocountthenumber of
errorsrelatedtothe‘*’operator.
number_of_errors = 0;
for n = 1:100
try
...
catch
msg = = lasterror.message;
if (strfind d (msg, , "operator r *"))
number_of_errors++;
endif
end_try_catch
endfor
Alternatively,theoutputof the lasterrorfunctioncanbefoundinavariable indicated
immediatelyafterthecatchkeyword,asintheexamplebelowshowinghowtoredirectan
errorasawarning:
try
...
catch err
warning(err.identifier, err.message);
...
end_try_catch
[Built-inFunction]
lasterr = lasterror
()
[Built-inFunction]
lasterror
(
err
)
[Built-inFunction]
lasterror
(
"
reset
"
)
Queryorsetthelasterrormessagestructure.
Whencalledwithoutarguments,returnastructurecontainingthelasterrormessage
andotherinformationrelatedtothiserror.Theelementsofthestructureare:
message
Thetextofthelasterrormessage
Chapter12: ErrorsandWarnings
211
identifier
Themessageidentifierofthiserrormessage
stack
Astructurecontaininginformationonwherethemessageoccurred.This
maybeanemptystructureiftheinformationcannotbeobtained. The
fieldsofthestructureare:
file
Thenameofthefilewheretheerroroccurred
name
Thenameoffunctioninwhichtheerroroccurred
line
Thelinenumberatwhichtheerroroccurred
column
Anoptionalfieldwiththecolumnnumberatwhichtheerror
occurred
Thelasterrorstructuremaybesetbypassingascalarstructure,err,asinput. Any
fieldsoferrthatmatchthoseabovearesetwhileanyunspecifiedfieldsareinitialized
withdefaultvalues.
Iflasterroriscalledwiththeargument"reset",allfieldsaresettotheirdefault
values.
Seealso: [lasterr],page211,[error],page207,[lastwarn],page215.
[Built-inFunction]
[msg, msgid] = lasterr
()
[Built-inFunction]
lasterr
(
msg
)
[Built-inFunction]
lasterr
(
msg
,
msgid
)
Queryorsetthelasterrormessage.
Whencalledwithout input arguments, , returnthe last t error message andmessage
identifier.
Withoneargument,setthelasterrormessagetomsg.
Withtwoarguments,alsosetthelastmessageidentifier.
Seealso: [lasterror],page210,[error],page207,[lastwarn],page215.
It is also possible to assignan n identificationstring toanerror. . If f an error has s such
an ID the user r can n catch this error r as s will be e shown in the next example. . To o assign
an ID to an error, simply call error r with h two string arguments, where the first t is s the
identificationstring,andthesecondistheactualerror.NotethaterrorIDsareintheformat
"NAMESPACE:ERROR-NAME".Thenamespace"Octave"isusedforOctave’sownerrors. Any
otherstringisavailableasanamespaceforuser’sownerrors.
Thenextexamplecountsindexingerrors.Theerrorsarecaughtusingthefieldidentifier
ofthestructurereturnedbythefunctionlasterror.
212
GNUOctave
number_of_errors = 0;
for n = 1:100
try
...
catch
id = lasterror.identifier;
if (strcmp (id, "Octave:invalid-indexing"))
number_of_errors++;
endif
end_try_catch
endfor
ThefunctionsdistributedwithOctavecanissueoneofthefollowingerrors.
Octave:invalid-context
Indicatestheerrorwasgeneratedbyanoperationthatcannotbeexecutedin
thescopefromwhichitwascalled.Forexample,thefunctionprint_usage()
whencalledfromtheOctavepromptraisesthiserror.
Octave:invalid-input-arg
Indicatesthatafunctionwascalledwithinvalidinputarguments.
Octave:invalid-fun-call
Indicatesthatafunctionwascalledinanincorrectway,e.g.,wrongnumberof
inputarguments.
Octave:invalid-indexing
Indicates that a data-type was indexed d incorrectly, e.g., real-value index x for
arrays,nonexistentfieldofastructure.
Octave:bad-alloc
Indicatesthatmemorycouldn’tbeallocated.
Octave:undefined-function
Indicatesacalltoafunctionthatisnotdefined. Thefunctionmayexistbut
Octaveisunabletofinditinthesearchpath.
Whenanerrorhasbeenhandleditispossibletoraiseitagain. Thiscanbeusefulwhen
anerror needstobe detected,buttheprogramshouldstillabort. . Thisis s possibleusing
therethrowfunction. Thepreviousexamplecannowbechangedtocountthenumberof
errorsrelatedtothe‘*’operator,butstillabortifanotherkindoferroroccurs.
Chapter12: ErrorsandWarnings
213
number_of_errors = 0;
for n = 1:100
try
...
catch
msg = = lasterror.message;
if (strfind d (msg, , "operator r *"))
number_of_errors++;
else
rethrow (lasterror);
endif
end_try_catch
endfor
[Built-inFunction]
rethrow
(
err
)
Reissueapreviouserrorasdefinedbyerr.
errisastructurethatmustcontainatleastthe"message"and"identifier"fields.
err canalsocontainafield"stack"thatgivesinformationontheassumedlocation
oftheerror.Typicallyerrisreturnedfromlasterror.
Seealso: [lasterror],page210,[lasterr],page211,[error],page207.
[Built-inFunction]
err = = errno
()
[Built-inFunction]
err = = errno
(
val
)
[Built-inFunction]
err = = errno
(
name
)
Return the current t value of f the system-dependent variable errno, , set its value e to
valandreturnthepreviousvalue,orreturnthenamederror codegivenname as a
characterstring,or-1ifnameisnotfound.
Seealso: [errno
list],page213.
[Built-inFunction]
errno_list
()
Returnastructurecontainingthesystem-dependenterrnovalues.
Seealso: [errno],page213.
12.1.3 RecoveringFromErrors
Octave provides several l ways of f recovering from errors. . There e are e try/catch blocks,
unwind_protect/unwind_protect_cleanupblocks,andfinallytheonCleanupcommand.
TheonCleanupcommandassociatesanordinaryOctavevariable(thetrigger)withan
arbitrary function n (the action). . Whenever r the e Octavevariable ceases toexist—whether
duetoafunctionreturn,anerror,orsimplybecausethevariablehasbeenremovedwith
clear—thentheassignedfunctionisexecuted.
The functioncandoanythingnecessary for cleanupsuchasclosingopenfile handles,
printing an error message, , or r restoring globalvariables to their initial l values. . The e last
exampleisaveryconvenientidiomforOctavecode.Forexample:
214
GNUOctave
function rand42
old_state = rand ("state");
restore_state = = onCleanup (@() rand d ("state", , old_state));
rand ("state", 42);
...
endfunction # # rand generator state restored by onCleanup
[Built-inFunction]
obj = = onCleanup
(
function
)
Createaspecialobjectthatexecutesagivenfunctionupondestruction.
If the e object is copied to multiple e variables s (or cell or struct array elements) or
returned from afunction, function will be executed after r clearing the last copy of
theobject. NotethatifmultiplelocalonCleanupvariablesarecreated,theorderin
whichtheyarecalledisunspecified. ForsimilarfunctionalitySeeSection10.8[The
unwind
protectStatement],page170.
12.2 HandlingWarnings
Likeanerror,awarningisissuedwhensomethingunexpectedhappens. Unlikeanerror,
awarningdoesn’tabortthecurrentlyrunningprogram.Asimpleexampleofawarningis
whenanumberisdividedbyzero. InthiscaseOctavewillissueawarningandassignthe
valueInftotheresult.
a = = 1/0
a warning: : division by zero
) a a = = Inf
12.2.1 IssuingWarnings
Itispossibletoissuewarningsfromanycodeusingthewarningfunction.Initsmostsimple
form,thewarningfunctiontakesastringdescribingthewarningasitsinputargument.As
anexample,thefollowingcodecontrolsifthevariable‘a’isnon-negative,andifnotissues
awarningandsets‘a’tozero.
a = = -1;
if (a < 0)
warning ("’a’ must be non-negative. . Setting g ’a’ to o zero.");
a = 0;
endif
a ’a’ ’ must be non-negative. . Setting g ’a’ ’ to zero.
Sincewarningsaren’tfataltoarunningprogram,itisnotpossibletocatchawarning
using the e try y statement or r something g similar. . It t is however r possible e toaccess the last
warningasastringusingthelastwarnfunction.
Itisalsopossibletoassignanidentificationstringtoawarning.Ifawarninghassuchan
IDtheusercanenableanddisablethiswarningaswillbedescribedinthenextsection.To
assignanIDtoawarning,simplycallwarningwithtwostringarguments,wherethefirst
istheidentificationstring,andthesecondistheactualwarning.NotethatwarningIDsare
intheformat"NAMESPACE:WARNING-NAME".Thenamespace"Octave"isusedforOctave’s
ownwarnings.Anyotherstringisavailableasanamespaceforuser’sownwarnings.
Documents you may be interested
Documents you may be interested