1\input texinfo	@c -*-texinfo-*-
2@comment Copyright (C) 1994-2004  K. Scott Hunziker.
3@comment Copyright (C) 1990-1994  The Boeing Company.
4@comment %**start of header (This is for running Texinfo on a region.)
5@setfilename algae.info
6@settitle Algae
7@setchapternewpage odd
8@comment %**end of header (This is for running Texinfo on a region.)
9
10@ifinfo
11@dircategory Programming Languages
12@direntry
13* algae: (algae).		Another Matrix Programming Language
14@end direntry
15@end ifinfo
16
17@titlepage
18@title The Algae Programming Language
19@subtitle For algae VERSION_NUMBER; VERSION_DATE.
20@author by K. Scott Hunziker
21@tex
22\special{papersize=8.5in,11in}
23\special{psfile=algae_fig.eps hoffset=-60 voffset=-180}
24@end tex
25@page
26@vskip 0pt plus 1filll
27Algae VERSION_NUMBER; VERSION_DATE
28@sp 1
29Copyright @copyright{} 1994--2004  K. Scott Hunziker.@*
30Copyright @copyright{} 1990--1994  The Boeing Company.
31@sp 1
32Algae is free software.  You may redistribute it and/or modify it
33under the terms of the GNU General Public License as published by
34the Free Software Foundation; either version 2 of the License, or
35(at your option) any later version.
36@sp 1
37Algae is distributed in the hope that it will be useful, but WITHOUT
38ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
39or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
40License for more details.
41@sp 1
42You should have received a copy of the GNU General Public License
43along with Algae; see the file @file{LICENSE}.  If not, write to the Free
44Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.@refill
45@sp 1
46The copyright to major portions of Algae belongs to The Boeing
47Company.  The following permission notice and warranty disclaimer
48pertain to those portions of the code:
49@sp 1
50@quotation
51Permission to use, copy, modify, and distribute this software and its
52documentation for any purpose is hereby granted, provided that the above
53copyright notice appear in all copies, that both the copyright notice
54and this permission notice and warranty disclaimer appear in supporting
55documentation, and that the names of Boeing or any of its entities not
56be used in advertising or publicity pertaining to distribution of the
57software without specific, written, prior permission.@refill
58@sp 1
59BOEING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
60ALL IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS, AND NONINFRINGEMENT.
61IN NO EVENT SHALL BOEING BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
62CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
63USE, DATA, OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE, OR
64OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
65PERFORMANCE OF THIS SOFTWARE.@refill
66@end quotation
67
68@comment This is funny, but I think that the JIR has a copyright on it.
69@ignore
70Notice:  The entire physical universe, including this product, may one
71day collapse back into an infinitesimally small space.  Should another
72universe subsequently emerge, the existence of this product in that
73universe cannot be guaranteed.@refill
74@end ignore
75
76@sp 1
77Caution: Use of this product as a substitute for a healthy physical,
78emotional, and spiritual life is not recommended and could be harmful.
79@end titlepage
80@page
81
82@node Top, About Algae, (dir), (dir)
83
84@ifhtml
85@html
86<h2>Another Matrix Programming Language</h2>
87<h2>VERSION_NUMBER; VERSION_DATE</h2>
88<i>by K. Scott Hunziker</i>
89<p>
90Next time you're in Seattle, visit the
91<a href="http://algae.sourceforge.net/">Algae Home Page</a>.
92<p>
93<hr>
94
95@end html
96@end ifhtml
97
98@ifinfo
99For algae VERSION_NUMBER; VERSION_DATE.
100
101Typing "q" exits, "?" lists all INFO commands, "h" gives an INFO
102tutorial, "m" selects menu items, etc.  Items are selected by any unique
103case-insensitive abbreviation of their name.  For example, type "m" and
104then "prim" to select the `Primer' item in the menu below.
105@end ifinfo
106
107@ifnottex
108@menu
109* About Algae::			History and acknowledgments.
110* Primer::			An introduction to Algae.
111* Examples::			Some example programs in Algae.
112* Language::			Variables, operators, and expressions.
113* Data::        		Scalars, vectors, matrices, ...
114* Standard Functions::  	Reference guide for the standard functions.
115* Running Algae::	        Starting and running the Algae interpreter.
116* Projects::			The Algae wish list.
117* Bugs::			Bugs, and how to report them.
118* Concept Index::		An item for each concept.
119* Function Index::		An item for each standard function.
120@end menu
121
122@noindent
123Copyright @copyright{} 1994--2004  K. Scott Hunziker.@*
124Copyright @copyright{} 1990--1994  The Boeing Company.
125
126Algae is free software.  You may redistribute it and/or modify it
127under the terms of the GNU General Public License as published by
128the Free Software Foundation; either version 2 of the License, or
129(at your option) any later version.
130
131Algae is distributed in the hope that it will be useful, but WITHOUT
132ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
133or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
134License for more details.
135
136You should have received a copy of the GNU General Public License along
137with Algae; see the file @file{LICENSE}.  If not, write to the Free
138Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.@refill
139
140The copyright to major portions of Algae belongs to The Boeing
141Company.  The following permission notice and warranty disclaimer
142pertain to those portions of the code:
143
144@quotation
145Permission to use, copy, modify, and distribute this software and its
146documentation for any purpose is hereby granted, provided that the above
147copyright notice appear in all copies, that both the copyright notice
148and this permission notice and warranty disclaimer appear in supporting
149documentation, and that the names of Boeing or any of its entities not
150be used in advertising or publicity pertaining to distribution of the
151software without specific, written, prior permission.@refill
152
153BOEING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
154INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS,
155AND NONINFRINGEMENT.  IN NO EVENT SHALL BOEING BE LIABLE FOR ANY
156SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY
157DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA, OR PROFITS,
158WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE, OR OTHER TORTIOUS
159ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
160PERFORMANCE OF THIS SOFTWARE.@refill
161@end quotation
162
163Caution: Use of this product as a substitute for a healthy physical,
164emotional, and spiritual life is not recommended and could be harmful.
165@end ifnottex
166
167@node About Algae, Primer, Top, Top
168@chapter About Algae
169@cindex Hunziker, Scott
170@cindex Hunziker, Jennifer
171@cindex Brennan, Mike
172@cindex MATLAB
173Algae is an interpreted language for numerical analysis.  Algae was
174developed because we needed a fast and versatile tool, capable of
175handling large problems.  Algae has been applied to interesting dynamics
176problems in aerospace and related fields for more than a decade.@refill
177
178This document describes both Algae, the programming language, and
179@code{algae}, the interpreter.  Neither one of them is complete.  Even
180so, they offer some unique capabilities that we hope you'll find
181useful.@refill
182
183Algae was designed and implemented by Scott Hunziker and Mike Brennan.
184
185Algae grew up in the ``Structures Outback'' of the Boeing Aerospace
186Company (now the Boeing Defense & Space Group).  Way back in 1989, Bill
187Russell convinced Bob Vos, the head of Boeing's ISM project, that ISM
188needed an interactive language.  With Dave Beste's help, Bill put
189together a crude system (it looked a lot like MATLAB) with a recursive
190descent parser.  They called it ISMLAB.  After Bill got a real job,
191Scott Hunziker took over and made major changes.  ISMLAB, along with the
192entire ISM project, was cancelled ignominiously in 1991.@refill
193
194Scott Hunziker and Mike Brennan began work on a successor to ISMLAB
195called AMPL (A Matrix Programming Language) with internal Boeing
196funding.  (The author remembers well the first day of their
197collaboration, when he inadvertently showed Mike that AMPL could
198multiply two matrices and get the wrong answer.)  As AMPL took shape,
199the internal funding dried up, leaving Scott to maintain it in his spare
200time.  Boeing generously released AMPL to the public in 1994.  The name
201was changed to Alki in 1995 because, by then, an unrelated package
202called AMPL was being distributed through netlib.  That name also had a
203conflict, and it was finally changed to Algae in early 1997.@refill
204
205Thanks to Don Morris for contributing the plotting code (not to
206mention countless bug reports), and Ian Searle for advice, constructive
207criticism, and pizza.@refill
208
209@node Primer, Examples, About Algae, Top
210@chapter Primer
211@cindex Starting algae
212@cindex Interactive mode
213
214What follows is a quick introduction to Algae.  It shows many simple
215examples, but leaves out the detailed descriptions.  @xref{Language},
216for more details about the Algae language.@refill
217
218The first thing that you'll need to know is how to get Algae
219started.  If your system is properly set up, it's a simple matter of
220typing the command @samp{algae}.  This brings Algae up in
221interactive mode; a prompt is displayed and it waits for you to start
222typing statements.  Later we'll discuss other options, such as giving
223Algae a file of statements to execute in ``batch'' mode.@refill
224
225This manual is available on-line through the @code{info} function; type
226@code{info()} to view it.  You can go to a specific topic by naming it
227as an argument.  For example, @code{info("operators")} takes you
228directly to the description of Algae's operators.@refill
229
230@cindex Statements
231@cindex Terminating statements
232@cindex Statement terminators
233@cindex Newline
234@cindex Question mark
235@cindex Semicolon
236@cindex ? (statement terminator)
237@cindex ; (statement terminator)
238An Algae @dfn{statement} describes the operations to be performed.  For
239example, the statement@refill
240
241@example
2421+sin(2)
243@end example
244
245@noindent
246tells Algae to add 1 to the sine of 2.  Statements may be terminated with
247a newline, a semicolon, or a question mark; the results are printed
248unless a semicolon is used.@refill
249
250The statement
251
252@example
253printf ("hello, world\n");
254@end example
255
256@noindent
257prints a hopeful little ``hello, world'' message to the terminal.  This
258is exactly like the C language, right down to the @samp{\n} escape
259sequence to indicate a newline.  If you know C, you'll probably notice
260many other similarities between its syntax and that of Algae.@refill
261
262@cindex Variables
263Like most computer languages, Algae has @dfn{variables} to which values
264can be assigned.  In Algae, these variables need not be declared before
265being used, and may be created or destroyed during a session.  If you
266type the statement @code{x=1}, the variable @code{x} will be created if
267it doesn't already exist.  If @code{x} already had a value, then
268assignment to @code{x} destroys its previous contents.@refill
269
270@cindex Entities
271@cindex Class of entities
272The values taken on by variables are known as @dfn{entities}, which have
273various @dfn{classes} such as @samp{scalar}, @samp{vector},
274@samp{matrix}, @samp{table}, etc.  A builtin function called
275@code{class} returns the class of its argument, so if you make the
276assignment @code{x=1} then the statement @code{class(x)} returns
277@samp{"scalar"}.@refill
278
279@cindex Converting between classes
280@cindex Automatic class conversion
281@cindex Class conversions
282Notice that a scalar is not the same thing as a one-element vector or as
283a one-by-one matrix.  The builtin functions @code{scalar},
284@code{vector}, and @code{matrix} may be used to convert from one to
285another.  For example, @code{matrix(7)} returns a matrix with one row
286and one column, its single element having the value 7.  Algae will often
287make these conversions between classes automatically.  In the
288code@refill
289
290@example
291x = [ 3, 2, 1 ];
292y = sort (x);
293@end example
294
295@noindent
296the @code{sort} function first converts its matrix argument @code{x}
297into a vector and then returns another vector with the same elements but
298sorted in increasing order.  (An expression enclosed in brackets defines
299a matrix, as we'll discuss later.)@refill
300
301@cindex Members
302@cindex Entity members
303@cindex Dot operator
304@cindex Predefined members
305@cindex Creating new members
306Besides its class, an entity may have other attributes which are stored
307as its @dfn{members}.  For example, the number of rows in a matrix is
308stored in a member called ``nr''.  Members are referenced with the ``dot''
309operator, so if @code{M} is a matrix, then @code{M.nr} returns its row
310size.  Most entities have one or more predefined members (such as
311@code{nr} in matrices) that you cannot directly modify.  You can create
312new members simply by assignment.@refill
313
314A function called @code{show} prints information about an entity and its
315members.  Another function, @code{members}, returns a vector containing
316the names of all the members of its argument.
317
318@cindex NULL
319@cindex Deleting entities
320@cindex Operations on NULL
321When a non-existent variable or member is referenced, the special value
322@code{NULL} is returned.  For example, the line@refill
323
324@example
325a = 1; a.nr
326@end example
327
328@noindent
329(which consists of two statements) prints ``NULL'', since scalars do not
330start life with a member @code{nr}.@refill
331
332The NULL constant may be used on the right-hand side of assignments,
333effectively deleting the previous value of an entity.  Actually, the
334entity still exists, but it has the value NULL.  You can perform a
335number of other operations on NULL, such as in@refill
336
337@example
338if (x != NULL) @{ x.class? @}
339@end example
340
341@cindex Types
342@cindex Integer type
343@cindex Real type
344@cindex Complex type
345@cindex Character type
346@cindex Strings
347All array entities (and that includes scalars) have a member called
348@code{type}, which may have one of these values: ``integer'', ``real'',
349``complex'', or ``character''.  The constant @code{1} is an integer, but
350@code{1.0} has real type.  Algae has no complex constant like Fortran
351does---you have to use an expression such as @code{sqrt(-1)}.  Users
352often make the assignment @code{i=sqrt(-1)} when they first start up
353Algae and then use expressions like @code{1+2*i} for their complex
354numbers.@refill
355
356The ``character'' type refers to a string of characters.  It is
357specified using double-quotes as we did for @code{"hello world"} above.
358A character scalar like @code{"1"} is different than an integer scalar
359like @code{1}, and an expression like @code{1+"1"} is not allowed.@refill
360
361@cindex Vectors
362@cindex Element numbering in vectors
363A @dfn{vector} is a one-dimensional array of values.  For example,
364@code{x=1,2,3} specifies a vector with three elements.  The elements in
365a vector are numbered starting at one, and the total number of elements
366is given by its @code{ne} member.  All of the elements have the same
367type.@refill
368
369@cindex Append operator
370@cindex Comma
371@cindex , (append operator)
372Actually, the comma character is Algae's ``append'' operator.  You can
373put several expressions together in a vector, as in
374
375@example
376v = 1, sin(2), 3+4;
377@end example
378
379@cindex Subvector expressions
380A ``subvector'' expression may be used to specify a particular element
381or elements.  You do that simply by following the vector with a
382@dfn{specifier} enclosed in brackets.  For example, @code{v[3]} gives a
383scalar having the value of the third element of @code{v}.  If the
384specifier is a scalar, then the result is a scalar; otherwise, the
385result is a vector.@refill
386
387A more complicated example is@refill
388
389@example
390aset = 3, 9, 15;
391x = v[aset][2];
392@end example
393
394@cindex Subvector assignment
395@noindent
396Here, @code{x} gets the value of the ninth element of @code{v}.  You can
397also assign to a subvector, so @code{v[1]=0} sets the first element of
398@code{v} to zero.
399
400@cindex Vector labels
401@cindex Matching labels
402Vectors have a member @code{eid} (it stands for @i{element id}) that
403contains labels for its elements.  You don't need labels (@code{eid} may
404be NULL), but they can be pretty useful.  For one thing, they can help
405you to avoid errors by not allowing you to perform certain operations
406unless the labels match.  If you try to add two vectors and they both
407have labels, then the labels must be identical.
408
409@cindex Labels in subvector expressions
410You can also use labels instead of element numbers in a subvector
411expression.  You do this by using character strings as the specifier.
412For example, the code
413
414@example
415weight =        172,    216,     188;
416weight.eid =  "Tom", "Dick", "Harry";
417@end example
418
419@noindent
420sets up the vector @code{weight} with character string labels.  Then
421@code{weight["Dick"]} gives Dick's weight of 216.@refill
422
423@cindex Generating vectors
424@cindex Vector generation
425@cindex Generate operator
426@cindex Colon
427@cindex : (vector generation operator)
428Vectors can be generated by using the colon operator.  The expression
429@code{1:5:2} gives a vector whose first element is @code{1}, last
430element is no more than @code{5}, and has a difference of @code{2}
431between each successive element.  In other words, @code{1:5:2} is the
432same as @code{1,3,5}.  If you leave off the second colon and the third
433operand, then Algae infers a @code{1} for the third operand.  Thus, if
434@code{n=100}, then @code{1:n} is the vector containing all the integers
435from @code{1} through @code{100}.@refill
436
437@cindex Matrices
438A @dfn{matrix} is a two-dimensional array of values.  The expression
439@code{[1,2;3,4;5,6]} specifies a matrix with three rows and two
440columns---rows are given as vectors and are separated by semicolons.
441
442@cindex Submatrix expressions
443@cindex Element numbering in matrices
444Submatrix expressions work just like subvector expressions, but with a
445semicolon to separate the row specifier from the column specifier.  The
446expression @code{M[3;2,3]} gives a vector containing the elements of
447@code{M} in its third row and second and third columns.  If both
448specifiers are scalars, then the result is a scalar.  If only one
449specifier is a scalar, then the result is a vector.  Otherwise, the
450result is a matrix.  The members @code{nr} and @code{nc} give the number
451of rows and columns of a matrix.@refill
452
453@cindex Matrix labels
454@cindex Labels in submatrix expressions
455Matrices have both row and column labels.  They're stored in the members
456@code{rid} and @code{cid}, respectively.  As with vectors, character
457strings used as specifiers in submatrix expressions refer to the
458labels.@refill
459
460@cindex Tables
461@cindex Braces
462A @dfn{table} is an entity that simply holds a collection of other
463entities.  For example, the statements@refill
464
465@example
466x = 1; y = "foo", "bar";
467t = @{ x; y @};
468@end example
469
470@noindent
471result in a table @code{t} that contains the scalar @code{x} and the
472vector @code{y}.  Instead, we could write
473
474@example
475t = @{ x = 1; y = "foo", "bar" @};
476@end example
477
478@noindent
479and get the same table.  In the latter case, though, @code{x} and
480@code{y} exist only inside the table.
481
482@cindex Operations on tables
483You can put any class of entity into a table, even another table.  The
484members are referenced with the ``dot'' operator, just like the other
485entities.  The line @code{a=@{u=1;v=2@}; a.u+a.v} prints the value 3.  You
486can add two tables (the members of the right-hand table are inserted
487into the left-hand table) and subtract two tables (the members of the
488left-hand table having the same name as a member of the right-hand table
489are removed).@refill
490
491@cindex if statement
492@cindex Control-flow statements
493@cindex Statements for control-flow
494Algae normally executes statements in the order that it receives them,
495but the control-flow statements @code{if}, @code{for}, @code{while}, and
496@code{try} can change that.  The code@refill
497
498@example
499if (x > 0) @{ y = 1/x; @}
500@end example
501
502@noindent
503is an example of an @code{if} statement.  The parentheses are required
504around the test expression.  If that expression is ``true'', then the
505statements following it are executed.  The @code{if} statement may also
506have an @code{elseif} part, an @code{else} part, or both, so@refill
507
508@example
509if (x > 0)
510@{
511    printf ("positive");
512elseif (x < 0)
513    printf ("negative");
514else
515    printf ("zero");
516@}
517@end example
518
519@noindent
520prints the sign of @code{x}.  (But you should use the @code{sign}
521function, instead.)@refill
522
523@cindex Relational operators
524@cindex Equality operators
525@cindex Logical operators
526@cindex < (less than operator)
527@cindex <= (less or equal operator)
528@cindex > (greater than operator)
529@cindex >= (greater or equal operator)
530@cindex == (equality operator)
531@cindex != (inequality operator)
532@cindex And operator
533@cindex & (and operator)
534@cindex Or operator
535@cindex | (or operator)
536@cindex && (and operator)
537@cindex || (or operator)
538@cindex Not operator
539@cindex ! (not operator)
540As long as only scalars are involved, Algae's relational, equality, and
541logical operators probably won't surprise you.  An expression is
542@code{1} if it's true and @code{0} if it's false.  The relational
543operators are @code{>}, @code{>=}, @code{<}, @code{<=}.  The equality
544operators are @code{==} and @code{!=}.  The logical operators are
545@code{&}, @code{|}, and @code{!}.  Two additional logical operators,
546@code{&&} and @code{||}, are special; they are described later.
547
548Where these operators might surprise you is when vectors and matrices
549are involved.  Like most Algae operators, they work on an
550element-by-element basis.  For example, if @code{A} and @code{B} are
551both matrices, then the expression @code{A==B} has several features:
552
553@itemize @bullet
554@item
555@code{A} and @code{B} must have the same size.
556
557@item
558Their labels must match.
559
560@item
561The expression returns a matrix with the same size as @code{A} and
562@code{B}, every element of which is either @code{1} or @code{0}
563depending on whether the corresponding elements of @code{A} and @code{B}
564are equal.
565@end itemize
566
567@noindent
568You can see, then, that @code{A==B} doesn't give you a simple true or
569false answer but rather a matrix of answers.
570
571@cindex True
572@cindex False
573The @code{if} statement, however, does need a simple true or false in
574order to decide whether to execute its statements or not.  It does this
575by recognizing certain entities as false---all others are true.  The
576``false'' entities are as follows:
577
578@itemize @bullet
579@item
580NULL.
581
582@item
583Numeric entities in which every element is zero.
584
585@item
586Character entities in which every element is @code{""}.
587
588@item
589Vectors and matrices with no elements.
590
591@item
592Tables with no members.
593@end itemize
594
595@cindex Testing for equality
596What gets new users into trouble is a statement like
597
598@example
599if (A == B) @{ done = 1; @}
600@end example
601
602@noindent
603If @code{A} and @code{B} are matrices, then @code{A==B} returns a matrix
604of ones and zeros.  The @code{if} statement interprets that as ``true''
605if even one of its elements is nonzero.  In words, the above statement
606starts out ``If any element of @code{A} is equal to the corresponding
607element of @code{B}, then @dots{}''  The difficulty is that the
608element-by-element ``equality'' operation is not the same as a test of
609the equality of two arrays.  If the latter test is what you really want,
610then you should use the @code{equal} function instead.@refill
611
612On the other hand, the statement
613
614@example
615if (A != B) @{ done = 0; @}
616@end example
617
618@noindent
619does work in both senses.  The expression @code{A!=B} returns a matrix
620that has nonzero elements where the corresponding elements of @code{A}
621and @code{B} are unequal.  Thus this expression also serves as a test of
622the inequality of the two arrays.@refill
623
624The @code{&&} ("and") and @code{||} ("or") operators are special in two
625ways:  they don't perform element-by-element like the other operators in
626this section, and they "short-circuit" by skipping evaluation of the
627second operand if the result is already established by the first
628operand.@refill
629
630Each operand of @code{&&} and @code{||} is evaluated for "truth" in the
631same way that the @code{if} test does.  For @code{&&}, if the first
632operand evaluates to "false" then the second operand is not evaluated
633and the result of the operation is 0.  For @code{||}, if the first
634operand evaluates to "true" then the second operand is not evaluated and
635the result of the operation is 1.@refill
636
637For example, in the expression
638
639@example
640x != NULL && x.type == "integer"
641@end example
642
643@noindent
644@code{x} is first checked to see if it's NULL.  If it is, then the first
645operand of @code{&&} is 0 and that's also the result of the entire
646expression.  In that case, the member reference @code{x.type} is never
647evaluated.  This is convenient, since that would otherwise be an
648error.@refill
649
650An @code{if} statement such as
651
652@example
653if (x < tol) @{ x = tol; @}
654@end example
655
656@noindent
657could be written instead as
658
659@example
660x < tol && (x = tol);
661@end example
662
663The parentheses are required in the second version, since the precedence
664of @code{=} is lower than that of @code{&&}.  Although they accomplish
665the same thing, the first version is recommended; it is easier to read
666and executes a bit faster.@refill
667
668@cindex while statement
669@cindex Loops
670Algae has two control-flow statements that perform looping:
671@code{while} and @code{for}.  The @code{while} statement executes a set
672of statements over and over, as long as a given condition is true.  For
673example, the code@refill
674
675@example
676a=0; b=1;
677while (b < 10000)
678@{
679  c = b;
680  b = a+b;
681  a = c;
682@}
683c?
684@end example
685
686@noindent
687computes and prints the largest Fibonacci number less than 10000.  The
688interpreter checks to make sure that @code{b<10000}, executes the
689statements in the @code{while} block, and then repeats.  The first time
690that the expression @code{b<10000} evaluates false, the loop
691terminates.@refill
692
693@cindex for statement
694@cindex Loops
695@cindex in keyword
696The @code{for} statement also causes looping, but in a different way.
697Assuming that @code{v} is a numeric vector, the code@refill
698
699@example
700for (i in 1:v.ne) @{ v[i] = 1 / v[i]; @}
701@end example
702
703@noindent
704inverts each of its members.  Inside the parentheses, the keyword
705@code{in} separates an identifier on the left and a vector expression on
706the right.  In this example, the vector expression is @code{1:v.ne}
707which contains the integers from 1 to the length of @code{v}.  The
708@code{for} loop sets @code{i} equal to the first element, 1, and then
709executes the statement @code{v[i]=1.0/v[i];}.  Then @code{i} is set
710equal to the second element, and the statement is executed again.  This
711cycle repeats until all of the elements of @code{1:v.ne} are used.@refill
712
713@cindex Efficiency of loops
714The previous example also illustrates an important topic concerning both
715@code{while} loops and @code{for} loops.  Essentially the same results
716would be obtained with the statement @code{v=1/v}.  This obviously takes
717less typing and is easier to read.  The really important difference,
718though, is that it is far more efficient.  With the @code{for} loop, all
719of the operations (assignment, division, etc.) are performed by the
720interpreter.  Although Algae is fast, it can't possibly compete
721with doing the same job in C, as @code{v=1/v} is.  On my computer, it's
722about 60 times faster.@refill
723
724@cindex Interrupting loops
725@cindex continue statement
726Sometimes it's convenient to interrupt the execution of @code{while} and
727@code{for} loops.  The @code{continue} statement causes another
728iteration of the loop to begin immediately.  If we wanted to invert the
729nonzero elements of a vector, we could write@refill
730
731@example
732for (i in 1:v.ne)
733@{
734  if (v[i] == 0) @{ continue; @}
735  v[i] = 1 / v[i];
736@}
737@end example
738
739@cindex break statement
740The @code{break} statement goes even further, exiting the loop
741altogether.  For example, we could have written our Fibonacci routine
742as@refill
743
744@example
745a=0; b=1;
746while (1)
747@{
748  c = b;
749  if ((b = a+b) > 10000) @{ break; @}
750  a = c;
751@}
752c?
753@end example
754
755@noindent
756The @code{continue} and @code{break} statements affect execution of only
757the innermost enclosing loop.@refill
758
759It's important to note that @code{continue} and @code{break} are
760statements, not expressions.  The code@refill
761
762@example
763x < 0 && break;
764@end example
765
766@noindent
767is not valid, since the operands of @code{&&} must be expressions.@refill
768
769@cindex try
770@cindex exceptions
771@cindex raise an exception
772The @code{try} statement is the remaining control-flow statement.  It is
773used to modify Algae's response to something called an @dfn{exception}.
774When an exception occurs, we say that it has been ``raised''.  Many
775error conditions (dividing by zero, running out of memory, etc.) cause
776an exception to be raised.  You may also raise an exception directly
777by calling the @code{exception} function.@refill
778
779When an exception is raised, Algae's default action is to stop
780execution.  If it's running interactively, it returns to the command
781line prompt; otherwise it exits completely.  This action can be modified
782by using the @code{try} statement.  If an exception is raised within the
783@code{try} block, execution continues at the point immediately following
784that block.  For example, the statement@refill
785
786@example
787try @{ i += 1; @}
788@end example
789
790@noindent
791increments @code{i} by one if possible.  If an error occurs (say
792@code{i} was NULL), then Algae just moves on to execute the next line.
793Although it's probably not a good idea, we could use this instead of
794@code{break} in the previous Fibonacci example:@refill
795
796@example
797a=0; b=1;
798try
799@{
800  while (1)
801  @{
802    c = b;
803    if ((b = a+b) > 10000) @{ exception (); @}
804    a = c;
805  @}
806@}
807c?
808@end example
809
810@noindent
811There's a real difference between these approaches, though.  In the
812version using the @code{break} statement, the result is printed only
813when the correct value is reached.  In the @code{try} version, the
814result is printed regardless of why the exception was raised---if Algae
815received an interrupt signal while in the middle of the loop, it would
816jump out of the @code{try} block and then print an incorrect value.@refill
817
818@cindex catch
819The @code{try} statement has an optional @code{catch} clause, which is
820something like the @code{else} clause of an @code{if} statement.  Any
821statements that follow @code{catch} are executed only if an exception is
822raised while in the preceding part of the @code{try} block.  Also,
823exceptions that occur within the @code{catch} block are not handled
824specially.  For example,@refill
825
826@example
827try
828@{
829  v = 1/v;
830catch
831  message ("I can't do that, Dave.");
832  exception ();
833@}
834@end example
835
836would print a message if it had trouble performing the inverse and then
837stop execution.  If no exception occurs prior to the @code{catch}
838clause, then execution continues following the end of the @code{try}
839statement.@refill
840
841The language syntax does not allow a @code{break} or @code{continue}
842statement to be positioned such that it would cause execution to jump
843out of the @code{try} block.@refill
844
845@cindex Functions
846@cindex Builtin functions
847@cindex User functions
848@cindex Arguments of functions
849@cindex Separating arguments
850@cindex Passing arguments by value
851@cindex Call by value
852Like other computer languages, Algae has @dfn{functions}.  Some functions
853(like @code{sin} and @code{printf}) are @dfn{builtin}, meaning that they
854are part of the Algae executable file.  Others, called @dfn{user
855functions}, are those written in the Algae language.  A function is
856called by giving its name followed by a parenthesized list of
857@dfn{arguments}.  The arguments are separated by semicolons, and their
858values are passed to the function.  Since only the values are passed,
859the function cannot modify the variables that you pass it.@refill
860
861For example, let's assume that you're calling the function @code{shady}.
862
863@example
864x = 1;
865y = shady (x);
866@end example
867
868@noindent
869The value returned by @code{shady} is assigned to @code{y}.  You can't
870tell by looking at it what class of entity (scalar, matrix, etc.)
871@code{shady} returns.  In fact, that might even change from one call to
872the next.  Rest assured, though, the value of @code{x} is still 1, no
873matter what happened in @code{shady}.@refill
874
875@cindex Operations on functions
876Algae functions are entities---just like scalars and matrices.  That
877means that you can perform operations on them as you do with other
878entities.  For example, the statement@refill
879
880@example
881my_sin = sin
882@end example
883
884@noindent
885creates a new function called @code{my_sin} that works just like the
886original @code{sin} function.  Of course,
887
888@example
889sin = NULL;
890@end example
891
892@noindent
893gets rid of the @code{sin} function completely---probably not a very
894good idea in most cases.@refill
895
896@cindex Defining functions
897Functions may be defined during an interactive session or simply
898included from files.  As an example, consider writing a function called
899``findit'' that will look through the elements of a vector for a given
900value, returning the locations where it found it.  The following
901function should do the job:@refill
902
903@example
904findit = function (s; v)
905@{
906  local (w; i);
907  w = vector ();
908  for (i in 1:v.ne)
909  @{
910    if (v[i] == s) @{ w = w, i; @}
911  @}
912  return w;
913@}
914@end example
915
916@noindent
917@cindex local statement
918@cindex Scope of variables
919@cindex Global scope
920(The builtin function @code{find} does this job much more efficiently.)
921The @code{local} statement declares its arguments as having local scope.
922For example, the assignment to @code{w} would have no effect outside
923this function.  Without the @code{local} declaration, the assignment
924would change the value of @code{w} globally.@refill
925
926@cindex return statement
927@cindex Recursion
928The @code{return} statement causes execution of the function to
929terminate and passes it's expression as the function's return value.
930Recursive calls to a function are no problem.  For example, we could
931write a function to compute factorials as@refill
932
933@example
934fact = function (n)
935@{
936  if (n < 2) @{ return 1.0; else return n * fact (n-1); @}
937@}
938@end example
939
940@cindex self
941This function has one slight problem.  (Several, really, if you consider
942that it does no error checking.)  If we later decide to change its name
943by typing @code{factorial=fact}, it still calls function @code{fact}
944internally.  Now if we're really mean-spirited we can change @code{fact}
945as in @code{fact=sin}; now @code{factorial} gives wrong answers.  The
946way to handle this is to call the function @code{self} when you make a
947recursive function call, as in@refill
948
949@example
950fact = function (n)
951@{
952  if (n < 2) @{ return 1.0; else return n * self (n-1); @}
953@}
954@end example
955
956The @code{self} keyword refers to the current function.  Besides
957recursive function calls, it's also useful for keeping data local to a
958function.  For example, consider a function that returns the ``shape''
959of its argument:@refill
960
961@example
962shape = function (x)
963@{
964  return self.(class(x)) (x);
965@};
966
967shape.scalar = function (x) @{ return NULL; @};
968shape.vector = function (x) @{ return x.ne; @};
969shape.matrix = function (x) @{ return x.nr, x.nc; @};
970@end example
971
972This @code{shape} function determines the class of its argument and then
973calls the appropriate member function.  (The standard @code{shape}
974function additionally provides some error checking.)@refill
975
976@node Examples, Language, Primer, Top
977@chapter Example Programs
978
979Following are several examples designed to show off Algae's capabilities
980as well as to give you a feel for how it is used.  The @file{examples}
981directory in the source distribution of Algae contains some
982additional code for perusal.@refill
983
984@menu
985* Temperatures::        Fahrenheit to Celsius conversions
986* Reading Numbers::     Reading and summing numbers
987* Powers::              Integer powers
988@end menu
989
990@node Temperatures, Reading Numbers, Examples, Examples
991@section Temperature Conversion
992@cindex Temperature conversion program
993@cindex Program, temperature conversions
994
995This Algae program prints a table of Fahrenheit temperatures and their
996Celsius equivalents:
997
998@example
999# Print temperature conversions
1000fahr = sort (0:300:20, 32, 212);
1001celsius = (5/9)*(fahr-32);
1002[fahr;celsius]'?
1003@end example
1004
1005@noindent
1006Its output looks like this:
1007
1008@example
1009[         0.000       -17.78 ]
1010[         20.00       -6.667 ]
1011[         32.00        0.000 ]
1012[         40.00        4.444 ]
1013[         60.00        15.56 ]
1014[         80.00        26.67 ]
1015[         100.0        37.78 ]
1016[         120.0        48.89 ]
1017[         140.0        60.00 ]
1018[         160.0        71.11 ]
1019[         180.0        82.22 ]
1020[         200.0        93.33 ]
1021[         212.0        100.0 ]
1022[         220.0        104.4 ]
1023[         240.0        115.6 ]
1024[         260.0        126.7 ]
1025[         280.0        137.8 ]
1026[         300.0        148.9 ]
1027@end example
1028
1029This program does quite a bit in only four lines.  The entire first line
1030is a @dfn{comment} (because it starts with @code{#}) and is ignored by
1031Algae.@refill
1032
1033In the second line we define the Fahrenheit temperatures for our table.
1034The expression @code{0:300:20} gives a vector that goes from 0 to 300 in
1035steps of 20.  We add two more elements, 32 and 212, to that vector by
1036using the comma operator.  Then we use the @code{sort} function to sort
1037it in increasing order.  Finally, our vector of Fahrenheit temperatures
1038is assigned to the variable @code{fahr}.  Nothing is printed by this
1039statement, since it ends with a semicolon.@refill
1040
1041The third line computes the Celsius equivalents using the familiar
1042conversion formula.  First 32 is subtracted from each element of
1043@code{fahr}.  Then each element is multiplied by 5/9.  The result is
1044assigned to the variable @code{celsius}.  Here, again, nothing is
1045printed.@refill
1046
1047Even though all of the terms so far have been integers, @code{celsius}
1048is a real-valued vector.  Unlike some programming languages, integer
1049division in Algae does not result in truncation---the expression
1050@code{5/9} returns a real value that is approximately 0.556.@refill
1051
1052The last line prints the temperatures out as a matrix, with the
1053Fahrenheit temperatures in the first column and their Celsius
1054equivalents in the second column.  We do that by using brackets to form
1055a matrix with @code{fahr} in the first row and @code{celsius} in the
1056second row and then transposing the matrix with the @code{'} operator.
1057The question mark on the end is not necessary, since the matrix would
1058also be printed without it, but it does call attention to the line as
1059one that prints.@refill
1060
1061@node Reading Numbers, Powers, Temperatures, Examples
1062@section Reading and Summing Numbers
1063@cindex Number reading program
1064@cindex Program, number reading
1065
1066This Algae program reads a bunch of numbers, adds them up, and prints the
1067result:
1068
1069@example
1070# Read and sum some numbers
1071sum = 0;
1072$read = 1;
1073while ($read) @{ sum += readnum(); @}
1074sum?
1075@end example
1076
1077The program reads numbers one at a time and adds them to @code{sum}, so
1078in the first line @code{sum} is initialized to zero.  The @code{readnum}
1079function is used to read the numbers.  This function is one of the few
1080standard functions that has a side effect:  it assigns to the variable
1081@code{$read} the number of values that it read.  It will be less than
1082the number you asked for if @code{readnum} runs out of data.@refill
1083
1084The @code{while} loop executes its statements repeatedly until its
1085condition tests true.  We set @code{$read} to 1 (true) first, so we know
1086that the @code{while} loop will execute at least once.  After that, the
1087@code{while} loop continues until @code{$read} is eventually set to 0 by
1088the @code{readnum} function.  When the @code{while} loop is done, the last
1089line prints @code{sum}.@refill
1090
1091Usually, we give the @code{readnum} function two arguments: a ``shape''
1092vector and a file name.  The ``shape'' vector describes the number of
1093values to read and in what form (vector, matrix, etc.) they should be
1094returned.  The values are read from the named file.  Since the program
1095above gives neither argument, @code{readnum} simply reads one value from
1096the standard input device.@refill
1097
1098The @code{+=} operator adds the value on the right to the variable on
1099the left; the expression @code{sum+=readnum()} does the same thing as
1100@code{sum=sum+readnum()}.  Every time the @code{while} loop repeats,
1101@code{sum} is increased by the value returned by @code{readnum}.  When
1102@code{readnum} runs out of data, it returns 0 (so @code{sum} isn't changed)
1103and sets @code{$read} to 0 (so the @code{while} loop quits
1104looping).@refill
1105
1106@cindex End of file
1107Unless you redirect standard input, this program will quietly read what
1108you type until you signal an end-of-file (@kbd{C-d} on UNIX systems and
1109@kbd{C-z} on VMS).@refill
1110
1111@node Powers, , Reading Numbers, Examples
1112@section Integer Powers
1113@cindex Integer power program
1114@cindex Program, integer powers
1115
1116This program illustrates the use of a function.  In it, we define the
1117function @code{power} that computes integer powers of its argument.  We
1118also show some Algae code that calls @code{power}.@refill
1119
1120@example
1121# power:  raise `x' to the `n'-th power
1122power = function (x; n)
1123@{
1124  local (y);
1125  y = x;
1126  while (n > 1)
1127  @{
1128    y = y * x;
1129    n -= 1;
1130  @}
1131  return y;
1132@};
1133
1134power (2; 8)?
1135power ([ 1, 2; 2, 3 ]; 4)?
1136@end example
1137
1138The first line of this program is an ordinary assignment statement,
1139which assigns the function on its right side to the variable
1140@code{power}.  The function's arguments are defined in the parentheses
1141that follow the @code{function} keyword.  In this case, there are two
1142arguments:  @code{x} and @code{n}.@refill
1143
1144In Algae, all function arguments are called ``by value''.  When a
1145function is called, it gets copies of what the calling program gave as
1146arguments and can modify them without changing the values retained by
1147the calling program.  In the @code{power} function we decrement
1148@code{n} each time through the @code{while} loop, but this has no effect
1149on the calling program.@refill
1150
1151The @code{local} statement defines its argument, the variable @code{y},
1152as having local scope.  This means that @code{power} has its own
1153temporary variable called @code{y} that is defined only within that
1154function.  This @code{y} is first given the value of @code{x} and then,
1155inside the @code{while} loop, repeatedly multiplied by @code{x} until
1156@code{n} is no longer greater than 1.@refill
1157
1158The value that @code{power} computes is returned to its caller by the
1159@code{return} statement.  Any expression may follow @code{return}, and
1160any number of @code{return} statements may appear in a function.  If the
1161function has no return statement, it returns NULL to its caller.@refill
1162
1163The first time we call @code{power}, it returns (and the calling program
1164prints) the value 256.  In this case @code{power} is really not very
1165useful, since we could have obtained the same result with the expression
1166@code{2^8} using Algae's exponentiation operator.@refill
1167
1168The @code{power} function does have a use, though, as the second call to
1169it shows.  Algae's exponentiation operator performs in an
1170element-by-element sense, so @code{[1,2;2,3]^4} returns@refill
1171
1172@example
1173[           1         16 ]
1174[          16         81 ]
1175@end example
1176
1177@noindent
1178In contrast, @code{power} performs in a matrix sense.  In the program
1179above, it returns@refill
1180
1181@example
1182[          89        144 ]
1183[         144        233 ]
1184@end example
1185
1186The algorithm used in the @code{power} function above can be improved
1187upon by using successive squaring:
1188
1189@example
1190power = function (x; n)
1191@{
1192  if (n == 1)
1193  @{
1194    return x;
1195  elseif (n%2)
1196    return x * self (x; n-1);
1197  else
1198    x = self (x; n/2);
1199    return x * x;
1200  @}
1201@};
1202@end example
1203
1204This @code{power} function might be useful, but it's certainly not ready
1205for prime-time.  Notice that it gives wrong answers if @code{n} is 0 or
1206a negative integer.  What happens for the expression
1207@code{power(4;1/2)}, in which @code{n} is not an integer?  To make
1208@code{power} more robust you'd probably want to add some @code{if}
1209statements to check for illegal arguments.@refill
1210
1211@node Language, Data, Examples, Top
1212@comment  node-name,  next,  previous,  up
1213@chapter The Algae Language
1214@cindex Expressions
1215@cindex Statements
1216
1217In Algae, variables and operators combine to form expressions and
1218statements.  The rules for this are mostly conventional; for example,
1219the statement @code{a=b+c} means that the sum of @code{b} and @code{c}
1220is assigned to the variable @code{a}.  In Algae, however, the concept
1221of addition (as well as many other operations) is expanded to include
1222operations between a variety of data classes.@refill
1223
1224@menu
1225* Entities::
1226* Variables::
1227* Operators::
1228* Expressions::
1229* Statements::
1230* Functions::
1231@end menu
1232
1233@node Entities, Variables, Language, Language
1234@comment  node-name,  next,  previous,  up
1235@section Entities
1236@cindex Entities
1237@cindex Class of entities
1238
1239The basic unit of data in Algae is the @dfn{entity}.  Every entity has
1240an attribute called its @dfn{class} which describes it as a ``scalar'',
1241``vector'', ``matrix'', etc.  The built-in function @code{class} returns
1242the class of its argument as a character string.  Thus@refill
1243
1244@example
1245x = 1.2E3; class(x)?
1246@end example
1247
1248@noindent
1249prints ``scalar'' and
1250
1251@example
1252class (cos)?
1253@end example
1254
1255@noindent
1256prints ``function''.  Naturally, the statement
1257
1258@example
1259class (class (log))?
1260@end example
1261
1262@noindent
1263prints ``scalar'', since @code{class} returns a scalar character string.
1264
1265@cindex Members of entities
1266@cindex Entity members
1267Entities also contain @dfn{members}, in which various additional
1268attributes of the entity are stored.  For example, matrix entities have
1269members such as @code{type}, @code{density}, and @code{symmetry}.  These
1270members are themselves entities, so it is not unusual to have several
1271levels of membership (a member of a member of a member).  @xref{Data},
1272for a description of the various classes.@refill
1273
1274@cindex Dot operator
1275The ``dot'' operator is used to refer to members.  The statements
1276
1277@example
1278x = 1; x.type?
1279@end example
1280
1281@noindent
1282print ``integer'', the value of the @code{type} member in @code{x}.  The
1283line@refill
1284
1285@example
1286foo = 1492; foo.bar?
1287@end example
1288
1289@noindent
1290prints ``NULL'', since scalars don't contain a @code{bar} member when
1291they're created.  You could give it one, of course:@refill
1292
1293@example
1294foo.bar = "Columbus"
1295@end example
1296
1297@node Variables, Operators, Entities, Language
1298@comment  node-name,  next,  previous,  up
1299@section Variables
1300@cindex Variables
1301@cindex Defining variables
1302
1303A @dfn{variable} is a symbol that refers to a named entity; the entity
1304is known as the symbol's @dfn{value}.  A variable comes into being when
1305a value is assigned to it; there are no explicit declarations.@refill
1306
1307@menu
1308* Variable Names::
1309* Evaluation::
1310* Scope::
1311* Predefined Variables::
1312@end menu
1313
1314@node Variable Names, Evaluation, Variables, Variables
1315@comment  node-name,  next,  previous,  up
1316@subsection Variable Names
1317@cindex Variable names
1318@cindex Names of variables
1319
1320@cindex Case of variable names
1321Variables have names consisting of letters, digits, dollar signs
1322(@kbd{$}) and underscores (@kbd{_}).  A variable name cannot begin with
1323a digit.  Variable names are case sensitive, so the variables @code{foo}
1324and @code{Foo} are distinct.@refill
1325
1326@cindex Global variables
1327We generally use names that begin with @kbd{$} to refer to global
1328variables that are set at startup or that have some kind of side effect.
1329For example, the variable @code{$beep} acts like any other variable, but
1330also control's Algae's sound effects.  The @code{who} function
1331does not report variables that begin with @kbd{$} unless you give it the
1332argument @code{"$"}.@refill
1333
1334@cindex Symbol table
1335@cindex $$
1336@cindex Global symbol table
1337One variable name is special---the variable @code{$$} refers to the
1338global symbol table.  For example,@refill
1339
1340@example
1341a = "x";
1342$$.(a)
1343@end example
1344
1345@noindent
1346prints the value of the global variable @code{x}.  You can use @code{$$}
1347like any other variable, except that you cannot reassign its value.@refill
1348
1349@cindex Length of variable names
1350The only limitation on the length of a variable name is that it must
1351have at least one character.  Short names are convenient for interactive
1352work, but longer, descriptive names have advantages in functions and
1353scripts.@refill
1354
1355@node Evaluation, Scope, Variable Names, Variables
1356@subsection Evaluation of Variables
1357@cindex Evaluation of variables
1358@cindex Variable evaluation
1359
1360When a variable name is encountered in an expression, it is evaluated by
1361replacing the variable name with the corresponding named entity.  If it
1362is an argument to a function, then a copy is made (conceptually, if not
1363in fact) and passed to the function.  Thus, in a function call like
1364@code{func(a)} (@pxref{Functions}), the function @code{func} only gets a
1365copy of @code{a} and can't modify the @code{a} belonging to its
1366caller.@refill
1367
1368There is one exceptional case, involving the ``dot'' operator, in which
1369an identifier is not evaluated as a variable name.  An identifier on the
1370right side of a member expression is taken literally as the name of the
1371member.  For example, the statement@refill
1372
1373@example
1374v.type
1375@end example
1376
1377@noindent
1378prints the value of @code{v}'s member called @code{type}.  You could
1379well have a variable named @code{type}, but it would not affect the
1380member expression above.@refill
1381
1382Alternatively, the statement
1383
1384@example
1385v.(type)
1386@end example
1387
1388has an expression to the right of the ``dot'' operator, not a simple
1389identifier, and so prints the value of the member of @code{v} named by
1390the variable @code{type}.
1391
1392@node Scope, Predefined Variables, Evaluation, Variables
1393@comment  node-name,  next,  previous,  up
1394@subsection Scope of Variables
1395@cindex Scope of variables
1396@cindex Variables, scope
1397@cindex local statement
1398
1399Variables referenced from within functions are global in scope unless
1400they are arguments to the function or are declared local with the
1401@code{local} statement.  For example, the function@refill
1402
1403@example
1404init = function ()
1405@{
1406  i = sqrt (-1);
1407  e = exp (1);
1408  pi = acos (-1);
1409@};
1410@end example
1411
1412@noindent
1413could be used to initialize some commonly used variables.  Once you
1414executed @code{init()}, the variables @code{i}, @code{e}, and @code{pi}
1415would be globally defined.
1416
1417At the same time, you could have another function
1418
1419@example
1420egg_hunt = function (v)
1421@{
1422  local (i);
1423  for (i in 1:v.ne)
1424  @{
1425    if (v[i] == 0) @{ return i; @}
1426  @}
1427@}
1428@end example
1429
1430@noindent
1431in which @code{i} has local scope.  Here, you can't modify or even get
1432the value of the global variable @code{i}.@refill
1433
1434The form of the @code{local} statement is similar to a function call,
1435and multiple variables may be specified by separating them by
1436semicolons.@refill
1437
1438The @code{local} statement is unusual, in that it is a directive to
1439the parser rather than something that is coded.  This means that it
1440takes effect when the parser sees it, not when it's executed.  In the
1441code@refill
1442
1443@example
1444f = function ()
1445@{
1446  a = 1;
1447  if (0) @{ local (a); @}
1448  a = 2;
1449@}
1450@end example
1451
1452@noindent
1453the global variable @code{a} gets set to 1.  Even though the code in
1454the @code{if} block is not executed, after seeing it the parser
1455considers @code{a} to be a local variable.  Normally, one simply puts
1456@code{local} statements at the beginning of a function.@refill
1457
1458@cindex veil statement
1459The @code{veil} statement allows you to make a temporary change to a
1460global variable which will remain active from that point until the end
1461of the current dynamic scope, typically until the function ends.  For
1462example, the function@refill
1463
1464@example
1465prt = function (x)
1466@{
1467  veil (pi);
1468  pi = "apple";
1469  bake ();
1470@};
1471@end example
1472
1473@noindent
1474changes the value of the global variable @code{pi} while it's
1475executing, but @code{pi} reverts to its previous value when @code{prt}
1476finishes.  If the function @code{bake} referred to @code{pi}, it would
1477use or modify the temporary value.@refill
1478
1479By dynamic scope, we refer to the current execution unit.  Within a
1480function, that lasts as long as the function is executing.  Otherwise,
1481the dynamic scope is the current file, except that for the @code{eval}
1482and @code{exec} functions it is the argument string itself.  Also, if
1483executing in interactive mode and not in a function, then the dynamic
1484scope extends only to the end of the last statement on a line.@refill
1485
1486Unlike the @code{local} statement, the effect of the @code{veil}
1487statement takes place at the time it is executed.  Once a variable is
1488veiled (and before you set it to something else), it has the same
1489value as the associated global variable.@refill
1490
1491@node Predefined Variables, , Scope, Variables
1492@subsection Predefined Variables
1493@cindex Predefined variables
1494@cindex Variables, predefined
1495
1496Several variables are already defined for you when Algae starts
1497up.  Some of these are used to control Algae, and some provide you
1498information.  The predefined variables are:@refill
1499
1500@table @code
1501@cindex Beep
1502@item $beep
1503If this variable is ``true'' (that is, @code{test($beep)} returns 1),
1504then error messages include a BEL character.  This causes most terminals
1505to beep.  On startup, @code{$beep} is 0.@refill
1506
1507@cindex Digits to print
1508@item $digits
1509This variable specifies the number of significant digits that
1510Algae prints for real and complex numbers.  On startup,
1511@code{$digits} is 4.@refill
1512
1513@cindex PID
1514@item $pid
1515On startup, @code{$pid} contains the ``process id'' of the Algae
1516process.@refill
1517
1518@item $program
1519On startup, @code{$program} gives the name of the current Algae
1520program.  This will normally be @code{"algae"}.  It would be different
1521if, for example, you had changed the name of the Algae executable.@refill
1522
1523@cindex Prompt
1524@item $prompt
1525This variable controls Algae's interactive prompt.  It is expected
1526to be a character vector with two elements---on startup it is@refill
1527
1528@example
1529(  "> ", "  " )
1530@end example
1531
1532@noindent
1533The first element is Algae's first-level prompt.  When Algae
1534is waiting for another line of input before it executes what it has
1535already seen, it presents its second-level prompt.  The second element
1536of @code{$prompt} defines this second-level prompt.  If Algae
1537can't make sense of @code{$prompt}'s value, it does without a
1538prompt.@refill
1539
1540@item $read
1541The @code{$read} variable is set as a side-effect of the @code{readnum}
1542function.  It reports the number of values read in the last call to
1543@code{readnum}.@refill
1544
1545@cindex Terminal, width
1546@cindex Width of terminal
1547@cindex Wrapping lines
1548@item $term_width
1549This variable tells Algae the width of your terminal in
1550characters.  Algae will attempt to adjust its display to fit
1551within this width.  On startup, Algae will attempt
1552to sense this on its own.  If @code{term_width} is set to 0,
1553Algae will not wrap lines.@refill
1554
1555@item help
1556This is simply a character scalar that provides a few basic instructions
1557for using Algae.@refill
1558@end table
1559
1560You may wish to set some of these variables (like @code{$beep} or
1561@code{$prompt}) every time you use Algae.  This is conveniently
1562done by putting the assignments in the @file{.algae} file in your home
1563directory.@refill
1564
1565@node Operators, Expressions, Variables, Language
1566@section Operators
1567@cindex Operators
1568
1569Algae has unary, binary, and ternary operators to perform a variety of
1570operations.  The standard arithmetic operators (@samp{+}, @samp{-},
1571@samp{*}, @samp{/}, etc.) are available and have the usual precedence.
1572The caret @samp{^} is for exponentiation: 8^2 equals 64.  The single
1573quote character @samp{'} denotes the conjugate transpose.@refill
1574
1575With a few exceptions, all operators work in the ``element by element''
1576sense.  For example, if @code{A} and @code{B} are matrices with the same
1577size, then @code{A/B} returns a matrix, each element of which is the
1578quotient of the corresponding elements of @code{A} and @code{B}.
1579The @samp{*} operator works in an ``inner product'' sense, so @code{A*B}
1580is a matrix multiplication.  The @samp{@@} operator is Algae's ``element
1581by element'' multiplication operator.@refill
1582
1583@cindex Type conversions
1584@cindex Conversions between types
1585@cindex Automatic type conversion
1586When an operator has array operands of different types, one will be
1587automatically converted so that they have a common type, if possible.
1588An @code{integer} may be converted to @code{real} or @code{complex}, and
1589a @code{real} may be converted to @code{complex}.  No conversion to or
1590from @code{character} type is possible.@refill
1591
1592Unlike some other languages, the result of an operation in Algae may have
1593a type that is different than its operands.  For example, the result of
1594@code{1/2} has @code{real} type, even though its operands have type
1595@code{integer}.  Another example is @code{(-1)^0.5}, which returns a
1596complex number.@refill
1597
1598@cindex Class conversions
1599@cindex Conversions between classes
1600@cindex Automatic class conversion
1601With the exception of @code{*}, if a binary operator has both a
1602@code{vector} and a @code{matrix} as its operands the @code{vector} is
1603converted to a @code{matrix} before the operation is performed.  Upon
1604conversion, a vector becomes a matrix with one row.  For example, in the
1605statement@refill
1606
1607@example
1608( 1, 2 ) + [ 3, 4 ]
1609@end example
1610
1611the left-hand operand of @code{+} is the vector @code{(1,2)}.  This is
1612converted to a @code{matrix} before being added to @code{[3,4]}.@refill
1613
1614@cindex Precedence of operators
1615@cindex Associativity of operators
1616@cindex Operators, precedence
1617@cindex Operators, associativity
1618The following table summarizes the precedence and associativity of
1619Algae's operators.  Those shown on the same line have equal precedence,
1620and the rows are in order of decreasing precedence.
1621
1622@table @asis
1623@item @strong{operators}
1624@strong{associativity}
1625
1626@item @code{()}  @code{[]}  @code{.}
1627left to right
1628
1629@item @code{'}
1630right to left
1631
1632@item @code{^}
1633right to left
1634
1635@item @code{!}  @code{+}  @code{-}
1636(unary) left to right
1637
1638@item @code{*}  @code{/}  @code{%}  @code{@@}
1639left to right
1640
1641@item @code{+}  @code{-}
1642(binary) left to right
1643
1644@item @code{<}  @code{>}  @code{<=}  @code{>=}  @code{==}  @code{!=}
1645left to right
1646
1647@item @code{&}
1648left to right
1649
1650@item @code{|}
1651left to right
1652
1653@item @code{&&}
1654left to right
1655
1656@item @code{||}
1657left to right
1658
1659@item @code{:}
1660left to right
1661
1662@item @code{,}
1663left to right
1664
1665@item @code{=}  @code{+=}  @code{-=}  @code{*=}  @code{/=}  @code{@@=}  @code{%=}
1666right to left
1667@end table
1668
1669@menu
1670* Call::		@samp{()}
1671* Element::		@samp{[]}
1672* Member::		@samp{.}
1673* Transpose::		@samp{'}
1674* Power::		@samp{^}
1675* Not::			@samp{!}
1676* Negation::		@samp{+} and @samp{-} (unary)
1677* Multiplication::	@samp{*}, @samp{/}, @samp{%}, and @samp{@@}
1678* Addition::		@samp{+} and @samp{-} (binary)
1679* Relation::		@samp{<}, @samp{>}, @samp{<=}, @samp{>=}, @samp{==}, and @samp{!=}
1680* And::			@samp{&}
1681* Or::			@samp{|}
1682* Short And::		@samp{&&}
1683* Short Or::		@samp{||}
1684* Generate::		@samp{:}
1685* Append::		@samp{,}
1686* Assign::		@samp{=}, @samp{+=}, @samp{-=}, @samp{*=}, @samp{/=}, @samp{@@=}, and @samp{%=}
1687@end menu
1688
1689@node Call, Element, Operators, Operators
1690@subsection Function Calls
1691@cindex Function calls
1692@cindex Calling functions
1693@cindex () function calls
1694
1695Functions are called in the usual way:  the function reference is
1696followed by a list of arguments.  For example,@refill
1697
1698@example
1699w = union (u; v);
1700@end example
1701
1702@noindent
1703calls the function @code{union}, passing it the values of @code{u} and
1704@code{v} for arguments.  The value returned by the function's
1705@code{return} statement (or NULL if it doesn't have one) is the value of
1706the function call.@refill
1707
1708@cindex Arguments of functions
1709The arguments may be any expressions, and are separated by semicolons.
1710The called function gets only the values of the expressions you give it
1711as arguments, so it can't modify the variables that you give it.@refill
1712
1713From its definition, the function knows how many arguments to expect.
1714Passing too many arguments is an error.  If you pass fewer arguments
1715than the function definition calls for, NULL's are passed in place of
1716the missing ones.@refill
1717
1718@cindex Parentheses
1719Besides their use in function calls, parentheses are used for several
1720other purposes, including grouping expressions, @code{if}, @code{for},
1721and @code{while} conditions, function definitions, etc.@refill
1722
1723@node Element, Member, Call, Operators
1724@subsection Element References
1725@cindex Element references
1726@cindex Referencing elements
1727@cindex Brackets
1728@cindex [ ] (element reference)
1729
1730The element reference operation returns specified vector elements or
1731matrix rows and columns.  Applied to a table, the operation is performed
1732on each of the table's members.
1733
1734Elements are referenced by following a vector or matrix expression with
1735a bracket-enclosed list of the desired elements.  For vector @code{v},
1736the expression @code{v[w]} gives the elements specified by @code{w}.
1737The expression within the brackets is expected to be a scalar or a
1738vector---if it's a matrix, it will be converted into a vector if
1739possible.  So, for example,@refill
1740
1741@example
1742v[3:8]
1743@end example
1744
1745@noindent
1746prints the third through eighth elements of @code{v}.  If the vector
1747inside the brackets has a numeric type, then it is converted to integer
1748if necessary (by taking the real part and rounding) and then used to
1749refer to the element numbers.@refill
1750
1751The class of the element reference expression is determined by the class
1752of the specifiers.  Once any matrix specifiers are converted to vectors,
1753the dimension of the result is equal to the sum of the dimensions of the
1754specifiers.  For example, @code{M[1;2]} is a scalar, @code{M[[1];2]} and
1755@code{M[1;[2]]} are vectors, and @code{M[[1];[2]]} is a matrix.  Notice
1756that the class of the result does not depend on the class of the
1757original entity.@refill
1758
1759If the vector inside the brackets has character type, then it is taken
1760to refer to the element labels instead of the element numbers.  For
1761example, if you set @code{x} as@refill
1762
1763@example
1764x = 1:3;
1765x.eid = "this", "that", "other";
1766@end example
1767
1768@noindent
1769then @code{x["that"]} returns 2, the value of the element of @code{x}
1770having the label @code{"that"}.  If the labels do not have character
1771type, they are temporarily converted to character type for the
1772comparison.@refill
1773
1774Element references work the same way for matrices, except that both rows
1775and columns are specified.  For example,@refill
1776
1777@example
1778M[ 1,3; 7:12 ]
1779@end example
1780
1781@noindent
1782specifies rows 1 and 3, columns 7 through 12, of the matrix @code{M}.
1783
1784The specifiers need not be irredundant.  For example, @code{M[1,1,1;]}
1785returns three copies of the first row of @code{M}.@refill
1786
1787Besides their use for element references, brackets are also used to form
1788matrices.@refill
1789
1790@node Member, Transpose, Element, Operators
1791@subsection Member References
1792@cindex Member references
1793@cindex Referencing members
1794@cindex Dot operator
1795@cindex . (member reference operator)
1796
1797Members of an entity are referenced with the ``dot'' operator.  For
1798example, @code{x.type} returns the value of @code{x}'s member
1799@code{type}.  Notice that, if the right-hand operand is an identifier,
1800then it is taken literally as the name of the desired member.  You might
1801have a variable called @code{type}, but that is irrelevant when it comes
1802to evaluating @code{x.type}.@refill
1803
1804On the other hand, if the right-hand operand is an expression, then its
1805value (converted to a character scalar) is taken as the desired member
1806name.  Since you can change an identifier into an expression simply by
1807enclosing it in parentheses, the expression @code{x.(type)} does use the
1808value of the variable @code{type} as the name of the member.@refill
1809
1810@cindex Member names
1811@cindex Names of members
1812Member names do not share the same limitations as variable names.  In
1813fact, any string of ASCII characters (excluding NUL) will work.  This
1814can be pretty useful.  For example, you could set up a ``vector'' of
1815entities (of any class) as in
1816
1817@example
1818V = @{@};
1819V.(1) = A;
1820V.(2) = B;
1821V.(3) = C;
1822V.(4) = D;
1823@end example
1824
1825@noindent
1826and then refer to the individual ``elements'' (that is, the members of
1827@code{V}) by number.  You could handle multiple dimensions by referring
1828to element @code{"3,2,4"}, for example.
1829
1830@node Transpose, Power, Member, Operators
1831@subsection Transpose
1832@cindex Transpose operator
1833@cindex Conjugate transpose operator
1834@cindex Apostrophe
1835@cindex ' (conjugate transpose operator)
1836
1837The transpose operator applies the conjugate transpose operation to a
1838matrix.  For integer, real, and character types, this means moving every
1839element from row @code{i} and column @code{j} to row @code{j} and column
1840@code{i}.  If the matrix has complex type, the complex conjugate
1841operation is applied as well.@refill
1842
1843If you want the transpose of a complex matrix @code{M}, and not its
1844conjugate transpose, then use the expression @code{conj(M')}.@refill
1845
1846If transpose is applied to a scalar or vector, the entity is first
1847converted to a matrix and then transposed.  For example, @code{(1,2)'}
1848is the same as @code{[1;2]}---the vector is first converted into a
1849matrix with one row and then transposed to form a matrix with one
1850column.@refill
1851
1852If this operator is applied to a table, then the operation is performed
1853on each member of that table.@refill
1854
1855@node Power, Not, Transpose, Operators
1856@subsection Power
1857@cindex Power operator
1858@cindex Circumflex
1859@cindex ^ (power operator)
1860
1861The ``power'' operator @samp{^} is a binary operator that raises its
1862left operand to the power of its right operand.  Thus @code{2^3} gives
18638.  It associates right-to-left, so the expressions @code{x^y^z} and
1864@code{x^(y^z)} are equivalent.@refill
1865
1866When vectors and matrices are involved, the ``power'' operator performs
1867in an ``element-by-element'' sense.  For example, if @code{M} is a
1868matrix, then @code{M^2} squares each element of @code{M}.  This is
1869definitely not the same thing as @code{M*M}!@refill
1870
1871In an expression such as @code{2^M}, where the left operand is scalar
1872and the right operand is a vector or matrix, the result has each element
1873@code{i} of @code{M} replaced by @code{2^M[i]}.  For example,@refill
1874
1875@example
18762^(0:3)
1877@end example
1878
1879@noindent
1880prints the vector @code{(1,2,4,8)}.
1881
1882Notice that the precedence of @samp{^} is higher than @samp{-}, so the
1883expression @code{-1^2} returns @code{-1}.@refill
1884
1885In mathematical usage, @code{0^0} is undefined---it yields an error in
1886Algae.@refill
1887
1888If both left and right operands are arrays, then they must have
1889matching dimensions and labels.@refill
1890
1891If this operator is applied to a table, then the operation is performed
1892on each member of that table.@refill
1893
1894@node Not, Negation, Power, Operators
1895@subsection Not
1896@cindex Not operator
1897@cindex Exclamation mark
1898@cindex ! (not operator)
1899
1900The @samp{!} operator is a unary, prefix operator that returns 1 if its
1901operand is considered ``false'', and 0 otherwise.  The ``false''
1902operands are:@refill
1903
1904@itemize @bullet
1905@item
1906NULL.
1907
1908@item
1909Numeric entities in which every element is zero.
1910
1911@item
1912Character entities in which every element is @code{""}.
1913
1914@item
1915Vectors and matrices with no elements.
1916
1917@item
1918Tables with no elements.
1919@end itemize
1920
1921If this operator is applied to a table, then the operation is performed
1922on each member of that table.@refill
1923
1924@node Negation, Multiplication, Not, Operators
1925@subsection Negation
1926@cindex Negation operator
1927@cindex Unary minus operator
1928@cindex Unary plus operator
1929@cindex Affirmation operator
1930@cindex Minus sign
1931@cindex Plus sign
1932@cindex -- (negation operator)
1933@cindex + (affirmation operator)
1934
1935The unary negation operator @samp{-} multiplies its numeric argument by
1936@code{-1}.  The @samp{+} operator is for user convenience---Algae ignores
1937it in its unary context.  For example, @code{+-1} gives a negative one.
1938On the other hand, @code{1+-1} and @code{1-+1} both return 0.@refill
1939
1940If one of these operators is applied to a table, then that operation is
1941performed on each member of the table.@refill
1942
1943@node Multiplication, Addition, Negation, Operators
1944@subsection Multiplication
1945@cindex Multiplication operators
1946@cindex * (multiplication operator)
1947@cindex @@ (element-by-element multiplication operator)
1948
1949Both the @samp{*} and the @samp{@@} operators perform multiplication.
1950The difference is that @samp{@@} performs in an element-by-element sense,
1951while @samp{*} performs in an inner product sense.  The operands of
1952@samp{@@} must have matching dimensions and labels; each element of its
1953left operand is multiplied by the corresponding element of the right
1954operand.  For example,@refill
1955
1956@example
1957( 1, 2, 3 ) @@ ( 4, 5, 6 )
1958@end example
1959
1960@noindent
1961returns the vector @code{(4,10,18)}.
1962
1963When @samp{*} is applied to matrices, the number of columns of the left
1964operand must equal the number of rows of the right operand, and the
1965corresponding labels must match.  The result is a matrix that has the
1966same number of rows as the left operand and the same number of columns
1967as the right operand.@refill
1968
1969If one of the operands of @samp{*} is a vector and the other is a
1970matrix, the vector is (conceptually) converted to a matrix before the
1971multiplication is performed.  If on the left, it is converted to a
1972matrix with one row; if on the right, it is converted to a matrix with
1973one column.@refill
1974
1975Multiplication of two vectors gives their inner product.
1976
1977@cindex Division operator
1978@cindex / (division operator)
1979The @samp{/} operator performs division.  Like @samp{@@}, it performs in
1980an element-by-element sense.@refill
1981
1982If either operand of any of these operators is a scalar, then the
1983operation is performed in an element-by-element sense.  For example@refill
1984
1985@example
19862*(1,2,3)
1987@end example
1988
1989@noindent
1990gives @code{(2,4,6)}---every element of the vector is multiplied by the
1991scalar.@refill
1992
1993@cindex Modulus operator
1994@cindex % (modulus operator)
1995The @samp{%} operator performs the modulus operation, producing the
1996remainder when the left operand is divided by the right operand.  For
1997example, @code{(2,2.5,3)%2} returns the vector @code{(0,0.5,1)}.@refill
1998
1999The result has the same sign as the left operand.
2000If this operator is applied to a table, then the operation is
2001performed on each member of the table.@refill
2002
2003@node Addition, Relation, Multiplication, Operators
2004@subsection Addition
2005@cindex Addition operator
2006@cindex Subtraction operator
2007@cindex + (addition operator)
2008@cindex -- (subtraction operator)
2009
2010The ``addition'' operators are the binary operators @samp{+} and
2011@samp{-}.  If their operands are numeric, then they perform the normal
2012addition and subtraction operations.
2013
2014@cindex Catenation, string
2015@cindex Concatenation, string
2016@cindex String concatenation
2017When the @samp{+} operator is applied to character strings, it catenates
2018them.  The @samp{-} operator is not defined for character strings.
2019
2020Between two tables, @samp{+} combines their members in the resulting
2021table.  Conceptually, the members of the left operand are inserted in
2022this new table first, followed by the members of the right operand.
2023This means that if the operands have a member with the same name, the
2024value of that member in the resulting table comes from the right
2025operand.  For example, if @code{t} is a table that contains the member
2026``foo'', then the result of@refill
2027
2028@example
2029t + @{ foo = NULL @}
2030@end example
2031
2032@noindent
2033is identical to @code{t} except that its member ``foo'' has the value
2034NULL.@refill
2035
2036When the @samp{-} operator is applied to tables, the result is a table
2037that has all the members of the left operand except those that are also
2038in the right operand.  For example@refill
2039
2040@example
2041@{x;y;z@}-@{x;y@}
2042@end example
2043
2044@noindent
2045returns a table that has the single member ``z''.@refill
2046
2047If just one of the operands is a table, then the operation is performed
2048between the other operand and each member of the table.@refill
2049
2050@node Relation, And, Addition, Operators
2051@subsection Relation
2052@cindex Relational operators
2053@cindex < (less than operator)
2054@cindex <= (less or equal operator)
2055@cindex > (greater than operator)
2056@cindex >= (greater or equal operator)
2057@cindex == (equality operator)
2058@cindex != (inequality operator)
2059
2060The relation operators @samp{<}, @samp{>}, @samp{<=}, @samp{>=},
2061@samp{==}, and @samp{!=} return ``true'' (1) or ``false'' (0) to reflect
2062the truth of the expression.  For example,@refill
2063
2064@example
2065(1:5) < 3
2066@end example
2067
2068@noindent
2069returns @code{(1,1,0,0,0)}.
2070
2071If both operands are arrays, then their dimensions and labels must
2072match.@refill
2073
2074Unlike most of the operators, @samp{==} and @samp{!=} allow NULL as an
2075operand.  In that case, the other operand is simply checked to see if
2076it is or is not a NULL.@refill
2077
2078If one of these operators is applied to a table, then that operation is
2079performed on each member of the table.@refill
2080
2081@node And, Or, Relation, Operators
2082@subsection And
2083@cindex And operator
2084@cindex & (and operator)
2085
2086The @samp{&} operator performs the logical ``and'' operation in an
2087element-by-element sense.  For example,@refill
2088
2089@example
2090x = 1:5;
2091x > 2 & x < 4
2092@end example
2093
2094@noindent
2095prints @code{(0,0,1,0,0)}.
2096
2097If this operator is applied to a table, then the operation is performed
2098on each member of that table.@refill
2099
2100@node Or, Short And, And, Operators
2101@subsection Or
2102@cindex Or operator
2103@cindex | (or operator)
2104
2105The @samp{|} operator performs the logical ``or'' operation in an
2106element-by-element sense.  For example,@refill
2107
2108@example
2109x = 1:5;
2110x < 2 | x > 4
2111@end example
2112
2113@noindent
2114prints @code{(1,0,0,0,1)}.
2115
2116If this operator is applied to a table, then the operation is performed
2117on each member of that table.@refill
2118
2119@node Short And, Short Or, Or, Operators
2120@subsection Short And
2121@cindex And operator
2122@cindex Short And
2123@cindex && (and operator)
2124
2125The @samp{&&} operator performs the ``short-circuit'' logical ``and''
2126operation.  Both operands are evaluated for ``truth'' as if they were
2127the test of an @code{if} statement.  If the left operand is ``false'',
2128then the right operand is not evaluated.  If both operands are ``true'',
2129the result of the operation is 1; otherwise the result is 0.  Note that
2130this operation is quite different from that of the @samp{&} operator,
2131which works element-by-element.@refill
2132
2133The following example code is from the @code{solve} function:
2134
2135@example
2136if (options != NULL && members (options) == "pos")
2137@{
2138  A = chol (A);
2139else
2140  A = factor (A);
2141@}
2142@end example
2143
2144@noindent
2145The variable @code{options} is first checked to see if it's NULL.  Only
2146if it is not NULL is the @code{member} function called.  That's just
2147what we want, since it would be an error to call @code{member} with a
2148NULL argument.@refill
2149
2150@node Short Or, Generate, Short And, Operators
2151@subsection Short Or
2152@cindex Or operator
2153@cindex Short Or
2154@cindex || (or operator)
2155
2156The @samp{||} operator performs the ``short-circuit'' logical ``or''
2157operation.  Both operands are evaluated for ``truth'' as if they were
2158the test of an @code{if} statement.  If the left operand is ``true'',
2159then the right operand is not evaluated.  If either operand is ``true'',
2160the result of the operation is 1; otherwise the result is 0.  Note that
2161this operation is quite different from that of the @samp{|} operator,
2162which works element-by-element.@refill
2163
2164In the statement
2165
2166@example
2167if (options == NULL || options.tol == NULL) @{ tol = 1e-6; @}
2168@end example
2169
2170@noindent
2171the variable @code{options} is first checked to see if it's NULL.  Only
2172if it is not NULL is the member reference @code{options.tol}
2173evaluated.@refill
2174
2175@node Generate, Append, Short Or, Operators
2176@subsection Generate
2177@cindex Generate operator
2178@cindex Vector generation
2179@cindex Colon
2180@cindex : (vector generation operator)
2181
2182Numeric vectors may be generated with the @samp{:} operator.  An
2183expression like @code{i:j} generates a vector that starts with the value
2184of @code{i}.  If @code{j} is greater than @code{i}, each successive
2185element is 1 greater than the previous one, with the last element less
2186than or equal to @code{j}.  If @code{j} is less than @code{i}, each
2187successive element is 1 less than the previous one, with the last
2188element greater than or equal to @code{j}.@refill
2189
2190The @samp{:} operator also has a ternary form, as in @code{i:j:k}.  This
2191does the same thing as @code{i:j} except that successive elements differ
2192by @code{k} instead of 1.@refill
2193
2194For complex operands, the operation can be described conceptually in the
2195complex plane.  A line is drawn between the points @code{i} and
2196@code{j}.  Then the resulting vector contains the points located on that
2197line segment beginning at @code{i}, proceeding toward @code{j}, spaced a
2198distance @code{k} (or 1, if @code{k} is not given) apart.@refill
2199
2200@node Append, Assign, Generate, Operators
2201@subsection Append
2202@cindex Append operator
2203@cindex Comma
2204@cindex , (append operator)
2205
2206The @samp{,} operator ``appends'' its operands.  If the operands are
2207vectors, then the result is a new vector containing both the operands.
2208If the operands are matrices, then the result is a new matrix containing
2209the left operand on the left and the right operand on the right.@refill
2210
2211If this operator is applied to a table, then the operation is performed
2212on each member of that table.@refill
2213
2214@node Assign, , Append, Operators
2215@subsection Assign
2216@cindex Assignment operators
2217@cindex = (assignment operator)
2218@cindex += (assignment operator)
2219@cindex --= (assignment operator)
2220@cindex *= (assignment operator)
2221@cindex /= (assignment operator)
2222@cindex @@= (assignment operator)
2223@cindex %= (assignment operator)
2224
2225The assignment operators are @samp{=}, @samp{+=}, @samp{-=}, @samp{*=},
2226@samp{/=}, @samp{@@=}, and @samp{%=}.  The @samp{=} operator returns the
2227value of the right operand, setting the left operand to that value in
2228the process.  For example,@refill
2229
2230@example
2231a = b = c = 1;
2232@end example
2233
2234@noindent
2235assigns 1 to the variables @code{a}, @code{b}, and @code{c}.  The
2236assignment operators associate right to left, so first @code{c} is given
2237the value 1.  The result of that expression, @code{c = 1}, is 1, so that
2238value is used with @code{b} as if it read @code{b = 1}.@refill
2239
2240Notice that a test like
2241
2242@example
2243if (i = j) ...
2244@end example
2245
2246@noindent
2247is entirely different than
2248
2249@example
2250if (i == j) ...
2251@end example
2252
2253@noindent
2254In the first example, @code{i} is assigned the value of @code{j} and
2255then that value is tested by the @code{if} statement.  In the second
2256example, the @code{if} statement tests the equality of @code{i} and
2257@code{j}.  So if @code{i} is 1 and @code{j} is 2, the first example
2258tests true (as well as changing the value of @code{i}) and the second
2259one tests false.@refill
2260
2261Individual elements of an array may be changed; for example
2262
2263@example
2264x[3;4:6] = 0, 0, 0;
2265@end example
2266
2267@noindent
2268sets to 0 the elements of @code{x} in row 3 and columns 4 through 6.
2269The right operand is converted to the same type as the left operand, if
2270possible, and the dimensions must agree.  However, if the right operand
2271is a scalar, then it is filled to the appropriate size.  Thus, the
2272previous example could just as well be written@refill
2273
2274@example
2275x[3;4:6] = 0;
2276@end example
2277
2278One more thing about array assignments: If the variable on the left is a
2279vector, but you specify two dimensions for it, then that variable will
2280be converted into a matrix.  Likewise, if the variable on the left is a
2281matrix, but you specify only one dimension, then it will be converted
2282into a vector.  For example, in the code@refill
2283
2284@example
2285A = B = [ 1, 2, 3 ];
2286A[2] = B[;2] = 9;
2287@end example
2288
2289@noindent
2290@code{A} and @code{B} both begin as matrices.  The second element of
2291each array is then changed to 9.  In the end, though, @code{A} is
2292changed to a vector because only one dimension was given for it.
2293@code{B} remains as a matrix.@refill
2294
2295The other assignment operators (@samp{+=}, @samp{-=}, etc.) are simply
2296for convenience.  The expression @code{i+=j} means the same thing as
2297@code{i=i+j}, and @code{i-=j} means the same thing as @code{i=i-j}.  If
2298the left-hand side is an expression, you should keep in mind that it
2299will be evaluated twice.  For example,@refill
2300
2301@example
2302x[ func() ] += 1
2303@end example
2304
2305@noindent
2306will actually make two calls to the function @code{func}.@refill
2307
2308@node Expressions, Statements, Operators, Language
2309@comment  node-name,  next,  previous,  up
2310@section Expressions
2311@cindex Expressions
2312@cindex Assignments
2313
2314Assignments are made in the normal fashion: @code{a=5} sets the variable
2315@samp{a} to contain the scalar 5.  Variables are not declared prior to
2316use, but rather take on the structure and type of whatever is assigned
2317to them.  You could, for example, enter@refill
2318
2319@example
2320a=1;
2321a=[a,a];
2322@end example
2323
2324@noindent
2325in which case the variable @samp{a} is first a scalar and then a matrix.
2326A list of the previously defined variables (except functions) is given by
2327the @samp{who()} function, and a variable can be deleted by assigning
2328NULL to it.@refill
2329
2330In addition to simple variables, elements and members can also be specified on
2331the left hand side of an assignment. For example, the statement@refill
2332
2333@example
2334A[ 1:4; 1:4 ] = 3;
2335@end example
2336
2337@noindent
2338assigns 3 to all of the elements of the first 4-by-4 partition of matrix
2339@samp{A}, leaving the other elements of @code{A} unchanged.  Values can
2340be assigned to members in the same way.  For example, the
2341statements@refill
2342
2343@example
2344A = [ 1,2,3; 4,5,6 ];
2345time = [ 1.1, 2.2, 3.3 ];
2346A.rid = [ "first"; "second" ]
2347A.cid = time
2348@end example
2349
2350@noindent
2351assign the row and column labels of @samp{A}.
2352
2353@node Statements, Functions, Expressions, Language
2354@comment  node-name,  next,  previous,  up
2355@section Statements
2356@cindex Statements
2357@cindex Terminating statements
2358@cindex Statement terminators
2359@cindex ? (statement terminator)
2360@cindex ; (statement terminator)
2361@cindex Question mark
2362@cindex Newline
2363@cindex Semicolon
2364
2365Statements are terminated by a question mark, a semicolon, or a newline.
2366Using a question mark or newline causes the value of the statement to be
2367printed; with a semicolon the printing is suppressed.  A newline
2368terminates a statement only if it does not occur within parentheses,
2369brackets, or braces.@refill
2370
2371Statement termination is implied by the closing brace of an ``if'',
2372``for'', or ``while'' statement or ``function'' expression.  Printing is
2373enabled when the terminator is implied.  For example,@refill
2374
2375@example
2376for (i in 1:10) @{ i @}
2377@end example
2378
2379@noindent
2380prints all of the integers from 1 to 10.
2381
2382@cindex Significant digits
2383@cindex Digits, significant
2384@cindex Format, real or complex number
2385When real or complex numbers are printed, Algae prints 4
2386significant digits by default.  This can be changed with the
2387@code{digits} function, or just by setting the global variable
2388@code{$digits}.@refill
2389
2390@cindex Comments
2391@cindex # (begin comment)
2392Comments are introduced with the @samp{#} character.  That character and
2393any that follow it on the same line are ignored (excluding the
2394newline).@refill
2395
2396@node Functions, , Statements, Language
2397@section Functions
2398@cindex Functions
2399@cindex Defining functions
2400
2401Functions are defined by a function expression, which consists of the
2402keyword ``function'', followed by a parenthesized list of arguments,
2403followed by a set of statements enclosed by braces.  For example, Algae's
2404@code{max} function is defined by something like@refill
2405
2406@example
2407max = function (x) @{ return x[imax(x)]; @};
2408@end example
2409
2410@noindent
2411Functions are just another class of entity; the statement above defines
2412a function and then assigns it to the variable @code{max}.
2413
2414@cindex Arguments of functions
2415The arguments are variables that are local to the function.  On entry,
2416they take on the values of the formal arguments in the calling
2417expression.  Passing more arguments than are in the function's definition
2418is an error.  If fewer arguments are passed, then NULL's are passed in
2419place of the missing arguments.@refill
2420
2421@cindex Function expressions
2422The function reference needn't be an identifier---a function expression
2423works just fine.  For example,@refill
2424
2425@example
2426child = (his_functions + her_functions).reproduce();
2427@end example
2428
2429@noindent
2430would combine the tables @code{his_functions} and @code{her_functions},
2431reference the member @code{reproduce}, call it with no arguments, and
2432then assign the result to @code{child}.  Notice that, since @samp{.} and
2433@samp{()} have the same precedence, their left-to-right associativity
2434causes the member reference to occur first and then the function call.
2435In an expression like @code{sin(1).type}, the function call is performed
2436first.@refill
2437
2438When a function is compiled, information is included that relates its
2439operations to the file name and line numbers of the source code.  If an
2440error occurs, this information is useful in tracking down its cause.  In
2441some cases, this information is undesirable and may be removed with the
2442@code{strip} function.  The @code{message} function is such a case.@refill
2443
2444@node Data, Standard Functions, Language, Top
2445@comment  node-name,  next,  previous,  up
2446@chapter Data
2447@cindex Class of entities
2448@cindex Entities
2449
2450Entities are the basic objects (constants and variables) in Algae.
2451They contain members and elements.  Members contain information about
2452the entity, such as the number of rows in a matrix.  An entity's
2453elements, if it has any, contain the data such as the value of a scalar.
2454There are five classes:@refill
2455
2456@table @samp
2457@item scalar
2458@cindex Scalars
2459@cindex Members of scalars
2460The @samp{scalar} data structure contains a single element, its value, which
2461may have any of the data types described above.  Its members are:@refill
2462
2463@table @samp
2464@item class
2465The string @samp{"scalar"}.
2466
2467@item type
2468The type (like @samp{"integer"} or @samp{"real"}).
2469@end table
2470
2471Notice that a scalar is not the same as a one-element vector or
2472matrix.@refill
2473
2474@item vector
2475@cindex Vectors
2476The @samp{vector} entity contains a one-dimensional array of elements.
2477Its members are:@refill
2478
2479@cindex Members of vectors
2480@table @samp
2481@item class
2482The string @samp{"vector"}.
2483
2484@item type
2485The type (like @samp{"integer"} or @samp{"real"}).
2486
2487@item density
2488Either @samp{"dense"} or @samp{"sparse"}.
2489
2490@item ne
2491The number of elements.
2492
2493@item nn
2494The number of non-zero elements.
2495
2496@item eid
2497The element labels.
2498@end table
2499
2500The element labels of a vector are themselves a vector.
2501
2502@item matrix
2503@cindex Matrices
2504The @samp{matrix} data structure contains two-dimensional arrays of
2505elements.  It contains zero or more rows and columns.  The members of a
2506matrix are:@refill
2507
2508@cindex Members of matrices
2509@table @samp
2510@item class
2511The string @samp{"matrix"}.
2512
2513@item type
2514The type (like @samp{"integer"} or @samp{"real"}).
2515
2516@item symmetry
2517One of @samp{"general"}, @samp{"symmetric"}, or @samp{"hermitian"}.
2518
2519@item density
2520One of @samp{"dense"}, @samp{"sparse"} or @samp{"sparse_upper"}.
2521
2522@item nr
2523The number of rows.
2524
2525@item nc
2526The number of columns.
2527
2528@item nn
2529The number of nonzero elements.  For matrices with ``sparse_upper''
2530density, this number does not include the elements on the diagonal, all
2531of which are stored.  Sorry.
2532
2533@item rid
2534The row labels.
2535
2536@item cid
2537The column labels.
2538@end table
2539
2540The row and column labels of a matrix are vectors.  The row label vector
2541has the same number of elements as its matrix has rows, and likewise for
2542the column label.@refill
2543
2544@cindex Tables
2545@item table
2546The @samp{table} object is like a bucket that can contain any number of
2547other objects.@refill
2548
2549Several functions return tables.  For example, the @code{eig} function
2550returns a table that contains the matrices @code{values} and
2551@code{vectors}.@refill
2552
2553The entities contained in a table are members of it, so they can be
2554extracted using the @kbd{.} operator.  Thus @code{eig(A).values} returns
2555the eigenvalues of @samp{A}.@refill
2556
2557@cindex Functions
2558@item function
2559Functions are entities just like scalars and matrices, and can be
2560operated on in the same manner.  Functions have two members:
2561@samp{class}, which is @code{"function"}, and @samp{ilk}, which is
2562either @code{"user"} or @code{"builtin"}.
2563@end table
2564
2565@cindex Arrays
2566@cindex Data types
2567@cindex Types
2568The @code{scalar}, @code{vector}, and @code{matrix} classes are known
2569collectively as @dfn{arrays}.  These are the only classes that contain
2570elements, and all have the member @code{type} that specifies the data
2571type.  There are four types:@refill
2572
2573@table @samp
2574@item integer
2575@cindex Integer type
2576On most machines this is a 32-bit integer, like 42 or -273.
2577
2578@item real
2579@cindex Real type
2580This is a floating point number like 3.1415.  It is stored in 64 bits on
2581most machines.
2582
2583@item complex
2584@cindex Complex type
2585This is a complex number having both real and imaginary
2586parts.
2587
2588@item character
2589@cindex Character type
2590This is a character string like @samp{"Hello"}.
2591@end table
2592
2593@cindex Constants
2594@cindex Scalar constants
2595@cindex Numeric constants
2596Scalar constants are specified in a manner similar to that used in other
2597programming languages.  Numeric constants can be given in decimal form,
2598such as @samp{32} or @samp{32.0}, or in scientific notation, such as
2599@samp{3.2E1}.  In the latter notation, the letters @samp{e} and @samp{E}
2600may be used interchangeably to prefix the exponent.  White space (space,
2601tab, etc.) is significant in that context, of course, so that @samp{1.2e+3}
2602(1200.0) is definitely not the same as @samp{1.2e +3} (4.2).@refill
2603
2604@cindex Character constants
2605@cindex Strings
2606@cindex Double quotes
2607@cindex " (quote character)
2608@cindex \ (backslash character)
2609@cindex Backslash character
2610@cindex Escape sequences
2611@cindex Quote character
2612A @samp{character} constant is a sequence of one or more characters
2613surrounded by matching double-quotes.  Within the quotes, the backslash
2614character may be used to introduce ``escape sequences'' for unusual
2615characters like @key{newline}.  For example, the string @samp{"\""} is a
2616string containing a single character (the right double-quote).  The
2617following escape sequences may be used:@refill
2618
2619@table @code
2620@item \a
2621bell
2622@item \b
2623backspace
2624@item \e
2625escape
2626@item \f
2627formfeed
2628@item \n
2629newline
2630@item \r
2631carriage return
2632@item \t
2633tab
2634@item \v
2635vertical tab
2636@item \ooo
2637octal number
2638@item \xhh
2639hexadecimal number
2640@end table
2641
2642@noindent
2643The escape sequence @code{\ooo} consists of a backslash followed by one,
2644two, or three octal digits, which are taken to specify the value of the
2645desired character.  For example, @code{\33} is the ASCII ``escape''
2646character (which is also given by @code{\e}).  Likewise, the sequence
2647@code{\xhh} consists of a backslash followed by @samp{x}, followed by
2648one or two hexadecimal digits, which specify the value of the desired
2649character.  For example, @code{\x1b} also specifies the ASCII ``escape''
2650character.@refill
2651
2652If the character following the backslash is not one of those specified
2653above, then that character is taken literally.  For example, @code{\"}
2654specifies the double-quote character---not the end of the character
2655constant.@refill
2656
2657@cindex Matrix constants
2658Matrices may be generated by specifying their elements within brackets.
2659Commas separate elements within rows and semicolons separate the rows.
2660Thus @code{[1,2;3,4]} specifies the matrix@refill
2661
2662@display
2663[ 1  2 ]
2664[ 3  4 ]
2665@end display
2666
2667@cindex Vector constants
2668@cindex MATLAB
2669A vector may be generated by using either of the forms @samp{i:j} or
2670@samp{i:j:k}.  It is obtained by starting with the value @samp{i} and
2671incrementing by @samp{k} (or 1 if the first form is used) while
2672remaining between @samp{i} and @samp{j}, inclusive.  (Notice that this
2673is not the same format used by MATLAB.)  For example, @code{[1:8:2]} is
2674the same as @code{[1,3,5,7]}.  All elements within a matrix have the
2675same type (@samp{integer}, @samp{real}, etc.); conversion will be
2676performed automatically if possible.@refill
2677
2678The terms within the brackets may be constants, variables, or
2679expressions.  For example, @code{[1+2,3]} is the same as @code{[3,3]}.
2680Matrices may be involved, as long as their dimensions are appropriate.
2681For example, if the variable @samp{A} is defined to be equal to the
2682square matrix @samp{[1,2;3,4]}, then a new column could be appended to
2683it with the expression @code{[A,[5;6]]} to yield@refill
2684
2685@display
2686[ 1  2  5 ]
2687[ 3  4  6 ]
2688@end display
2689
2690Matrices may be partitioned by specifying the desired row and column
2691numbers within brackets.  For example, if @samp{A} is a previously
2692defined matrix then @code{A[1;1]} specifies a scalar having the value of
2693the element in the first row and the first column of @samp{A}.  The
2694semicolon within the parentheses separates the row specifiers from the
2695column specifiers.@refill
2696
2697Members of data structures are referred to by using the member operator
2698@samp{.}.  For example, the number of rows in a matrix is stored in the
2699member @code{nr}, so @code{A.nr} returns the number of rows in the
2700matrix @code{A}.  The member operator associates left to right, so that
2701@code{A.type.type} returns the string @code{"character"}.@refill
2702
2703@node Standard Functions, Running Algae, Data, Top
2704@comment  node-name,  next,  previous,  up
2705@chapter The Standard Functions
2706@cindex Standard functions
2707
2708Functions are called by giving their name followed by a parenthesized
2709list of their arguments.  For example, @code{sqrt(a)} computes the
2710square root of its argument @samp{a}.  The parentheses are required,
2711whether they contain any arguments or not.  Functions may take more than
2712one number and kind of argument.@refill
2713
2714@menu
2715* Basic Math::		abs, sin, sqrt, ...
2716* Arrays::		fill, sparse, zero, ...
2717* Sets::		union, intersection, ...
2718* Linear Algebra::	solve, factor, fft, ...
2719* Numerical Analysis::	ode4, brent, ...
2720* Basic I/O::		read, printf, ...
2721* Entity I/O::		get, put, ...
2722* Execution::		source, system, ...
2723* Special Tools::	plot, npsol, ...
2724* Miscellaneous::	who, what, time, ...
2725@end menu
2726
2727@node Basic Math, Arrays, Standard Functions, Standard Functions
2728@section Basic Math
2729
2730@ifinfo
2731@menu
2732* abs::		absolute value
2733* acos::	arc cosine
2734* acosh::	arc cosine hyperbolic
2735* arg::         argument (phase)
2736* asin::	arc sine
2737* asinh::	arc sine hyperbolic
2738* atan::	arc tangent
2739* atanh::	arc tangent hyperbolic
2740* atan2::	arc tangent (y/x)
2741* ceil::        ceiling
2742* conj::	complex conjugate
2743* cos::		cosine
2744* cosh::	hyperbolic cosine
2745* erf::         error function
2746* erfc::        complementary error function
2747* exp::		exponential
2748* floor::       floor
2749* gcd::         greatest common divisor
2750* imag::	imaginary part
2751* integer::	round to nearest integer
2752* lcm::         least common multiple
2753* log::		natural logarithm
2754* log10::       base-10 logarithm
2755* primef::      prime factors
2756* primes::      prime numbers
2757* real::	real part
2758* round::       round to nearest whole number
2759* sin::		sine
2760* sinh::	hyperbolic sine
2761* sqrt::	square root
2762* tan::		tangent
2763* tanh::	hyperbolic tangent
2764@end menu
2765@end ifinfo
2766
2767@node abs, acos, Basic Math, Basic Math
2768
2769@cindex Absolute value
2770@cindex Magnitude
2771@defun abs ( x )
2772The @code{abs} function returns the absolute value of its numeric
2773argument.  ``Absolute value'' is synonymous with ``magnitude'' for
2774complex types.  If @var{x} is non-scalar, every element is replaced by
2775its absolute value.@refill
2776
2777@code{x} must be a numeric scalar, vector, or matrix.
2778@end defun
2779
2780@node acos, acosh, abs, Basic Math
2781
2782@cindex Arc cosine
2783@cindex Inverse cosine
2784@defun acos ( x )
2785The @code{acos} function returns the arc cosine of its numeric
2786argument.  If it's argument is complex or has a magnitude greater than
2787one, then the result is complex.  Otherwise, the result is real.  If
2788@var{x} is non-scalar, every element is replaced by its arc
2789cosine.@refill
2790
2791The argument @var{x} must be a numeric scalar, vector, or matrix.@refill
2792@end defun
2793
2794@node acosh, arg, acos, Basic Math
2795
2796@cindex Arc cosine hyperbolic
2797@cindex Hyperbolic arc cosine
2798@cindex Inverse hyperbolic cosine
2799@defun acosh ( x )
2800The @code{acosh} function returns the hyperbolic arc cosine of its
2801numeric argument.  If it's argument is complex or is less than 1.0, then
2802the result is complex.  Otherwise, the result is real.  If @var{x} is
2803non-scalar, every element is replaced by its hyperbolic arc cosine.@refill
2804
2805The argument @var{x} must be a numeric scalar, vector, or matrix.  Note
2806that @code{acosh(0)} is not zero, so if @code{acosh} is applied to a
2807sparse vector or matrix, then a dense array is the result.@refill
2808@end defun
2809
2810@node arg, asin, acosh, Basic Math
2811
2812@cindex Phase
2813@cindex Argument
2814@defun arg ( z )
2815The @code{arg} function returns the argument (phase angle) of its
2816numeric argument.@refill
2817
2818See also @code{abs}.
2819@end defun
2820
2821@node asin, asinh, arg, Basic Math
2822
2823@cindex Arc sine
2824@defun asin ( x )
2825The @code{asin} function returns the arc sine of its numeric argument.
2826If it's argument is complex or has a magnitude greater than one, then
2827the result is complex.  Otherwise, the result is real.  If @var{x} is
2828non-scalar, every element is replaced by its arc sine.@refill
2829
2830The argument @var{x} must be a numeric scalar, vector, or matrix.@refill
2831@end defun
2832
2833@node asinh, atan, asin, Basic Math
2834
2835@cindex Arc sine hyperbolic
2836@cindex Hyperbolic arc sine
2837@cindex Inverse hyperbolic sine
2838@defun asinh ( x )
2839The @code{asinh} function returns the hyperbolic arc sine of its numeric
2840argument.  If @var{x} is non-scalar, every element is replaced by its
2841hyperbolic arc sine.@refill
2842
2843The argument @var{x} must be a numeric scalar, vector, or matrix.@refill
2844@end defun
2845
2846@node atan, atanh, asinh, Basic Math
2847
2848@cindex Arc tangent
2849@cindex Inverse tangent
2850@defun atan ( x )
2851The @code{atan} function returns the arc tangent of its numeric
2852argument.  If it's argument is complex, then the result is complex.
2853Otherwise, the result is real.  If @var{x} is non-scalar, every element
2854is replaced by its arc tangent.@refill
2855
2856The argument @var{x} must be a numeric scalar, vector, or matrix.
2857@end defun
2858
2859@node atanh, atan2, atan, Basic Math
2860
2861@cindex Arc tangent hyperbolic
2862@cindex Hyperbolic arc tangent
2863@cindex Inverse hyperbolic tangent
2864@defun atanh ( x )
2865The @code{atanh} function returns the hyperbolic arc tangent of its
2866numeric argument.  If it's argument is complex or has magnitude greater
2867than 1.0, then the result is complex.  Otherwise, the result is real.
2868If @var{x} is non-scalar, every element is replaced by its hyperbolic
2869arc tangent.@refill
2870
2871The argument @var{x} must be a numeric scalar, vector, or matrix.
2872@end defun
2873
2874@node atan2, ceil, atanh, Basic Math
2875
2876@defun atan2 ( y; x )
2877The @code{atan2} function computes an angle corresponding to @var{y} and
2878@var{x}, the lengths of the opposite and adjacent sides.  This is
2879similar to @code{atan(y/x)}, but with these differences:@refill
2880
2881@itemize @bullet
2882@item
2883The signs of @var{y} and @var{x} are used to determine the quadrant in
2884which the angle lies.  The angle returned is in the range -pi to
2885pi.@refill
2886
2887@item
2888The argument @var{x} may be zero, as long as @var{y} is nonzero.  This
2889is different than @code{atan(y/x)}, because it avoids division by
2890zero.@refill
2891
2892@item
2893Complex type for either argument is not allowed.
2894@end itemize
2895
2896The arguments must be scalars, vectors, or matrices, with either integer
2897or real type.@refill
2898@end defun
2899
2900@node ceil, conj, atan2, Basic Math
2901
2902@cindex Ceiling
2903@defun ceil ( x )
2904The @code{ceil} function returns the ceiling of its numeric argument.
2905The ceiling of @var{x} is the smallest integer that is not less than
2906@var{x}.  If @var{x} is complex, the ceiling is applied to both real and
2907imaginary parts.  If @var{x} is non-scalar, every element is replaced by
2908its ceiling.  The type of @var{x} is not changed by @code{ceil}.@refill
2909
2910@var{x} must be a numeric scalar, vector, or matrix.
2911@end defun
2912
2913@node conj, cos, ceil, Basic Math
2914
2915@cindex Complex conjugate
2916@cindex Conjugate, complex
2917@defun conj ( x )
2918The @code{conj} function returns the complex conjugate of its numeric
2919argument.  If @var{x} is non-scalar, every element is replaced by its
2920complex conjugate.@refill
2921
2922@var{x} must be a numeric scalar, vector, or matrix.
2923@end defun
2924
2925@node cos, cosh, conj, Basic Math
2926
2927@cindex Cosine
2928@defun cos ( x )
2929The @code{cos} function returns the cosine of its numeric argument.  If
2930@var{x} is non-scalar, every element is replaced by its cosine.@refill
2931
2932@var{x} must be a numeric scalar, vector, or matrix.
2933@end defun
2934
2935@node cosh, erf, cos, Basic Math
2936
2937@cindex Hyperbolic cosine
2938@defun cosh ( x )
2939The @code{cosh} function returns the hyperbolic cosine of its numeric
2940argument.  If @var{x} is non-scalar, every element is replaced by its
2941hyperbolic cosine.@refill
2942
2943@var{x} must be a numeric scalar, vector, or matrix.
2944@end defun
2945
2946@node erf, erfc, cosh, Basic Math
2947
2948@cindex Error function
2949@defun erf ( x )
2950The @code{erf} function returns the error function of its numeric
2951argument.  If @var{x} is non-scalar, every element is replaced by its
2952error function result.@refill
2953
2954The error function is defined as @code{2/sqrt(pi)} times the integral
2955from 0 to @var{x} of @code{exp(-t^2) dt}.  Among its useful
2956properties, the error function is twice the integral of the Gaussian
2957distribution with 0 mean and variance of 1/2.@refill
2958
2959Complex arguments are not yet implemented.
2960@end defun
2961
2962@node erfc, exp, erf, Basic Math
2963
2964@cindex Error function
2965@defun erfc ( x )
2966The @code{erfc} function returns the complementary error function of
2967its numeric argument.  If @var{x} is non-scalar, every element is
2968replaced by its complementary error function result.@refill
2969
2970The complementary error function @code{erfc(x)} is simply @code{1-erf(c)},
2971but it is computed in a way that avoids round-off errors when @var{x}
2972is large.@refill
2973
2974Complex arguments are not yet implemented.
2975@end defun
2976
2977@node exp, floor, erfc, Basic Math
2978
2979@cindex Exponential
2980@defun exp ( x )
2981The @code{exp} function returns the exponential of its numeric argument.
2982If @var{x} is non-scalar, every element is replaced by its
2983exponential.@refill
2984
2985@var{x} must be a numeric scalar, vector, or matrix.
2986@end defun
2987
2988@node floor, gcd, exp, Basic Math
2989
2990@cindex Floor
2991@defun floor ( x )
2992The @code{floor} function returns the floor of its numeric argument.
2993The floor of @var{x} is the largest integer that is not greater than
2994@var{x}.  If @var{x} is complex, the floor is applied to both real and
2995imaginary parts.  If @var{x} is non-scalar, every element is replaced by
2996its floor.  The type of @var{x} is not changed by @code{floor}.@refill
2997
2998@var{x} must be a numeric scalar, vector, or matrix.
2999@end defun
3000
3001@node gcd, imag, floor, Basic Math
3002
3003@cindex Greatest common divisor
3004@defun gcd ( x )
3005This function computes the greatest common divisor (GCD) of the
3006elements of its vector argument.  The input is rounded to integer
3007type.  The scalar return value is the GCD.  Its member ``factors''
3008contains an integer vector such that @code{gcd(x).factors*x} is equal
3009to @code{gcd(x)}.
3010
3011See also @code{lcm} and @code{primef}.
3012@end defun
3013
3014@node imag, integer, gcd, Basic Math
3015
3016@cindex Imaginary value
3017@defun imag ( x )
3018The @code{imag} function returns the imaginary part of its numeric
3019argument.  If @var{x} is non-scalar, every element is replaced by its
3020imaginary part.  The value returned by @code{imag} has real type.@refill
3021
3022See also @code{real}.
3023@end defun
3024
3025@node integer, lcm, imag, Basic Math
3026
3027@defun integer ( x )
3028The @code{integer} function converts the real part of its numeric
3029argument to integer type, rounding it if necessary.@refill
3030
3031See also @code{round}.
3032@end defun
3033
3034@node lcm, log, integer, Basic Math
3035
3036@cindex Least common multiple
3037@defun lcm ( x )
3038This function computes the least common multiple (LCM) of the elements
3039of its vector argument.  The input is rounded to integer type.  The
3040scalar return value is the LCM.
3041
3042See also @code{gcd} and @code{primef}.
3043@end defun
3044
3045@node log, log10, lcm, Basic Math
3046
3047@cindex Logarithm
3048@defun log ( x )
3049The @code{log} function returns the natural logarithm of its numeric
3050argument.  If @var{x} is non-scalar, every element is replaced by its
3051logarithm.@refill
3052
3053@var{x} must be a numeric scalar, vector, or matrix.
3054@end defun
3055
3056@node log10, primef, log, Basic Math
3057
3058@defun log10 ( x )
3059The @code{log10} function returns the base-10 logarithm of its numeric
3060argument.  If @var{x} is non-scalar, every element is replaced by its
3061base-10 logarithm.@refill
3062
3063@var{x} must be a numeric scalar, vector, or matrix.
3064@end defun
3065
3066@node primef, primes, log10, Basic Math
3067
3068@cindex Prime factors
3069@cindex Factors, prime
3070@defun primef ( n )
3071This function computes the prime factors of its scalar argument,
3072returning them as elements of an integer vector.  The argument @var{n}
3073is rounded to integer, if necessary.  If the argument is less than 2,
3074a zero length vector is returned.@refill
3075
3076See also @code{gcd}, @code{lcm}, and @code{primes}.
3077@end defun
3078
3079@node primes, real, primef, Basic Math
3080
3081@cindex Prime numbers
3082@defun primes ( n )
3083This function generates a vector of prime numbers that are less than
3084or equal to the scalar argument.  The argument @var{n} is rounded to
3085an integer, if necessary.  If the argument is less than 2, a zero
3086length vector is returned.@refill
3087
3088See also @code{gcd}, @code{lcm}, and @code{primes}.
3089@end defun
3090
3091@node real, round, primes, Basic Math
3092
3093@cindex Real value
3094@defun real ( x )
3095This function returns the real part of @var{x}.  The value returned by
3096@code{real} has real type.@refill
3097
3098See also @code{imag}.
3099@end defun
3100
3101@node round, sin, real, Basic Math
3102
3103@cindex Rounding
3104@defun round ( x )
3105The @code{round} function rounds its numeric argument to the nearest
3106whole number.  If @var{x} is complex, both real and imaginary parts are
3107rounded.  If @var{x} is non-scalar, every element is rounded.  The type
3108of @var{x} is not changed by @code{round}.@refill
3109
3110If Algae has been compiled to use the system's rint(3m) function, then
3111arguments with a fractional part of exactly 1/2 are rounded to the
3112nearest even whole number.  Otherwise, such arguments are rounded
3113towards +infinity.@refill
3114
3115See also @code{integer}.
3116@end defun
3117
3118@node sin, sinh, round, Basic Math
3119
3120@cindex Sine
3121@defun sin ( x )
3122The @code{sin} function returns the sine of its numeric argument.  If
3123@var{x} is non-scalar, every element is replaced by its sine.@refill
3124@end defun
3125
3126@node sinh, sqrt, sin, Basic Math
3127
3128@cindex Hyperbolic sine
3129@defun sinh ( x )
3130The @code{sinh} function returns the hyperbolic sine of its numeric
3131argument.  If @var{x} is non-scalar, every element is replaced by its
3132hyperbolic sine.@refill
3133@end defun
3134
3135@node sqrt, tan, sinh, Basic Math
3136
3137@cindex Square root
3138@defun sqrt ( x )
3139The @code{sqrt} function returns the square root of its numeric
3140argument.  If @var{x} is complex or negative, then the result is
3141complex.  Otherwise, the result is real.  If @var{x} is non-scalar,
3142every element is replaced by its square root.@refill
3143@end defun
3144
3145@node tan, tanh, sqrt, Basic Math
3146
3147@cindex Tangent
3148@defun tan ( x )
3149The @code{tan} function returns the tangent of its numeric argument.  If
3150@var{x} is non-scalar, every element is replaced by its tangent.@refill
3151@end defun
3152
3153@node tanh, , tan, Basic Math
3154
3155@cindex Hyperbolic tangent
3156@defun tanh ( x )
3157The @code{tanh} function returns the hyperbolic tangent of its numeric
3158argument.  If @var{x} is non-scalar, every element is replaced by its
3159hyperbolic tangent.@refill
3160@end defun
3161
3162@node Arrays, Sets, Basic Math, Standard Functions
3163@section Arrays
3164
3165@ifinfo
3166@menu
3167* band::	bandwidth reduction
3168* bdiag::	block diagonal
3169* btrans::	block transpose
3170* circshift::   circular shift of array
3171* combine::     union, but in original order
3172* cram::	form an array, possibly sparse
3173* dense::	dense storage
3174* diag::	matrix diagonal
3175* dice::        individual characters of a string
3176* diff::	difference between elements
3177* exsparse::    disassemble a sparse matrix
3178* fill::	fill an array
3179* find::	find elements in a vector
3180* first::       first "true" element in a vector
3181* form::	form an array
3182* full::	full storage
3183* gpskca::      profile or bandwidth reduction
3184* grep::        search using regular expression
3185* hermitian::	hermitian part of a matrix
3186* ident::       identity matrix
3187* imax::        find maximum element
3188* imin::        find minimum element
3189* isort::       sorted index
3190* label::       add labels
3191* last::        last "true" element in a vector
3192* linspace::    uniformly spaced vector
3193* logspace::    logarithmically spaced vector
3194* lose::	lose elements in a vector
3195* magic::	magic squares
3196* matrix::	convert to a matrix
3197* max::		maximum value
3198* merge::	merge arrays
3199* min::		minimum value
3200* mksparse::    sparse matrix from coordinate data
3201* norm::	vector and matrix norms
3202* pick::        pick non-zero elements
3203* product::     product of array elements
3204* rand::	uniform random numbers
3205* randn::       normal random numbers
3206* reverse::     reverse elements of a vector
3207* scalar::	convert to scalar
3208* select::      select an element at random
3209* seq::         integer sequence
3210* shape::       array dimensions
3211* sign::        signum function
3212* sort::	sort a vector
3213* sparse::	sparse storage
3214* srand::	seed random numbers
3215* sum::		sum elements
3216* surprise::    random arrays with given properties
3217* symmetric::	symmetric part of a matrix
3218* tril::        lower triangle
3219* triu::        upper triangle
3220* unlabel::     remove labels
3221* vector::	convert to a vector
3222* zero::	make a zero array
3223@end menu
3224@end ifinfo
3225
3226@node band, bdiag, Arrays, Arrays
3227
3228@cindex Bandwidth
3229@cindex Profile
3230@defun band ( m )
3231The @code{band} function computes the upper and lower bandwidths and
3232profiles of the square matrix @var{m}.  The row bandwidth of a
3233particular row is the number of elements to the left of the diagonal in
3234that row, but not including any consecutive zero elements at the
3235beginning of that row.  Likewise, the column bandwidth of a particular
3236column is the number of elements above the diagonal in that column, but
3237not including any consecutive zero elements at the beginning of that
3238column.  Notice that, for a diagonal matrix, all row and column
3239bandwidths are zero.  The lower bandwidth is the largest of all the row
3240bandwidths, and the upper bandwidth is the largest of all the column
3241bandwidths.  The lower profile is the sum of all the row bandwidths, and
3242the upper profile is the sum of all the column bandwidths.@refill
3243
3244This function returns a real vector with four elements.  In order,
3245these elements are as follows:  lower bandwidth, lower profile, upper
3246bandwidth, and upper profile.@refill
3247
3248Profile reduction can be very effective in reducing the time and memory
3249required to factor a matrix.  The function @code{gpskca} provides one
3250approach for doing this.@refill
3251
3252See also @code{gpskca}.
3253@end defun
3254
3255@node bdiag, btrans, band, Arrays
3256
3257@cindex Block diagonal
3258@defun bdiag ( x; m; n )
3259The @code{bdiag} function mimics the @code{diag} function, but in a
3260``block'' sense.  The matrix @var{x} is taken to be comprised of
3261@var{m} rows and @var{n} columns of blocks that are themselves matrices.
3262If either @var{m} or @var{n} is 0, then the matrix returned has the
3263blocks of @var{x} on its diagonal and is elsewhere zero.  Otherwise,
3264the blocks of the diagonal of @var{x} are appended together.@refill
3265
3266An example of the former case is:
3267
3268@example
3269> M = magic (4)
3270        [  9   7   6  12 ]
3271        [  4  14  15   1 ]
3272        [ 16   2   3  13 ]
3273        [  5  11  10   8 ]
3274> bdiag (M; 0; 2)
3275        [           9          7          .          . ]
3276        [           4         14          .          . ]
3277        [          16          2          .          . ]
3278        [           5         11          .          . ]
3279        [           .          .          6         12 ]
3280        [           .          .         15          1 ]
3281        [           .          .          3         13 ]
3282        [           .          .         10          8 ]
3283@end example
3284
3285An example of the latter case is:
3286
3287@example
3288> bdiag ( M; 2; 2 )
3289        [  9   7   3  13 ]
3290        [  4  14  10   8 ]
3291@end example
3292
3293@var{x} must be scalar, vector, or matrix.  After being converted to a
3294matrix, if necessary, the number of rows of @var{x} must be evenly
3295divisible by @var{m} (unless @var{m} is 0) and the number of columns of
3296@var{x} must be evenly divisible by @var{n} (unless @var{n} is 0).@refill
3297
3298See also @code{btrans} and @code{diag}.
3299@end defun
3300
3301@node btrans, circshift, bdiag, Arrays
3302
3303@cindex Block transpose
3304@defun btrans ( x; m; n )
3305The @code{btrans} function mimics the transpose operator, but in a
3306``block'' sense.  The matrix @var{x} is taken to be comprised of @var{m}
3307rows and @var{n} columns of blocks that are themselves matrices.  The
3308blocks themselves are not transposed, but are simply moved across the
3309diagonal.@refill
3310
3311For example:
3312
3313@example
3314> M = magic (4)
3315        [  9   7   6  12 ]
3316        [  4  14  15   1 ]
3317        [ 16   2   3  13 ]
3318        [  5  11  10   8 ]
3319> btrans (M; 2; 2)
3320        [  9   7  16   2 ]
3321        [  4  14   5  11 ]
3322        [  6  12   3  13 ]
3323        [ 15   1  10   8 ]
3324@end example
3325
3326@var{x} must be scalar, vector, or matrix.  After being converted to a
3327matrix, if necessary, the number of rows of @var{x} must be evenly
3328divisible by @var{m} and the number of columns of @var{x} must be evenly
3329divisible by @var{n}.@refill
3330
3331See also @code{bdiag}.
3332@end defun
3333
3334@node circshift, combine, btrans, Arrays
3335
3336@cindex Circular shift
3337@cindex Shift, circular
3338@defun circshift ( x; s )
3339
3340The @code{circshift} function shifts the elements of the array @var{x}.
3341The arg @var{s} is a vector---each of its elements specifies the shift
3342distance for the corresponding dimension of @var{x}.  A positive shift is
3343down or right; a negative shift is up or left.  If unspecified, the
3344shift distance is zero (meaning no shift).  If @var{x} is a table, the
3345function is applied to each of its members.@refill
3346
3347For example:
3348
3349@example
3350> x = fill (3,3; 1:9)
3351        [ 1   2   3 ]
3352        [ 4   5   6 ]
3353        [ 7   8   9 ]
3354> circshift (x; 1)
3355        [ 7   8   9 ]
3356        [ 1   2   3 ]
3357        [ 4   5   6 ]
3358> circshift (x; 0,1)
3359        [ 3   1   2 ]
3360        [ 6   4   5 ]
3361        [ 9   7   8 ]
3362> circshift (x; 1,1)
3363        [ 9   7   8 ]
3364        [ 3   1   2 ]
3365        [ 6   4   5 ]
3366@end example
3367
3368@end defun
3369
3370@node combine, cram, circshift, Arrays
3371
3372@defun combine ( u; v )
3373The @code{combine} function appends the vectors @var{u} and @var{v},
3374removing all but the first of any redundant elements.  This is exactly
3375like the @code{union} function, except that the result is not sorted.@refill
3376@end defun
3377
3378@node cram, dense, combine, Arrays
3379
3380@defun cram ( shape; x )
3381This function uses the elements of @var{x} to make an entity described
3382by the vector @var{shape}.  If @var{shape} is NULL or has no elements, a
3383scalar is returned.  If @var{shape} has one element, then a vector of
3384length @code{shape[1]} is returned.  If @var{shape} has two elements,
3385then a matrix with @code{shape[1]} rows and @code{shape[2]} columns is
3386returned.@refill
3387
3388The elements of @var{x} are used, in order, to fill the new entity.  For
3389matrices, this proceeds by rows.  If the entity returned has more
3390elements than @var{x}, it is padded with zeros or null strings.  For
3391example, @code{cram( 5; 1,2 )} returns the vector
3392@code{(1,2,0,0,0)}.@refill
3393
3394If the return value is an array, it may be either dense or sparse.  The
3395code will try to make a reasonable choice, but avoids spending much time
3396in deciding.  For example, @code{cram( 1000; 1 )} returns a sparse
3397vector since it is immediately apparent that most of its elements are
3398zero.  On the other hand, @code{cram( 1000; (1:1000)<2 )} is dense even
3399though it would be more efficient to store it sparse; since its second
3400argument is a dense vector, @code{cram} would need to check most of its
3401elements to realize that.@refill
3402
3403The @code{form} function is identical to this function except that the
3404arrays it returns are always dense.@refill
3405
3406See also @code{fill}, @code{form}, and @code{zero}.
3407@end defun
3408
3409@node dense, diag, cram, Arrays
3410
3411@cindex Dense storage
3412@defun dense ( x )
3413The @code{dense} function converts its argument array to dense storage.
3414See also @code{sparse}.@refill
3415@end defun
3416
3417@node diag, dice, dense, Arrays
3418
3419@cindex Diagonal of a matrix
3420@cindex Matrix, diagonal
3421@defun diag ( x )
3422The @code{diag} function performs two different tasks, depending on the
3423class of @var{x}.  If @var{x} is a matrix, then its diagonal is returned
3424as a vector.  If @var{x} is a vector, then a matrix is returned which
3425has @var{x} as its diagonal and is zero elsewhere.  (If @var{x} is a
3426scalar, it is returned intact.)@refill
3427
3428See also @code{bdiag}.
3429@end defun
3430
3431@node dice, diff, diag, Arrays
3432
3433@defun dice ( s )
3434The @code{dice} function takes a character scalar @var{s} and returns a
3435character vector, each element of which is a single character from
3436@var{s}.  For example, the expression @code{dice("Go dawgs!")}
3437yields@refill
3438
3439@example
3440(  "G", "o", " ", "d", "a", "w", "g", "s", "!" )
3441@end example
3442
3443See also @code{split}.
3444@end defun
3445
3446@node diff, exsparse, dice, Arrays
3447
3448@defun diff ( v )
3449The @code{diff} function takes a numeric vector @var{v} and returns a
3450vector of differences between its elements.  If @var{v} has @code{n}
3451elements, then the return vector is@refill
3452
3453@example
3454v[2]-v[1], v[3]-v[2], ..., v[n]-v[n-1]
3455@end example
3456
3457The return vector has one less element than @var{v}.  If @var{v} has
3458labels, then the return vector contains all but the last one.@refill
3459
3460One simple use for @code{diff} is to compute forward-difference
3461approximations for the slope of a curve.  If @code{c} is a vector
3462containing ordinates of the curve in its elements and abscissae in its
3463labels, then the expression@refill
3464
3465@example
3466diff (c) / diff (unlabel (c.eid))
3467@end example
3468
3469@noindent
3470returns an approximation to its slope.  (The call to @code{unlabel} is
3471probably unnecessary in most cases, but it avoids trouble when the
3472labels of @code{c} themselves have labels.)@refill
3473@end defun
3474
3475@node exsparse, fill, diff, Arrays
3476
3477@defun exsparse ( x )
3478This function disassembles a matrix, returning it in its ``coordinate''
3479form, suitable for reassembly by the @code{mksparse} function.  A table
3480is returned, containing the members @var{shape}, @var{rows}, @var{cols},
3481and @var{values}.  The argument matrix @var{x} must be numeric.  Despite
3482the name of the function, it need not be sparse.@refill
3483
3484See also @code{mksparse}.
3485@end defun
3486
3487@node fill, find, exsparse, Arrays
3488
3489@defun fill ( shape; x )
3490This function uses the elements of @var{x} to make an entity described
3491by the vector @var{shape}.  If @var{shape} is NULL or has no elements, a
3492scalar is returned.  If @var{shape} has one element, then a vector of
3493length @code{shape[1]} is returned.  If @var{shape} has two elements,
3494then a matrix with @code{shape[1]} rows and @code{shape[2]} columns is
3495returned.@refill
3496
3497The elements of @var{x} are used, in order, to fill the new entity.  For
3498matrices, this proceeds by rows.  If the entity returned has more
3499elements than @var{x}, then the elements of @var{x} are reused.  For
3500example, @code{fill( 5; "a","b" )} returns the vector
3501@code{("a","b","a","b","a")}.@refill
3502
3503When the return value from @code{fill} is a vector or matrix, it will
3504always be dense.  See the @code{cram} function for sparse return arrays.
3505
3506The @code{form} function differs from this function only in that it
3507pads with zeros rather than reusing elements of @var{x}.@refill
3508
3509See also @code{form}, @code{cram}, and @code{zero}.
3510@end defun
3511
3512@node find, first, fill, Arrays
3513
3514@defun find ( a; b )
3515The @code{find} function locates the elements of @var{b} that have the
3516values given by @var{a} and returns a vector containing their element
3517numbers.  For example, @code{find( 2,3; 0,1,2,3,4 )} returns the vector
3518@code{(3,4)}.  One common use is in an expression like
3519@code{A[find(77;A.rid);]}, which returns the row (or rows) of @var{a}
3520having the row label 77.@refill
3521
3522If @var{a} is a scalar, then @code{find(a;b)} returns the element
3523numbers of @var{b}, sorted from smallest to largest, for which the
3524corresponding element of @var{b} is equal to @var{a}.  If @var{a} is a
3525vector, then @code{find(a;b)} returns the same as
3526@code{find(a[1];b),find(a[2];b),...}.@refill
3527
3528See also @code{grep} and @code{lose}.
3529@end defun
3530
3531@node first, form, find, Arrays
3532
3533@defun first ( v )
3534The @code{first} function returns the index of the first ``true''
3535element in the vector @var{v}.  If none are found, 0 is returned.@refill
3536
3537See also @code{find} and @code{last}.
3538@end defun
3539
3540@node form, full, first, Arrays
3541
3542@defun form ( shape; x )
3543This function uses the elements of @var{x} to make an entity described
3544by the vector @var{shape}.  If @var{shape} is NULL or has no elements, a
3545scalar is returned.  If @var{shape} has one element, then a vector of
3546length @code{shape[1]} is returned.  If @var{shape} has two elements,
3547then a matrix with @code{shape[1]} rows and @code{shape[2]} columns is
3548returned.@refill
3549
3550The elements of @var{x} are used, in order, to fill the new entity.  For
3551matrices, this proceeds by rows.  If the entity returned has more
3552elements than @var{x}, it is padded with zeros or null strings.  For
3553example, @code{form( 5; "a","b" )} returns the vector
3554@code{("a","b","","","")}.@refill
3555
3556When the return value from @code{form} is a vector or matrix, it will
3557always be dense.  See the @code{cram} function for sparse return arrays.
3558
3559The @code{fill} function differs from this function only in that it
3560reuses the elements of @var{x} rather than padding with zeros.@refill
3561
3562See also @code{fill}, @code{cram}, and @code{zero}.
3563@end defun
3564
3565@node full, gpskca, form, Arrays
3566
3567@cindex Full storage
3568@defun full ( x )
3569The @code{full} function converts a matrix stored in ``sparse_upper''
3570form to the ``sparse'' form.@refill
3571@end defun
3572
3573@node gpskca, grep, full, Arrays
3574
3575@cindex Bandwidth reduction
3576@cindex Gibbs-Poole-Stockmeyer
3577@cindex Gibbs-King
3578@cindex Lewis, John
3579@cindex Profile reduction
3580@cindex Reduction, bandwidth
3581@cindex Reduction, profile
3582@defun gpskca ( m; flag )
3583The @code{gpskca} function attempts to find a symmetric permutation of
3584the rows and columns of matrix @var{m} to reduce either its bandwidth or
3585its profile.  If the @var{flag} argument is ``true'' (in the sense of
3586the @code{test} function, then the Gibbs-Poole-Stockmeyer algorithm is
3587used for bandwidth reduction; otherwise, the Gibbs-King algorithm is
3588used for profile reduction.  See the description of the @code{band}
3589function for a definition of these terms.@refill
3590
3591The return value is the permutation, given as an integer vector with
3592length equal to the order of @var{m}.  Consider the following example
3593interaction:@refill
3594
3595@example
3596> a = symmetric (magic(6) > 25);
3597> band (a)
3598    ( 4, 13, 4, 13 )
3599> v = gpskca (a);
3600> b = a[v;v];
3601> band (b)
3602    ( 2, 9, 2, 9 )
3603@end example
3604
3605@noindent
3606First, the sparse, symmetric matrix @var{a} is created.  The
3607@code{band} function shows that it has a bandwidth of 4 and a profile of
360813.  Next, @code{gpskca} provides a permutation to reduce the profile.
3609The matrix @var{b} is set to equal @var{a} but with this permutation
3610applied.  Finally, @code{band} shows that this permutation reduces both
3611the bandwidth (to 2) and the profile (to 9).
3612
3613The matrix @var{m} must be either symmetric or hermitian.  This function
3614uses the GPSKCA subroutine written by John Lewis.@refill
3615
3616See also @code{band}.
3617@end defun
3618
3619@node grep, hermitian, gpskca, Arrays
3620
3621@cindex grep
3622@cindex Searching
3623@cindex Regular expressions
3624@defun grep ( expr; v )
3625The @code{grep} function finds the elements of the vector @var{v} which
3626match the pattern @code{expr}.  The pattern is an extended regular
3627expression which is given to the UNIX function @code{egrep} to do the
3628searching.@refill
3629
3630The character strings in @var{v} must not contain a newline, or the
3631results will generally be wrong.@refill
3632
3633Here are some examples (user input is preceded by the @samp{>} prompt):
3634
3635@example
3636> grep ("a"; "ab", "ac", "bc")
3637    ( 1, 2 )
3638
3639> grep ("9$"; 1:40)
3640    ( 9, 19, 29, 39 )
3641
3642> m = magic (3)
3643    [ 8  1  6 ]
3644    [ 3  5  7 ]
3645    [ 4  9  2 ]
3646> m.rid = "top", "middle", "bottom";
3647> m[ grep ("top|bottom"; m.rid); ]
3648    [ 8  1  6 ]
3649    [ 4  9  2 ]
3650@end example
3651
3652This is a terribly inefficient implementation (maybe someday Algae will
3653have builtin regular expressions), but maybe you'll find it useful.@refill
3654
3655See also @code{find} and @code{lose}.
3656@end defun
3657
3658@node hermitian, ident, grep, Arrays
3659
3660@defun hermitian ( x )
3661This function returns the hermitian part of the square, numeric matrix
3662@var{x}.  A hermitian matrix has complex-conjugate symmetry.  It's
3663diagonal must necessarily be real.  The returned matrix is complex only
3664if @var{x} is complex.@refill
3665
3666If @var{x} has both row and column labels, they must match.@refill
3667
3668See also @code{symmetric}.@refill
3669@end defun
3670
3671@node ident, imax, hermitian, Arrays
3672
3673@cindex Identity matrix
3674@defun ident ( n )
3675The @code{ident} function returns an identity matrix with @var{n} rows
3676and columns.@refill
3677@end defun
3678
3679@node imax, imin, ident, Arrays
3680
3681@cindex Maximum
3682@defun imax ( v )
3683If @var{v} is a vector, this function returns the number of the
3684element with the greatest value.  If multiple elements qualify, then
3685the number of the first one is returned.@refill
3686
3687If @var{v} is a matrix, then a vector is returned, each element giving
3688the row number of the greatest value in the corresponding column.
3689Again, if more than one element qualifies, the first one is
3690given.@refill
3691
3692If @var{v} is a table, then the @code{imax} function is applied to each
3693of its members.@refill
3694
3695The argument @var{v} may not be a scalar, and must not have complex
3696type.  Note that @code{imax(v)} is not necessarily equal to
3697@code{imin(-v)}.@refill
3698
3699See also @code{imin}, @code{max}, @code{min}, @code{isort}, and @code{sort}.
3700@end defun
3701
3702@node imin, isort, imax, Arrays
3703
3704@cindex Minimum
3705@defun imin ( v )
3706If @var{v} is a vector, this function returns the number of the
3707element with the least value.  If multiple elements qualify, then
3708the number of the last one is returned.@refill
3709
3710If @var{v} is a matrix, then a vector is returned, each element giving
3711the row number of the least value in the corresponding column.
3712Again, if more than one element qualifies, the last one is
3713given.@refill
3714
3715If @var{v} is a table, then the @code{imin} function is applied to each
3716of its members.@refill
3717
3718The argument @var{v} may not be a scalar, and must not have complex
3719type.  Note that @code{imin(v)} is not necessarily equal to
3720@code{imax(-v)}.@refill
3721
3722See also @code{imax}, @code{max}, @code{min}, @code{isort}, and @code{sort}.
3723@end defun
3724
3725@node isort, label, imin, Arrays
3726
3727@cindex Sorting vectors
3728@defun isort ( v )
3729This function sorts the elements of vector @var{v} in increasing order,
3730and returns a vector containing the corresponding indices.  For example,
3731@code{sort(20,40,10,30)} returns the vector @code{(3,1,4,2)}.  The
3732expression @code{v[isort(v)]} actually returns the sorted vector
3733@var{v}, although the builtin function @code{sort} does this more
3734efficiently.  Complex numbers are sorted primarily by real value and
3735secondarily by imaginary value.@refill
3736
3737See also @code{sort}, @code{max}, @code{min}, and @code{set}.
3738@end defun
3739
3740@node label, last, isort, Arrays
3741
3742@defun label ( x; a; b )
3743The @code{label} function assigns labels to vectors and matrices.  If
3744@var{x} is a vector, @var{a} is assigned as its element labels.  If
3745@var{x} is a matrix, @var{a} and @var{b} are assigned as its row and
3746column labels, respectively.  If @var{x} has any other class, an
3747exception is raised.@refill
3748
3749See also @code{unlabel}.
3750@end defun
3751
3752@node last, linspace, label, Arrays
3753
3754@defun last ( v )
3755The @code{last} function returns the index of the last ``true''
3756element in the vector @var{v}.  If none are found, 0 is returned.@refill
3757
3758See also @code{find} and @code{first}.
3759@end defun
3760
3761@node linspace, logspace, last, Arrays
3762
3763@cindex Linear spacing
3764@defun linspace ( a; b; n )
3765The @code{linspace} function generates a vector of @var{n} elements,
3766spaced uniformly between @var{a} and @var{b}.  All three arguments must
3767be (or be convertible to) scalars.  The argument @var{n} must be (or
3768round to) an integer greater than one.@refill
3769
3770The vector generation operator @samp{:} also generates uniformly spaced
3771vectors.  With the operator, the number of elements is determined from
3772the specified spacing; with the @code{linspace} function, the spacing is
3773determined from the number of elements specified.  Also notice that the
3774last element of the vector returned by @code{linspace} is equal to
3775@var{b}, which is not necessarily the case with the @samp{:} operator.@refill
3776
3777See also @code{logspace}.
3778@end defun
3779
3780@node logspace, lose, linspace, Arrays
3781
3782@cindex Logarithmic spacing
3783@defun logspace ( a; b; n )
3784The @code{logspace} function generates a vector of @var{n} elements,
3785spaced logarithmically between @var{a} and @var{b}.  All three arguments must
3786be (or be convertible to) scalars.  Both @var{a} and @var{b} must be
3787nonzero, and @var{n} must be (or round to) an integer greater than one.@refill
3788
3789Logarithmic spacing means that the logarithm of the result vector is a
3790uniformly spaced vector.  This also means that the ratio between any two
3791adjacent elements is constant.  Note that even if both @var{a} and
3792@var{b} are real, the result will be complex if they have opposite
3793signs, and that a complex result will not necessarily form a straight
3794line in the complex plane.
3795
3796See also @code{linspace}.
3797@end defun
3798
3799@node lose, magic, logspace, Arrays
3800
3801@defun lose ( a; b )
3802The @code{lose} function locates elements of @var{b} that do not have
3803the values given by @var{a} and returns a vector containing their
3804element numbers.  For example, @code{lose( 2,3; 0,1,2,3,4 )} returns the
3805vector @code{(1,2,5)}.  One common use is in an expression such as
3806@code{A[lose(77;A.rid);]}, which returns all of the rows of @var{a} that
3807don't have the row label 77.@refill
3808
3809If @var{a} is a scalar, then @code{lose(a;b)} returns the element
3810numbers of @var{b}, sorted from smallest to largest, for which the
3811corresponding element of @var{b} is not equal to @var{a}.  If @var{a} is
3812a vector, then @code{lose(a;b)} returns the intersection of the results of
3813@code{lose(a[1];b)}, @code{lose(a[2];b)}, etc.@refill
3814
3815See also @code{find}.
3816@end defun
3817
3818@node magic, matrix, lose, Arrays
3819
3820@cindex Magic squares
3821@defun magic ( n )
3822The @code{magic} function returns a magic square of order @var{n}.
3823(What system would be complete without it?)  The elements of a magic
3824square consist of all the integers 1 through @var{n^2}, arranged so
3825that the row, column, and the two diagonal sums are equal.@refill
3826
3827@var{n} must be greater than 0.  No magic square exists for order
38282.@refill
3829@end defun
3830
3831@node matrix, max, magic, Arrays
3832
3833@defun matrix ( x )
3834This function converts its argument @var{x} to a matrix if possible.
3835Scalars become one-by-one matrices, vectors become matrices with one
3836row, and matrices are unchanged.  If @var{x} is NULL, @code{matrix}
3837returns a real matrix with zero rows and zero columns.@refill
3838
3839See also @code{scalar} and @code{vector}.
3840@end defun
3841
3842@node max, merge, matrix, Arrays
3843
3844@cindex Maximum
3845@defun max ( v )
3846If @var{v} is a vector, this function returns its greatest value.
3847If @var{v} is a matrix, then a vector is returned, each element giving
3848the greatest value of any element in the corresponding column.@refill
3849
3850If @var{v} is a table, then the @code{max} function is applied to each
3851of its members.@refill
3852
3853The argument @var{v} may not be a scalar, and must not have complex
3854type.@refill
3855
3856See also @code{min}, @code{imax}, @code{imin}, @code{isort}, and @code{sort}.
3857@end defun
3858
3859@node merge, min, max, Arrays
3860
3861@defun merge ( x; y )
3862This function merges two entities, @var{x} and @var{y}, with respect to
3863their labels.  The result has labels that consist of the union of the
3864labels of @var{x} and @var{y}.  Its elements come from the corresponding
3865elements in @var{x} and @var{y}; they are summed when the same element
3866occurs in both.@refill
3867
3868This is demonstrated by the following interactive session:
3869
3870@example
3871> A = fill (3,3; 1:9)
3872        [  1   2   3 ]
3873        [  4   5   6 ]
3874        [  7   8   9 ]
3875> A.rid = A.cid = 1:3;
3876> B = fill (3,3; 10:90:10)
3877        [ 10  20  30 ]
3878        [ 40  50  60 ]
3879        [ 70  80  90 ]
3880> B.rid = B.cid = 2:4;
3881> merge (A; B)
3882        [  1   2   3   0 ]
3883        [  4  15  26  30 ]
3884        [  7  48  59  60 ]
3885        [  0  70  80  90 ]
3886@end example
3887
3888If @var{x} and @var{y} are not vectors or matrices, they are simply
3889summed.@refill
3890@end defun
3891
3892@node min, mksparse, merge, Arrays
3893
3894@cindex Minimum
3895@defun min ( v )
3896If @var{v} is a vector, this function returns its least value.
3897If @var{v} is a matrix, then a vector is returned, each element giving
3898the least value of any element in the corresponding column.@refill
3899
3900If @var{v} is a table, then the @code{min} function is applied to each
3901of its members.@refill
3902
3903The argument @var{v} may not be a scalar, and must not have complex
3904type.@refill
3905
3906See also @code{max}, @code{imax}, @code{imin}, @code{isort}, and @code{sort}.
3907@end defun
3908
3909@node mksparse, norm, min, Arrays
3910
3911@defun mksparse ( t )
3912This function returns a sparse matrix with dimensions and elements given
3913by the members of table @var{t}.  If the member @var{shape} exists, it
3914should be a vector with two elements specifying the number of rows and
3915columns of the matrix.  If it does not exist, the matrix is sized just
3916large enough to include all of the given elements.  The members
3917@var{rows}, @var{cols}, and @var{values} must all exist; these are
3918vectors, all with the same length, corresponding elements of which
3919specify respectively the row number, column number, and value of each
3920specified element of the matrix.  If an element is not specified, it is
3921zero.  If an element is given more than once, its value is the sum of
3922the given values.@refill
3923
3924The following interactive session provides an example:
3925
3926@example
3927> mksparse (@{shape=3,4; rows=1,2,3; cols=1,3,2; values=10,11,12@})
3928	[          10          .          .          . ]
3929	[           .          .         11          . ]
3930	[           .         12          .          . ]
3931@end example
3932
3933The @var{values} vector must have numeric type.  If @var{t} is NULL, a
3934real matrix with 0 rows and 0 columns is returned.@refill
3935
3936See also @code{sparse} and @code{exsparse}.
3937@end defun
3938
3939@node norm, pick, mksparse, Arrays
3940
3941@cindex Norm
3942@cindex Matrix norm
3943@cindex Vector norm
3944@defun norm ( x; p )
3945The @code{norm} function computes the @var{p}-norm of @var{x}, where
3946@var{p} is 1, 2, ``frobenius'', or ``infinity''.  (The latter two may be
3947abbreviated as ``frob'' and ``inf''.)  If @var{p} is not specified, the
39482-norm is used.@refill
3949
3950For complex @var{x}, the 1 and ``infinity'' norms deal not with the
3951magnitude of each element, but with the sum of the absolute values of
3952the real and imaginary parts.@refill
3953@end defun
3954
3955@node pick, product, norm, Arrays
3956
3957@defun pick ( x )
3958This function returns a vector containing the indices of the non-zero
3959elements of the numeric input vector @var{x}.  For example, the
3960expression@refill
3961
3962@example
3963V [ pick (V < 0) ]
3964@end example
3965
3966returns all of the negative elements of @code{V}.
3967
3968See also @code{find}.
3969@end defun
3970
3971@node product, rand, pick, Arrays
3972
3973@defun product ( x )
3974The @code{product} function computes the product of the elements of an
3975array.  If @var{x} is a scalar, it is returned unchanged.  If @var{x} is
3976a vector, the product of all of its elements is returned.  If @var{x} is a
3977matrix, a vector is returned, each element of which is the product of the
3978elements in the corresponding columns of @var{x}.  If @var{x} is a
3979table, the @code{product} function is applied to each of its members.@refill
3980@end defun
3981
3982@node rand, randn, product, Arrays
3983
3984@cindex Random numbers
3985@defun rand ( shape )
3986This function generates pseudo-random numbers with a uniform
3987distribution in the range from 0 to 1.  Called with no arguments, it
3988returns a scalar.  Otherwise, the vector @var{shape} specifies a vector
3989or matrix; see the @code{readnum} function for more information.@refill
3990
3991The random number generator may be ``seeded'' with the @code{srand}
3992function.  If you don't call @code{srand}, the seed is based on the
3993system's clock.  Note that @code{rand} and @code{randn} share the same
3994seed.@refill
3995
3996See also @code{randn} and @code{srand}.
3997@end defun
3998
3999@node randn, reverse, rand, Arrays
4000
4001@cindex Random numbers
4002@defun randn ( shape )
4003This function generates pseudo-random numbers from a normal distribution
4004with zero mean and unit variance.  Called with no arguments, it returns a
4005scalar.  Otherwise, the vector @var{shape} specifies a vector or matrix;
4006see the @code{readnum} function for more information.@refill
4007
4008The random number generator may be ``seeded'' with the @code{srand}
4009function.  If you don't call @code{srand}, the seed is based on the
4010system's clock.  Note that @code{rand} and @code{randn} share the same
4011seed.@refill
4012
4013See also @code{rand} and @code{srand}.
4014@end defun
4015
4016@node reverse, scalar, randn, Arrays
4017
4018@defun reverse ( v )
4019The @code{reverse} function simply reverses the order of the elements in
4020vector @var{v}.  For example, @code{reverse(1,2,3)} returns the vector
4021@code{(3,2,1)}.@refill
4022@end defun
4023
4024@node scalar, select, reverse, Arrays
4025
4026@defun scalar ( x )
4027This function converts its argument @var{x} to a scalar if possible.
4028See also @code{matrix} and @code{vector}.@refill
4029@end defun
4030
4031@node select, seq, scalar, Arrays
4032
4033@defun select ( x )
4034The @code{select} function selects one element at random from the given
4035vector.  The result is a scalar.  The vector @var{x} must have at least
4036one element.@refill
4037@end defun
4038
4039@node seq, shape, select, Arrays
4040
4041@defun seq ( n )
4042The @code{seq} function returns a vector of consecutive integers from 1
4043to @var{n}.  The argument @var{n} is first rounded to the nearest
4044integer; if it is less than 1, a zero-length vector is returned.@refill
4045@end defun
4046
4047@node shape, sign, seq, Arrays
4048
4049@defun shape ( x )
4050This function returns the ``shape'' (that is, the dimensions) of its
4051argument @var{x}.  This return value has the same form as is used for
4052the @var{shape} arguments of functions like @var{readnum} and @var{rand}.
4053If @var{x} is a scalar, NULL is returned.  If @var{x} is a vector, a
4054scalar is returned having the length of @var{x} as its value.  If
4055@var{x} is a matrix, a vector is returned having the number of rows and
4056the number of columns as its first and second elements, respectively.
4057If @var{x} has any other class, an exception is raised.
4058@end defun
4059
4060@node sign, sort, shape, Arrays
4061
4062@cindex Signum
4063@cindex Sign
4064@defun sign ( v )
4065The @code{sign} function returns an array with the same size as
4066@var{v}.  Each element of the returned array is either -1, 0, or +1,
4067depending on whether the corresponding element of @var{v} is negative,
4068zero, or positive, respectively.  The argument @var{v} must be a numeric
4069scalar or array.@refill
4070@end defun
4071
4072@node sort, sparse, sign, Arrays
4073
4074@cindex Sorting vectors
4075@defun sort ( v )
4076This function sorts the elements of vector @var{v} in increasing order.
4077For example, @code{sort(20,40,10,30)} returns the vector
4078@code{(10,20,30,40)}.  Complex numbers are sorted primarily by real
4079value and secondarily by imaginary value.@refill
4080
4081See also @code{isort}, @code{max}, @code{min}, and @code{set}.
4082@end defun
4083
4084@node sparse, srand, sort, Arrays
4085
4086@cindex Sparse storage
4087@defun sparse ( x )
4088This function converts its argument @var{x} to sparse storage.@refill
4089@end defun
4090
4091@node srand, sum, sparse, Arrays
4092
4093@cindex Random numbers
4094@defun srand ( s )
4095The @code{srand} function is used to ``seed'' the random number
4096generator @code{rand}.  (OK, they're really pseudo-random numbers.)  The
4097seed @var{s} determines the sequence of numbers returned by @code{rand}.
4098If @var{s} is NULL (or if @code{srand} is never called at all), then the
4099seed is taken from the system's clock.  See also @code{rand}.@refill
4100@end defun
4101
4102@node sum, surprise, srand, Arrays
4103
4104@defun sum ( x )
4105The @code{sum} function sums elements of arrays.  If @var{x} is a
4106scalar, it is returned unchanged.  If @var{x} is a vector, the sum of
4107all of its elements is returned.  If @var{x} is a matrix, a vector is
4108returned, each element of which is the sum of the elements in the
4109corresponding columns of @var{x}.@refill
4110@end defun
4111
4112@node surprise, symmetric, sum, Arrays
4113
4114@defun surprise ( rows; cols; type; density; symmetry; other )
4115The @code{surprise} function returns a more-or-less random matrix with
4116characteristics given by the input arguments.  It may be useful for
4117testing or timing purposes.@refill
4118
4119Each of the arguments to @code{surprise} may be a vector, in which case
4120one of its members is chosen at random for that characteristic.  For
4121example, if @var{rows} is the vector @code{4,5,6} then the resulting
4122array will have either 4, 5, or 6 rows.@refill
4123
4124The @var{rows} and @var{cols} arguments specify the number of rows and
4125columns in the array.  The choice of dimensions has a lower priority
4126than the other characteristics, so any dimensions that are incompatible
4127with other choices are discarded.  For example, consider the call@refill
4128
4129@example
4130surprise (3,4; 4,5; "real"; ; "general","symmetric")
4131@end example
4132
4133@noindent
4134This specifies a real matrix that is either general or symmetric.  If
4135general symmetry is chosen, then the array will have either 3 or 4 rows
4136and either 4 or 5 columns.  However, if a symmetric array is chosen,
4137then it must be square and the result will have 4 rows and 4
4138columns.@refill
4139
4140On the other hand, the specified dimensions can affect the choice of the
4141other characteristics.  For example, in the call@refill
4142
4143@example
4144surprise (3; 4; "real"; ; "general","symmetric")
4145@end example
4146
4147@noindent
4148the result will not be symmetric, because the dimensions preclude
4149it.@refill
4150
4151The @var{type} argument may contain any or all of the character strings
4152@code{"integer"}, @code{"real"}, or @code{"complex"}.  Only numeric
4153types are supported.  The default is @code{"real"}.@refill
4154
4155The @var{density} argument specifies the approximate ratio of nonzero to
4156total array elements.  For diagonal arrays, only the diagonal elements
4157are considered.  The default is 1.0.@refill
4158
4159The @var{symmetry} argument may be @code{"general"}, @code{"symmetric"},
4160or @code{"hermitian"}.  The default is @code{"general"}.@refill
4161
4162The @var{other} argument may be @code{"none"}, @code{"diagonal"}, or
4163@code{"positive_definite"}.  The default is @code{"none"}.@refill
4164@end defun
4165
4166@node symmetric, tril, surprise, Arrays
4167
4168@defun symmetric ( x )
4169This function returns the symmetric part of the square, numeric matrix
4170@var{x}.  If @var{x} has both row and column labels, they must match.@refill
4171
4172See also @code{hermitian}.@refill
4173@end defun
4174
4175@node tril, triu, symmetric, Arrays
4176
4177@cindex Triangle
4178@cindex Lower triangle
4179@defun tril ( a; k )
4180The @code{tril} function returns the lower ``triangular'' part of the
4181matrix @var{a}.  The return matrix is identical to @var{a} except that,
4182for any @code{i}, all elements @code{a[i;i+k+1]}, @code{a[i;i+k+2]},
4183etc. are zero.  If @var{k} is NULL, it defaults to zero.  Here is an
4184example:@refill
4185
4186@example
4187> tril (magic (4); 1)
4188        [  9   7   0   0 ]
4189        [  4  14  15   0 ]
4190        [ 16   2   3  13 ]
4191        [  5  11  10   8 ]
4192@end example
4193@end defun
4194
4195@node triu, unlabel, tril, Arrays
4196
4197@cindex Triangle
4198@cindex Upper triangle
4199@defun triu ( a; k )
4200The @code{triu} function returns the upper ``triangular'' part of the
4201matrix @var{a}.  The return matrix is identical to @var{a} except that,
4202for any @code{i}, all elements @code{a[i;i+k-1]}, @code{a[i;i+k-2]},
4203etc. are zero.  If @var{k} is NULL, it defaults to zero.  Here is an
4204example:@refill
4205
4206@example
4207> triu (magic (4); 1)
4208        [  0   7   6  12 ]
4209        [  0   0  15   1 ]
4210        [  0   0   0  13 ]
4211        [  0   0   0   0 ]
4212@end example
4213@end defun
4214
4215@node unlabel, vector, triu, Arrays
4216
4217@defun unlabel ( x )
4218The @code{unlabel} function removes the labels from its argument.  If
4219@var{x} is a vector or a matrix, it sets the labels to NULL and returns
4220the result.  If @var{x} has any other class, it is returned
4221unchanged.@refill
4222@end defun
4223
4224@node vector, zero, unlabel, Arrays
4225
4226@defun vector ( x )
4227This function converts its argument @var{x} to a vector if possible.
4228Scalars become one-element vectors.  If @var{x} is a matrix with either
4229one row or one column, then it is converted to a vector.@refill
4230
4231See also @code{scalar} and @code{matrix}.
4232@end defun
4233
4234@node zero, , vector, Arrays
4235
4236@defun zero ( shape )
4237This function generates an integer scalar, vector, or matrix, all the
4238elements of which are zero.  The vector @var{shape} specifies the
4239dimensions of the entity returned; see the @code{readnum} function for more
4240information.@refill
4241
4242If a vector or matrix is returned, it is stored in sparse form.  This
4243may or may not be the most efficient storage for your application; use
4244the @code{dense} function to convert it if desired.@refill
4245
4246See also @code{dense}.
4247@end defun
4248
4249@node Sets, Linear Algebra, Arrays, Standard Functions
4250@section Sets
4251
4252@ifinfo
4253@menu
4254* complement::		complement
4255* intersection::	intersection
4256* set::			make a set
4257* union::		union
4258@end menu
4259@end ifinfo
4260
4261@node complement, intersection, Sets, Sets
4262
4263@cindex Complement
4264@defun complement ( a; b )
4265The @code{complement} function returns the relative complement of
4266@var{a} in @var{b}; that is, the set of elements of @var{b} which are
4267not in @var{a}.  The return value is a set, which we define as a sorted,
4268irredundant vector.  ``Sorted'' means sorted by increasing value;
4269character strings are sorted by ASCII values and complex numbers
4270are sorted with the real values as the primary key and the imaginary
4271values as the secondary key.@refill
4272
4273If @var{b} has labels, then the returned vector also has labels that
4274correspond to the retained elements.  If @var{b} has no labels, the
4275labels of the returned vector give the index of the corresponding
4276element in @var{b}.@refill
4277
4278If @var{b} has redundant elements, the element retained is not
4279necessarily the first.  For example, @code{complement(1;2,2,2).eid}
4280might be 1, 2, or 3.@refill
4281
4282See also @code{intersection}, @code{set}, and @code{union}.
4283@end defun
4284
4285@node intersection, set, complement, Sets
4286
4287@cindex Intersection
4288@defun intersection ( a; b )
4289The @code{intersection} function returns the intersection of set @var{a}
4290in @var{b}; that is, the set of elements that are in both @var{a} and
4291@var{b}.  The return value is a set, which we define as a sorted,
4292irredundant vector.  ``Sorted'' means sorted by increasing value;
4293character strings are sorted by ASCII values and complex numbers
4294are sorted with the real values as the primary key and the imaginary
4295values as the secondary key.@refill
4296
4297The return vector has no labels.
4298
4299See also @code{complement}, @code{set}, and @code{union}.
4300@end defun
4301
4302@node set, union, intersection, Sets
4303
4304@cindex Sets
4305@defun set ( x )
4306This function changes @var{x} into a set, if possible.  A ``set'' is
4307defined as a sorted, irredundant vector.  ``Sorted'' means sorted by
4308increasing value; character strings are sorted by ASCII values and
4309complex numbers are sorted with the real values as the primary key and
4310the imaginary values as the secondary key.  ``Irredundant'' means that
4311no two elements have the same value.@refill
4312
4313If @var{x} has labels, then the returned vector also has labels that
4314correspond to the retained elements.  If @var{x} has no labels, the
4315labels of the returned vector give the index of the corresponding
4316element in @var{x}.@refill
4317
4318If @var{x} has redundant elements, the element retained is not
4319necessarily the first.  For example, @code{set(1,1,1).eid} might be 1,
43202, or 3.@refill
4321
4322See also @code{complement}, @code{intersection}, and @code{union}.
4323@end defun
4324
4325@node union, , set, Sets
4326
4327@cindex Union of two sets
4328@defun union ( a; b )
4329The @code{union} function returns the union of sets @var{a} and @var{b}.
4330The return value is a set, which we define as a sorted, irredundant
4331vector.  ``Sorted'' means sorted by increasing value; character strings
4332are sorted by ASCII values and complex numbers are sorted with the
4333real values as the primary key and the imaginary values as the secondary
4334key.@refill
4335
4336The return vector will always have labels.  To understand them, you
4337need to know that the function call @code{union(a;b)} is identical to
4338the code @code{set(a,b)} provided that @var{a} and @var{b} are both
4339vectors.  (The @code{union} function will convert them both to
4340vectors if necessary.)@refill
4341
4342See also @code{complement}, @code{intersection}, and @code{set}.
4343@end defun
4344
4345@node Linear Algebra, Numerical Analysis, Sets, Standard Functions
4346@section Linear Algebra
4347
4348@ifinfo
4349@menu
4350* backsub::     back substitution
4351* chol::        Cholesky factorization
4352* eig::		eigenvalues and eigenvectors
4353* equilibrate:: matrix equilibration
4354* factor::	triangular factorization
4355* fft::		fast Fourier transform
4356* filter::      digital filter
4357* ifft::	inverse fast Fourier transform
4358* inv::		matrix inverse
4359* iram::        Arnoldi method for eigenvalue problems
4360* leastsq::     least squares solver
4361* mult::        efficient matrix products
4362* solve::	solve a linear system
4363* ssi::		subspace iteration for eigenvalues
4364* svd::		singular value decomposition
4365* transform::	linear transformation
4366@end menu
4367@end ifinfo
4368
4369@node backsub, chol, Linear Algebra, Linear Algebra
4370
4371@cindex Back substitution
4372@cindex Forward substitution
4373@cindex Solving linear equations
4374@cindex Linear equations
4375@defun backsub ( afac; b )
4376The @code{backsub} function solves the set of linear equations
4377@code{A*x=b} for @var{x}.  (Despite the name, it does both forward and
4378backward substitution.)  The argument @var{afac} must contain the
4379factorization of @code{A} returned as a table from either of the
4380functions @code{factor} or @code{chol}.  The argument @var{b} provides
4381the right-hand side.@refill
4382
4383@cindex SuperLU
4384@cindex LAPACK
4385This function handles both LAPACK (dense) and SuperLU (sparse) factors.
4386It determines the appropriate solution method based on the members in
4387the @var{afac} table.@refill
4388
4389@cindex BCSLIB-EXT
4390@cindex Boeing Computer Services
4391If @sc{bcslib-ext} (a sparse math library produced by Boeing Computer
4392Services) is available on your system and Algae has been compiled
4393for it, then the @code{backsub} function can use it.  If @var{afac}
4394contains factors computed by @sc{bcslib-ext} routines (in @code{factor}
4395or @code{chol}), then @code{backsub} will call the corresponding
4396routines to perform the back substitution.@refill
4397
4398See also @code{chol}, @code{factor}, and @code{solve}.
4399@end defun
4400
4401@node chol, eig, backsub, Linear Algebra
4402
4403@cindex Cholesky factorization
4404@cindex Matrix factorization
4405@defun chol ( m )
4406The @code{chol} function computes the Cholesky factorization of the
4407symmetric, positive definite matrix @var{m}.  The factors are returned
4408in a table, which may contain a variety of members depending on the type
4409and density of @var{m}.  For example, if @var{m} is a real, dense
4410matrix, then @code{"L"} (the output of the @sc{lapack} routine
4411@code{DSYTRF} routine) and @code{"RCOND"} are returned.  For now, you'll
4412have to go digging in the code if you really want to understand the
4413output.  The idea, though, is that functions like @code{backsub} can
4414make sense of them so that you don't have to.@refill
4415
4416Although its other members vary, the table returned by @code{chol}
4417always contains a member named @code{"RCOND"}.  This non-negative real
4418scalar is an estimate of the reciprocal of the condition number of
4419@var{m}.  If @code{"RCOND"} is very small (that is, the condition number
4420is very large), then the matrix @var{m} is ill-conditioned.  A warning
4421message is produced if @code{"RCOND"} is less than 1.0E-8.@refill
4422
4423The key difference between the @code{chol} and @code{factor} functions
4424is that @code{chol} requires that the matrix be symmetric and positive
4425definite.  In that case, no pivoting is required; this generally results
4426in a savings in execution time over the @code{factor} function.@refill
4427
4428Unless the matrix @var{m} happens to be diagonal (or BCSLIB-EXT is
4429used), @code{chol} uses a dense method from LAPACK.  Consequently,
4430@code{factor} is preferred over @code{chol} for large, sparse
4431systems.@refill
4432
4433@cindex BCSLIB-EXT
4434@cindex Boeing Computer Services
4435If @sc{bcslib-ext} (a sparse math library produced by Boeing Computer
4436Services) is available on your system and Algae has been compiled
4437for it, then @code{chol} may use its routines to factor sparse matrices.
4438In turn, the @code{backsub} and @code{solve} functions can use these
4439factors to solve linear equations.  It is often useful to compute the
4440factors of a matrix and then save them (using @code{put}) for later use.
4441Keep in mind, however, that if these factors were computed with the
4442@sc{bcslib-ext} routines, then the Algae version with which you
4443intend to use them must also support @sc{bcslib-ext}.  The table
4444returned by @code{chol} contains the member @code{HOLD} iff a
4445@sc{bcslib-ext} routine was used to produce it.  @sc{bcslib-ext} is
4446never used on dense matrices.@refill
4447
4448See also @code{backsub}, @code{factor}, and @code{solve}.
4449@end defun
4450
4451@node eig, equilibrate, chol, Linear Algebra
4452
4453@cindex Eigenvalues and eigenvectors
4454@defun eig ( a; b; opts )
4455The @code{eig} function computes eigenvalues and eigenvectors for the
4456standard and generalized eigenvalue problems@refill
4457@example
4458A * x = lambda * x
4459@end example
4460@noindent
4461and
4462@example
4463A * x = lambda * B * x
4464@end example
4465
4466@noindent
4467If @var{a} is the only matrix argument, then both @var{lambda} and
4468@var{x} are computed for the standard problem.  If a matrix @var{b} is
4469given as the second argument, then the generalized problem is solved.@refill
4470
4471A table of options @var{opts} may be given as the last argument.  If it
4472contains the member @code{no_right}, then the right eigenvectors @var{x}
4473are not computed.  If it contains the member @code{left}, then the
4474corresponding left eigenvectors are computed.@refill
4475
4476This function returns a table containing the eigenvalues in a member
4477called @code{values} and, if appropriate, the (right) eigenvectors in a
4478member called @code{vectors}.  If the @code{left} option was given and
4479the problem is unsymmetric, then the left eigenvectors are returned in a
4480member called @code{left_vectors}.@refill
4481
4482The solution method used depends on the type and symmetry of the
4483coefficient arrays.  Some of these methods entail strict requirements,
4484such as positive definiteness, on the matrices.  Each case is described
4485below, along with the LAPACK routine called to solve it.  See the
4486@cite{LAPACK Users' Guide} for more information.@refill
4487
4488For real, symmetric, standard problems, DSYEV is used.  The eigenvalues
4489are real and in ascending order; the eigenvectors are orthonormal.@refill
4490
4491For complex, hermitian, standard problems, ZHEEV is used.  The
4492eigenvalues are real and in ascending order; the eigenvectors are
4493orthonormal.@refill
4494
4495For nonsymmetric, standard problems, DGEEV is used for real type and
4496ZGEEV for complex type.  The eigenvalues are complex, and complex
4497conjugate pairs appear consecutively with the eigenvalue having the
4498positive imaginary part first.  The eigenvectors are normalized to have
4499Euclidean norm equal to 1 and largest component real.@refill
4500
4501For real, symmetric, generalized problems, DSYGV is used.  This method
4502requires that @var{a} be symmetric and that @var{b} be symmetric and
4503positive definite.  The eigenvalues are real and in ascending order.
4504The eigenvectors are @var{b}-orthonormal.@refill
4505
4506For real, nonsymmetric, generalized problems, DGGEV is used.  This
4507method performs full balancing on @var{a} and @var{b}.  The eigenvalues
4508are complex, and complex conjugate pairs appear consecutively with the
4509eigenvalue having the positive imaginary part first.  Note, however,
4510that the eigenvalues are returned in a table; the member @code{num}
4511contains their numerators and member @code{denom} contains their
4512denominators.  The quotients may easily overflow or underflow, and the
4513denominator (and maybe the numerator, too) may be zero.  A good
4514beginning reference is the book @cite{Matrix Computations} by G. Golub
4515and C. Van Loan.  Each eigenvector is scaled so that the sum of the
4516absolute values of the real and imaginary parts of the largest component
4517is 1, except that for eigenvalues with numerator and denominator both
4518zero, the corresponding eigenvector is zero.@refill
4519
4520For complex, hermitian, generalized problems, ZHEGV is used.  This method
4521requires that @var{a} be hermitian and that @var{b} be hermitian and
4522positive definite.  The eigenvalues are real and in ascending order.
4523The eigenvectors are @var{b}-orthonormal.@refill
4524
4525For complex, nonsymmetric, generalized problems, ZGGEV is used.  The
4526eigenvalues and eigenvectors are complex.  Note, however, that the
4527eigenvalues are returned in a table; the member @code{num} contains
4528their numerators and member @code{denom} contains their denominators.
4529The quotients may easily overflow or underflow, and the denominator (and
4530maybe the numerator, too) may be zero.  A good beginning reference is
4531the book @cite{Matrix Computations} by G. Golub and C. Van Loan.  Each
4532eigenvector is scaled so that the sum of the absolute values of the real
4533and imaginary parts of the largest component is 1, except that for
4534eigenvalues with numerator and denominator both zero, the corresponding
4535eigenvector is zero.@refill
4536
4537See also @code{iram}.
4538@end defun
4539
4540@node equilibrate, factor, eig, Linear Algebra
4541
4542@cindex Equilibration
4543@cindex Condition number
4544@defun equilibrate ( A )
4545The @code{equilibrate} function computes row and column scalings
4546intended to equilibrate a matrix and reduce its condition
4547number.  The input matrix @var{A} need not be square, but it must be
4548numeric and both dimensions must be nonzero.  If @var{A} is hermitian or
4549real symmetric, it must be positive definite.@refill
4550
4551If @code{equilibrate} succeeds, it returns a table containing the
4552following members:
4553
4554@table @var
4555@item r
4556A vector containing the row scale factors.
4557
4558@item c
4559A vector containing the column scale factors.
4560
4561@item rowcnd
4562The (scalar) ratio of the smallest to the largest of the row scale
4563factors.
4564
4565@item colcnd
4566The (scalar) ratio of the smallest to the largest of the column scale
4567factors.
4568
4569@item amax
4570The (scalar) absolute value of the largest matrix element.
4571@end table
4572
4573Even if the matrix @var{A} is symmetric or hermitian, the row and column
4574scale factors may or may not be identical.  If not, the resulting
4575equilibrated matrix would no longer be symmetric or hermitian.  You will
4576have to decide whether the improvement in matrix condition is worth the
4577loss of symmetry.  The row and column scale factors will be identical
4578for dense, real, symmetric matrices and for dense, complex, hermitian
4579matrices (both of which must also be positive definite); otherwise,
4580there's no guarantee.@refill
4581
4582Oftentimes, going on to apply the equilibration scale factors is not
4583worth the effort.  Roughly speaking, if @var{amax} is not close to
4584overflow or underflow and both @var{rowcnd} and @var{colcnd} are greater
4585than 0.1, it probably isn't worth doing.@refill
4586
4587If @code{equilibrate} is unsuccessful, it returns a scalar integer
4588instead of a table.  If this value is positive, it indicates the row
4589causing the problem.  If it is negative, its absolute value indicates
4590the column causing the problem.@refill
4591
4592To apply the equilibration, the matrix must be pre- and post-multiplied
4593by the scale factors.  If @var{r} and @var{c} are identical, you'll
4594probably want to use the @code{transform} function to preserve symmetry.
4595Here is an example usage:
4596
4597@example
4598e = equilibrate (A);
4599if (equal (e.r; e.c))
4600@{
4601  Ae = transform (A; diag (e.r));
4602else
4603  Ae = diag (e.r) * A * diag (e.c);
4604@}
4605@end example
4606
4607@noindent
4608Notice, though, that this example does not check the result of
4609@code{equilibrate} to determine if it succeeded, it applies the scale
4610factors without checking to see if it's worth it, and it assumes that
4611@var{A} obeys the requirement regarding positive definiteness.@refill
4612@end defun
4613
4614@node factor, fft, equilibrate, Linear Algebra
4615
4616@cindex Matrix factorization
4617@defun factor ( m )
4618The @code{factor} function computes a triangular factorization of the
4619matrix @var{m}.  The factors are returned in a table, which may contain
4620a variety of members depending on the type, density, and definition of
4621@var{m}.  For example, if @var{m} is a real, dense, symmetric matrix,
4622then @code{"LD"} and @code{"IPIV"} (the output of the @sc{lapack}
4623routine @code{DSYTRF} routine) are returned.  For now, you'll have to go
4624digging in the code if you really want to understand the output.  The
4625idea, though, is that functions like @code{backsub} can make sense of them
4626so that you don't have to.@refill
4627
4628For sparse systems, the SuperLU package is used.  These routines reorder
4629the columns of the matrix to increase its sparsity, and perform dynamic
4630pivoting of the rows for numerical stability.  (No advantage is taken of
4631symmetry.)  For the column ordering, the Multiple Minimum Degree (MMD)
4632algorithm is used if the matrix is symmetric; otherwise, the Column
4633Approximate Minimum Degree (COLAMD) algorithm is used.  Currently, there
4634is no provision to supply your own ordering.@refill
4635
4636Although its other members vary, the table returned by @code{factor}
4637always contains a member named @code{"RCOND"}.  This non-negative real
4638scalar is an estimate of the reciprocal of the condition number of
4639@var{m}.  If @code{"RCOND"} is very small (that is, the condition number
4640is very large), then the matrix @var{m} is ill-conditioned.  A warning
4641message is produced if @code{"RCOND"} is less than 1.0E-8.@refill
4642
4643@cindex BCSLIB-EXT
4644@cindex Boeing Computer Services
4645If @sc{bcslib-ext} (a sparse math library produced by Boeing Computer
4646Services) is available on your system and Algae has been compiled
4647for it, then @code{factor} may use its routines to factor sparse matrices.
4648In turn, the @code{backsub} and @code{solve} functions can use these
4649factors to solve linear equations.  It is often useful to compute the
4650factors of a matrix and then save them (using @code{put}) for later use.
4651Keep in mind, however, that if these factors were computed with the
4652@sc{bcslib-ext} routines, then the Algae version with which you
4653intend to use them must also support @sc{bcslib-ext}.  The table
4654returned by @code{factor} contains the member @code{HOLD} iff a
4655@sc{bcslib-ext} routine was used to produce it.  @sc{bcslib-ext} is
4656never used on dense matrices.@refill
4657
4658The key difference between the @code{chol} and @code{factor} functions
4659is that @code{chol} requires that the matrix be symmetric and positive
4660definite.  In that case, no pivoting is required; this generally results
4661in a savings in execution time over the @code{factor} function.@refill
4662
4663See also @code{backsub}, @code{chol}, and @code{solve}.
4664@end defun
4665
4666@node fft, filter, factor, Linear Algebra
4667
4668@cindex Fourier transform
4669@defun fft ( x; opts )
4670The @code{fft} function computes the complex discrete Fourier
4671transform of the vector (or matrix---see below) @var{x} using the fast
4672Fourier transform method.  The result is ordered such that the
4673corresponding frequencies are increasing (from negative to positive).
4674Note that this is a different order than that returned by many FFT
4675routines.@refill
4676
4677If @var{x} has @code{N} elements, the transform is a complex vector with
4678the same length.  If @code{N} is even, then element @code{k} of the
4679transform is equal to@refill
4680@example
4681sum (x @@ exp (-2*i*pi*(k-N/2)*((1:N)-1)/N))
4682@end example
4683If @code{N} is odd, then element @code{k} is equal to
4684@example
4685sum (x @@ exp (-2*i*pi*(k-(N+1)/2)*((1:N)-1)/N))
4686@end example
4687
4688The method is most efficient when the number of elements in @var{x} is
4689the product of small primes.  For example, a vector with 1021 elements
4690(a large prime number) takes roughly 100 times longer to transform than
4691a vector with 1024 elements (a power of 2).  On the other hand, 1152
4692elements (with prime factors of 2 and 3) is almost as fast as
46931024.@refill
4694
4695If @var{x} has integer or real labels, they are taken to be the
4696corresponding abscissae (i.e., time or distance) and are transformed
4697accordingly to form labels for the results vector.  In that case, the
4698label values must be evenly spaced.@refill
4699
4700If @var{x} is a matrix, the transform is computed for each row or
4701column.  By default this is done by column, but you can change it to
4702work by rows by supplying the @code{row} option, as described below.@refill
4703
4704The argument @var{opts} is an options table; it may contain any or all
4705of the following members.  (The values of these members are
4706irrelevant; only their existence is signficant.)@refill
4707
4708@table @code
4709@item row
4710If @var{x} is a matrix, this option causes the transform of each row
4711to be computed.  By default, the columns are transformed.
4712
4713@cindex FFTW
4714@item estimate
4715When planning the transform, use a simple heuristic to pick a
4716(probably sub-optimal) plan quickly.  This is the default rigor.  This
4717and the following options have an effect only if Algae has been
4718linked with the FFTW package.
4719
4720@item measure
4721Find an optimized plan by actually computing several FFTs and
4722measuring their execution time.
4723
4724@item patient
4725Like @code{measure}, but considers a wider range of algorithms.  This
4726may produce a ``more optimal'' plan, but at the expense of a longer
4727planning time.
4728
4729@item exhaustive
4730Like @code{patient}, but with an even wider range of algorithms and
4731substantially increased planning time.
4732
4733@item forget
4734Plans are kept for use on subsequent FFTs with the same size and
4735characteristics.  The @code{forget} option causes this accumulated
4736information to be discarded.
4737@end table
4738
4739See also @code{ifft}.
4740@end defun
4741
4742@node filter, ifft, fft, Linear Algebra
4743
4744@cindex Digital filter
4745@defun filter ( b; a; x; z )
4746The @code{filter} function computes a digital filter from the standard
4747difference equation@refill
4748@example
4749y[n] = b[1]*x[n] + b[2]*x[n-1] + b[3]*x[n-2] + ...
4750                 - a[2]*y[n-1] - a[3]*y[n-2] - ...
4751@end example
4752
4753This filter is implemented using the "direct form II transposed"
4754method.  For more information, see Chapter 6 of the book "Discrete-Time
4755Signal Processing" by Oppenheim and Schafer.@refill
4756@end defun
4757
4758@node ifft, inv, filter, Linear Algebra
4759
4760@cindex Inverse fourier transform
4761@defun ifft ( x )
4762The @code{ifft} function computes the complex inverse discrete Fourier
4763transform of the vector (or matrix---see below) @var{x} using the fast
4764Fourier transform method.  The input is ordered such that the
4765corresponding frequencies are increasing (from negative to positive).
4766Note that this is a different order than that required by many inverse
4767FFT routines.@refill
4768
4769If @var{x} has @code{N} elements, the transform is a complex vector with
4770the same length.  If @code{N} is even, then element @code{n} of the
4771transform is equal to@refill
4772@example
4773(1/N) * sum (x @@ exp (2*i*pi*((1:N)-N/2)*(n-1)/N))
4774@end example
4775If @code{N} is odd, then element @code{n} is equal to
4776@example
4777(1/N) * sum (x @@ exp (2*i*pi*((1:N)-(N+1)/2)*(n-1)/N))
4778@end example
4779
4780The method is most efficient when the number of elements in @var{x} is the
4781product of small primes.  For example, a vector with 1021 elements
4782(a prime number) takes roughly 100 times longer to transform than a
4783vector with 1024 elements (a power of 2).  On the other hand, 1152
4784elements (with prime factors of 2 and 3) is almost as fast as
47851024.@refill
4786
4787If @var{x} has integer or real labels, they are taken to be the
4788corresponding abscissae (i.e., frequencies) and are transformed
4789accordingly to form labels for the results vector.  In that case, the
4790label values must be evenly spaced.@refill
4791
4792If @var{x} is a matrix, the transform is computed for each row or
4793column.  By default this is done by column, but you can change it to
4794work by rows by supplying the @code{row} option.@refill
4795
4796For a description of the valid options and their effects, see the
4797@code{fft} function.@refill
4798
4799See also @code{fft}.
4800@end defun
4801
4802@node inv, iram, ifft, Linear Algebra
4803
4804@cindex Inverse, matrix
4805@cindex Matrix inverse
4806@defun inv ( a; opts )
4807The @code{inv} function computes the inverse of a matrix.  This is
4808sometimes useful, but you should be aware that an alternative approach
4809using @code{factor} (or @code{chol}) and @code{solve} is usually more
4810efficient and accurate.  (See below for more details.)@refill
4811
4812The @code{inv} function is implemented simply by calling the
4813@code{solve} function with an identity matrix as the second argument.
4814The argument @var{opts} is optional and is passed as the third argument
4815to @code{solve}.  For example,@refill
4816
4817@example
4818inv (A; @{pos@});
4819@end example
4820
4821@noindent
4822computes the inverse of the positive-definite matrix @code{A}.@refill
4823
4824The matrix inverse is often used to solve systems of linear equations.
4825If @code{Ax=b} is such a system, where @code{A} is a square matrix with
4826full rank, then its solution may be computed as@refill
4827
4828@example
4829x = inv (A) * b;
4830@end example
4831
4832@noindent
4833A more efficient and accurate approach, though, is to use the
4834@code{solve} function as@refill
4835
4836@example
4837x = solve (A; b);
4838@end example
4839
4840The use of @code{solve} is appropriate even when several right-hand
4841sides are to be considered separately.  For example, the code@refill
4842
4843@example
4844x = @{@};
4845A_inv = inv (A);
4846for (b in members (blist))
4847@{
4848  x.(b) = A_inv * blist.(b);
4849@}
4850@end example
4851
4852@noindent
4853would be better written as
4854
4855@example
4856x = @{@};
4857A_fac = factor (A);
4858for (b in members (blist))
4859@{
4860  x.(b) = solve (A_fac; blist.(b));
4861@}
4862@end example
4863
4864See also @code{backsub}, @code{chol}, @code{factor}, and @code{solve}.@refill
4865@end defun
4866
4867@node iram, leastsq, inv, Linear Algebra
4868
4869@cindex Eigenvalues and eigenvectors
4870@cindex Arnoldi method
4871@cindex Lanczos method
4872@cindex ARPACK
4873@defun iram ( n; op_func; b_func; params; options )
4874This function is an interface to the ARPACK routines for solving
4875algebraic eigenvalue problems.  It is based on the implicitly restarted
4876Arnoldi method.  For hermitian problems, this is a Lanczos
4877method.  This code is particularly well suited to large, sparse
4878problems.@refill
4879
4880The @code{iram} function provides almost all of the capability of
4881ARPACK.  However, it is a relatively low-level function and requires
4882very careful use.  Because of it's design, many simple input errors
4883cannot be detected by the function and may well result in incorrect
4884results.  I hope to soon see a high-level function written, perhaps
4885called @code{arnoldi}, that calls @code{iram} but trades off some of its
4886flexibility in exchange for a simplified and less error-prone
4887interface.@refill
4888
4889To use @code{iram} effectively, you will need more information regarding
4890the various solution modes than can be included here.  Please consult
4891the ARPACK users manual.@refill
4892
4893The most general problem solved by @code{iram} is to compute a few
4894eigenvalues (@code{lambda}) and eigenvectors (@code{x}) for@refill
4895
4896@example
4897A * x = M * x * lambda
4898@end example
4899
4900@noindent
4901where @var{A} and @var{B} are real or complex square matrices and
4902@var{M} is hermitian (symmetric when real).  This is a standard
4903eigenvalue problem if @var{M} is the identity matrix; otherwise it is a
4904generalized problem.@refill
4905
4906The argument @var{n} specifies the dimension of the problem.  This
4907should be an integer scalar, or at least able to be cast to one.@refill
4908
4909Rather than providing @var{A} and @var{B} directly, @code{iram} requires
4910input functions that perform certain operations on those matrices.  This
4911allows numerous solution approaches (called ``modes''), which are
4912described in detail below.  The two user-supplied functions are called
4913as@refill
4914
4915@example
4916op_func (v; params)
4917b_func (v; params)
4918@end example
4919
4920The operations required of the @var{op_func} function differ depending
4921on the solution mode.  In the simplest case (mode 1), it is just the
4922matrix-vector multiplication @code{A*v}.  The argument @var{params} is
4923passed unchanged from the @var{params} argument to @code{iram}---it is
4924commonly a table containing the coefficient arrays @var{A} and
4925@var{B}.@refill
4926
4927The requirements for the @var{b_func} function also depend on the
4928solution mode.  It is not used at all for some modes, in which case it
4929may be NULL.  As with @var{op_func}, the @var{params} argument is passed
4930unchanged from the @code{iram} input.@refill
4931
4932The @var{options} argument is a table; its members specify various
4933problem and solution options:@refill
4934
4935@table @code
4936@item mode
4937The integer solution mode, which defaults to 1.
4938
4939@table @code
4940@item 1
4941This is the ``regular'' mode, for standard problems only.  Function
4942@var{op_func} should return @code{A*v}, and @var{b_func} should be NULL.
4943This mode is mostly suited to finding a few of the eigenvalues with
4944largest magnitude.  It may be used with any problem type.@refill
4945
4946@item 2
4947This is the ``regular inverse'' mode for generalized problems.  Function
4948@var{op_func} should return @code{inv(B)*A*v} (conceptually, but you
4949should use @code{factor} and @code{solve} rather than @code{inv}), and
4950@var{b_func} should return @code{B*v}.  This mode may not be used with
4951real, symmetric problems.@refill
4952
4953@item 3
4954This is the ``shift-invert'' mode for standard or generalized problems.
4955Function @var{op_func} should return @code{inv(A-sigma*B)*B*v}
4956(concepturally, but you should use @code{factor} and @code{solve} rather
4957than @code{inv}), and @var{b_func} should return @code{B*v}.  This mode
4958may be used with any problem type.  Convergence is enhanced to
4959eigenvalues that are near the value of @var{sigma}.  For this mode, the
4960@code{which} option refers to the inverted problem, so use ``LM'' to
4961refer to the eigenvalues closest to @var{sigma}.@refill
4962
4963@item 4
4964This is the ``buckling'' mode for generalized problems.  Function
4965@var{op_func} should return @code{inv(A-sigma*B)*A*v} (concepturally,
4966but you should use @code{factor} and @code{solve} rather than
4967@code{inv}), and @var{b_func} should return @code{A*v}.  This mode may
4968only be used for real, symmetric problems.  Convergence is enhanced to
4969eigenvalues that are near the value of @var{sigma}.  For this mode, the
4970@code{which} option refers to the inverted problem, so use ``LM'' to
4971refer to the eigenvalues closest to @var{sigma}.@refill
4972
4973@item 5
4974This is the ``Cayley'' mode for generalized problems.  Function
4975@var{op_func} should return @code{inv(A-sigma*B)*(A+sigma*B)*v}
4976(concepturally, but you should use @code{factor} and @code{solve} rather
4977than @code{inv}), and @var{b_func} should return @code{B*v}.  This mode
4978may only be used for real, symmetric problems.  Convergence is enhanced
4979to eigenvalues that are near the value of @var{sigma}.  For this mode,
4980the @code{which} option refers to the inverted problem, so use ``LM'' to
4981refer to the eigenvalues closest to @var{sigma}.@refill
4982@end table
4983
4984@item bmat
4985A character scalar:  @code{"I"} for standard problems or @code{"G"} for
4986generalized problems.  The default is @code{"I"}.@refill
4987
4988@item which
4989A character scalar that specifies which of the eigenvalues to compute.
4990For other than ``regular'' mode (mode 1), this is with respect to the
4991transformed problem.  For example, with the ``shift-invert'' mode (mode
49923), one usually wants the eigenvectors nearest the shift point.  In the
4993transformed problem, they are the eigenvalues with largest magnitude
4994(@code{"LM"}).  For real, symmetric problems, @var{which} must be one of
4995the following: @code{"LA"} (largest amplitude), @code{"SA"} (smallest
4996amplitude), @code{"LM"} (largest magnitude), @code{"SM"} (smallest
4997magnitude), or @code{"BE"} (both ends of the spectrum).  For
4998non-symmetric or complex problems, @var{which} must be one of these:
4999@code{"LM"} (largest magnitude), @code{"SM"} (smallest magnitude), or
5000@code{"LR"} (largest real), @code{"SA"} (smallest real), @code{"LI"}
5001(largest imaginary), or @code{"SI"} (smallest imaginary).  The default
5002is @code{"LA"} for symmetric problems and @code{"LR"} for the
5003others.@refill
5004
5005@item nev
5006The number of eigenvalues to be computed.  This must be greater than
5007zero and less than @var{n}.  The default is the lesser of 10 and
5008@code{n/2}.  For non-symmetric and complex problems, @var{nev} must be
5009less than @code{n-1}.@refill
5010
5011@item ncv
5012Controls the number of Arnoldi vectors generated at each iteration.  For
5013real, symmetric problems, this must be less than or equal to @var{n},
5014must exceed @var{nev}, and defaults to the lesser of @code{2*nev} and
5015@code{n}.  For real, non-symmetric problems, @var{ncv} must be less than
5016or equal to @var{n}, must exceed @code{nev+1}, and defaults to the
5017lesser of @code{2*nev+1} and @code{n}.  For complex problems, @var{ncv}
5018must be less than or equal to @var{n}, must exceed @var{nev}, and
5019defaults to the lesser of @code{2*nev} and @code{n}.@refill
5020
5021@item mxiter
5022The maximum number of Arnoldi update iterations allowed.  The default is
5023100.@refill
5024
5025@item basis
5026If ``true'' (in the sense of the @code{test} function), then @code{iram}
5027returns, along with its other results, an orthonormal basis for the
5028associated approximate invariant subspace.@refill
5029
5030@item vectors
5031If ``true'' (in the sense of the @code{test} function), then @code{iram}
5032returns the eigenvectors along with its other results.@refill
5033
5034@item tol
5035The stopping criterion.  If @var{tol} is NULL or less than or equal to
5036zero, then machine precision is used.@refill
5037
5038@item resid
5039If present, this is an n-length vector that provides the initial
5040residual vector.  Otherwise, a random initial vector is used.@refill
5041
5042@item shift
5043A real scalar providing the shift point (@var{sigma}) for a spectral
5044transformation.  This is used in modes 3, 4, and 5.  The default is
50450.0.@refill
5046@end table
5047@end defun
5048
5049@node leastsq, mult, iram, Linear Algebra
5050
5051@cindex Least squares
5052@cindex Overdetermined systems
5053@cindex Underdetermined systems
5054@defun leastsq ( A; b )
5055This function solves full-rank overdetermined and underdetermined linear
5056systems using a QR or LQ factorization.  The inputs are the coefficient
5057array @var{A} and the RHS @var{b}.  The return value is the solution
5058array @var{x}.@refill
5059
5060An underdetermined system is one for which @var{A} has fewer rows than
5061columns.  The rank of @var{A} must be equal to the number of rows of
5062@var{A}.  The return value is the minimum norm solution.@refill
5063
5064An overdetermined system is one for which @var{A} has more rows than
5065columns.  This function treats a square @var{A} as if it were an
5066overdetermined system.  The rank of @var{A} must be equal to the number
5067of columns of @var{A}.  The return value is the solution to the least
5068squares problem@refill
5069
5070@example
5071minimize || B - A*X ||
5072@end example
5073
5074See also @code{solve}.
5075@end defun
5076
5077@node mult, solve, leastsq, Linear Algebra
5078
5079@cindex Matrix products
5080@cindex Matrix multiplication
5081@cindex Efficient matrix products
5082@defun mult ( @dots{} )
5083This function multiplies together a series of matrices, performing
5084the multiplications in an order so as to minimize the total number
5085of operations.@refill
5086
5087Only the leftmost non-NULL arguments are used, and at most 10
5088arguments are allowed.  They will be converted to matrices if
5089necessary (and possible), but in a context-free manner.  A scalar
5090becomes a 1x1 matrix, and a vector becomes a matrix with 1 row.  This
5091is in contrast to Algae's multiplication operator, which makes
5092different conversions according to the context.@refill
5093
5094As an example, consider an NxN matrix @code{A} and an N vector
5095@code{b}.  If you give Algae the product @code{A'*A*b}, it first
5096multiplies @code{A'*A} which involves an order of N^3 operations.  But
5097if you do it as @code{A'*(A*b)}, there are only an order of N^2
5098operations.  The difference can be huge!  With this function, you'd do
5099it as @code{mult(A';A;b')}.  (Note that we have to explicitly convert
5100@code{b} to a matrix with the right shape.)@refill
5101@end defun
5102
5103@node solve, ssi, mult, Linear Algebra
5104
5105@cindex Solving linear equations
5106@cindex Linear equations
5107@defun solve ( A; b; opts )
5108This function solves the linear equations @code{A*x=b} for @var{x}.
5109Conceptually it returns @code{inv(A)*b}, except that @code{solve} is
5110generally much more efficient and accurate.  If @var{A} has already been
5111factored by the @code{factor} or @code{chol} functions, then its factors
5112(in the form of a table returned by those functions) may be given in the
5113place of @var{A}.  If the optional argument @var{opts} contains the
5114member ``pos'', then the Cholesky method is used to factor
5115@var{A}.@refill
5116
5117See also @code{backsub}, @code{chol}, and @code{factor}.
5118@end defun
5119
5120@node ssi, svd, solve, Linear Algebra
5121
5122@cindex Subspace iteration
5123@defun ssi ( A; B; V; eps )
5124The @code{ssi} function uses subspace iteration to compute the first few
5125eigenvalues and vectors for a real, symmetric, generalized eigenvalue
5126problem @code{A*v=B*v*w}.  The terms @var{w} and @var{v} are the
5127eigenvalues and eigenvectors, respectively.@refill
5128
5129Subspace iteration is an effective approach for large, sparse problems
5130and for problems for which good estimates of the eigenvectors are
5131available.  Otherwise, it sucks.@refill
5132
5133Both @var{A} and @var{B} must be real, symmetric, non-singular matrices.
5134The matrix @var{V} contains a set of starting vectors, one to a column.
5135A convergence tolerance may be specified with @var{eps}; 1.0E-6 is used
5136if @var{eps} is NULL.  A table is returned, containing the members
5137``values'' and ``vectors''.@refill
5138
5139See also @code{eig}.
5140@end defun
5141
5142@node svd, transform, ssi, Linear Algebra
5143
5144@cindex Singular value decomposition
5145@defun svd ( A; opts )
5146This function computes the singular value decomposition (SVD) of the
5147matrix @var{A}.  In the full case, the SVD is written @code{A=U*S*V'},
5148where @var{S} is a real matrix with the same dimensions as @var{A} and
5149@var{U} and @var{V} are the orthogonal (unitary) left and right singular
5150vectors.  The matrix @var{S} contains the singular values on its
5151diagonal and is zero elsewhere.@refill
5152
5153When @var{A} is not square, one or more rows or columns of @var{S} are
5154known @i{a priori} to be zero.  By default, @code{svd} then returns a
5155``compact'' form of the singular vectors, in which the corresponding
5156columns of @var{U} or @var{V} are not included.  This behavior may be
5157modified by using the @code{full} option, as described below.@refill
5158
5159The argument @var{opts} is an options table; it may contain the members
5160@code{novectors} and @code{full}.  (The values of these members are
5161irrelevant; only their existence is signficant.)  If @var{opts} contains
5162the member @code{novectors}, then only the singular values are computed.
5163If @var{opts} contains only the member @code{full}, then the full
5164singular vectors are computed.@refill
5165
5166The results of @code{svd} are returned in a table.  The member
5167@code{sigma} contains the vector of singular values, sorted in
5168decreasing order.  Unless the @code{novectors} option is specified, the
5169members @code{U} and @code{V} contain the corresponding left and right
5170singular vectors.@refill
5171
5172This function calls the LAPACK routines DGESVD and ZGESVD.@refill
5173@end defun
5174
5175@node transform, , svd, Linear Algebra
5176
5177@defun transform ( A; P )
5178The @code{transform} function performs the linear coordinate
5179transformation @code{P'*A*P}, where @var{A} is a square matrix.  In
5180fact, there are only two differences between the operator expression
5181@code{P'*A*P} and the function expression @code{transform(A;P)}:@refill
5182
5183@itemize @bullet
5184@item
5185The @code{transform} function results in the most appropriate symmetry.
5186For example if @var{A} and @var{P} are both real, and @var{A} is
5187symmetric, then the result is a symmetric matrix.  With the operator
5188expression this would not be the case; the result would be exactly the
5189same (neglecting any roundoff errors) except that it would be marked
5190with general symmetry.@refill
5191
5192@item
5193The @code{transform} function is considerably faster than the operator
5194expression for some matrix combinations.  In particular, it may be two
5195or three times faster when @var{P} is dense and @var{A} is large,
5196sparse, and either hermitian or real symmetric.@refill
5197@end itemize
5198@end defun
5199
5200@node Numerical Analysis, Basic I/O, Linear Algebra, Standard Functions
5201@section Numerical Analysis
5202
5203@ifinfo
5204@menu
5205* brent::	zeros of a nonlinear equation
5206* monte::       Monte Carlo integration
5207* ode4::        ordinary differential equation solver
5208* roots::	roots of a polynomial
5209* spline::	natural cubic splines
5210* trapz::       trapezoidal numerical integration
5211@end menu
5212@end ifinfo
5213
5214@node brent, monte, Numerical Analysis, Numerical Analysis
5215
5216@cindex Root finding
5217@cindex Solving nonlinear equations
5218@cindex Nonlinear equations
5219@defun brent ( f; a; b; tol; param )
5220This function uses Brent's method to find a single root of the function
5221@var{f}; that is, a solution to @code{f(x)=0}.  The ordinates @var{A}
5222and @var{B} must bracket a root, meaning that @code{f(A)*f(B)} must be
5223negative.  If @var{param} is given, it is passed as the second argument
5224to the function @var{f}.@refill
5225@end defun
5226
5227@node monte, ode4, brent, Numerical Analysis
5228
5229@cindex Monte Carlo integration
5230@defun monte ( f; limits; tol )
5231This function uses the Monte Carlo method to integrate a function.  The
5232function values are obtained by calling the function @var{f} with one
5233vector argument.  The matrix @var{limits} describes the rectangular
5234region over which the function is integrated.  It has two columns and as
5235many rows as @var{f} has dimensions.  Each row specifies the extremes of
5236the region for the corresponding dimension.@refill
5237
5238The @var{tol} argument specifies an error tolerance.  (This argument
5239is required: there is no default.)  There is no limit to the number of
5240points chosen; @code{monte} continues to pick points until its one
5241standard deviation error estimate is less than @var{tol}.  Generally,
5242the accuracy increases only as the square root of the number of points
5243evaluated.@refill
5244
5245The Monte Carlo method provides a simple, easy approach for solving
5246(numerically) even complicated, multi-dimensional integrals.  However,
5247it is notoriously inefficient.  Each additional digit of accuracy
5248requires 100 times more effort.@refill
5249
5250Here is a simple example, in which we compute the area of a circle
5251with unit radius.  With @var{domain}, we specify a square centered on
5252the origin within which to integrate.  The number of independent
5253variables in the problem (2 in this case) is determined by the number
5254of rows of @var{domain}.  The function @var{f} takes as its argument a
5255vector of the independent variables and returns the function value at
5256that point.  It will be called repeatedly, with the independent
5257variables spread randomly within the domain.  For this problem,
5258@var{f} returns 1 if the point is inside the circle, and 0
5259otherwise.@refill
5260
5261@example
5262domain = [-1,1; -1,1];
5263f = function (x) @{ return norm(x) < 1; @};
5264monte (f; domain; 0.1)?
5265        3.040
5266monte (f; domain; 0.01)?
5267        3.120
5268monte (f; domain; 0.001)?
5269        3.142
5270@end example
5271
5272As you can see from the results, the third call to @code{monte} gave
5273a more accurate result, but it took 10,000 times the effort used in
5274the first call.@refill
5275
5276By the way, this problem could be solved faster with a one-dimensional
5277integration.  Then again, we already know the answer, don't we?
5278@end defun
5279
5280@node ode4, roots, monte, Numerical Analysis
5281
5282@cindex Ordinary differential equations
5283@cindex Runge-Kutta
5284@cindex Initial value problems
5285@defun ode4 ( f; t0; tf; x0; y; tol; h; s )
5286The @code{ode4} function uses fourth and fifth order Runge-Kutta
5287formulas to solve an initial value problem involving a system of
5288ordinary differential equations.  The function @var{f}, called as
5289@code{f( t; x )}, is expected to return the first derivative of the
5290state vector @var{x} with respect to the independent variable @var{t}.
5291The arguments @var{t0} and @var{tf} are the initial and final values of
5292the independent variable, and @var{x0} is the initial state vector.  The
5293argument @var{y} may be a function, called as @code{y( t; x )}, that
5294returns a vector of output values.  If @var{y} is NULL, the output
5295vector is the state vector itself.@refill
5296
5297The optional argument @var{tol} specifies the desired accuracy; we use
52980.001 if @var{tol} is NULL.  An initial stepsize may be suggested with
5299@var{h}.  The @var{s} argument may be used to provide better control
5300over the accuracy---if @var{s} is not NULL, then a step is accepted if
5301the estimated error in each state, divided by the corresponding term of
5302@var{s}, is not greater than @var{tol}.@refill
5303
5304The return value is a matrix containing the output history.  Each column
5305contains the output from @var{y} for the particular value of the
5306independent variable given by the column label.@refill
5307@end defun
5308
5309@node roots, spline, ode4, Numerical Analysis
5310
5311@cindex Polynomial roots
5312@cindex Roots of a polynomial
5313@defun roots ( c )
5314This function computes the roots of the polynomial having the
5315coefficients given by the vector @var{c}.  If @var{c} has @code{n+1}
5316elements, the equation solved (for @code{x}) is@refill
5317
5318@example
5319c[1]*x^n + c[2]*x^(n-1) + ... + c[n]*x + c[n+1] = 0
5320@end example
5321
5322A vector with zero elements is returned if the equation has no solution
5323(@code{roots(1)}, for example).  NULL is returned if it has an infinite
5324number of solutions (@code{roots(0)}, for example).  Otherwise, the
5325vector returned contains all of the solutions.@refill
5326@end defun
5327
5328@node spline, trapz, roots, Numerical Analysis
5329
5330@cindex Cubic splines
5331@cindex Spline interpolation
5332@cindex Interpolation
5333@defun spline ( a; x )
5334This function computes or evaluates natural cubic spline interpolations
5335for given data.  If called with one argument, @var{a}, a spline for the
5336points in the vector @var{a} is computed.  The elements of @var{a} give
5337the ordinates; the labels of @var{a} give the abscissae.  If @var{a} has
5338no numeric labels, then the natural numbers from one to the length of
5339@var{a} are assumed.  In any case, the vector @var{a} is sorted with
5340respect to its labels; they must be unique.@refill
5341
5342If @code{spline} is called with two arguments, @var{a} and @var{x}, then
5343the spline @var{a} (or a spline interpolation of @var{a}, if @var{a} is
5344not a spline) is evaluated at the abscissa values given by the vector
5345@var{x}.@refill
5346@end defun
5347
5348@node trapz, , spline, Numerical Analysis
5349
5350@cindex Integration
5351@cindex Numerical integration
5352@cindex Trapezoidal integration
5353@defun trapz ( y )
5354This function computes an approximation of the integral of @var{y}
5355using the trapezoidal method.  If @var{y} has numeric labels, they
5356are used as its abscissae; otherwise, unit spacing is assumed.  For
5357the result to make sense, you'll probably want the labels to be in
5358monotonically increasing order.@refill
5359
5360As an example, use @code{trapz} to compute the definite integral of
5361@code{1/x} from 1 to 2.@refill
5362
5363@example
5364x = linspace (1; 2; 11);
5365y = label (1/x; x);
5366trapz (y)
5367        0.6938
5368log(2)-log(1)
5369        0.6931
5370@end example
5371@end defun
5372
5373@node Basic I/O, Entity I/O, Numerical Analysis, Standard Functions
5374@section Basic I/O
5375
5376@ifinfo
5377@menu
5378* close::	close a file
5379* digits::	specify numeric print format
5380* fread::       read a binary file
5381* fprintf::	formatted print to a file
5382* fwrite::      write a binary file
5383* message::	print an error message
5384* print::	print to a file
5385* printf::	formatted print to standard output
5386* read::	read a line from a file
5387* readnum::     read numbers from a file
5388* sprintf::	formatted write to a character scalar
5389* tmp_file::    create a temporary file
5390@end menu
5391@end ifinfo
5392
5393@node close, digits, Basic I/O, Basic I/O
5394
5395@cindex Closing a file
5396@cindex File closing
5397@defun close ( file )
5398The @code{close} function closes the specified file.  The file name
5399@var{file} must be given exactly as it was when the file was opened.
5400(Whitespace is significant.)  Any buffered data is flushed.
5401@end defun
5402
5403@node digits, fread, close, Basic I/O
5404
5405@cindex Digits to print
5406@cindex Print format
5407@cindex Format for printing
5408@defun digits ( n )
5409The @code{digits} function may be used to specify the number of digits
5410that Algae uses when printing real and complex numbers.  This
5411applies to the @code{print} function and to ``printing statements''
5412(those with question mark or newline terminators).  The argument @var{n}
5413specifies the number of digits.  If @var{n} is NULL, no action is
5414taken.@refill
5415
5416The function returns the number of digits being used.  By default,
5417Algae uses 4 digits.@refill
5418
5419Here's an example interaction, with user input preceded by the ``>''
5420prompt:@refill
5421
5422@example
5423> digits ()      # the default
5424        4
5425> acos (-1)      # pi, to 4 significant digits
5426        3.142
5427> digits (20);   # set to 20 digits
5428> acos (-1)      # pi, to 20 digits (but only accurate to 17)
5429        3.1415926535897931000
5430@end example
5431
5432This function simply sets the global variable @code{$digits}, so you
5433can do the same thing by assigning to it directly.@refill
5434
5435See also @code{print}.
5436@end defun
5437
5438@node fread, fprintf, digits, Basic I/O
5439
5440@cindex Binary input
5441@cindex Input, binary
5442@defun fread ( file; length; type )
5443The @code{fread} function reads data from a binary file into a numeric
5444array.  This is a low-level routine, and it requires that you know
5445precisely the format of the data that is being read.  To read Algae's own
5446binary files (those written with @code{put}), see @code{get}.@refill
5447
5448The @var{file} argument (a character scalar) is the file name.  As with
5449any file name, if its first character is an exclamation mark then the
5450rest of the string is given to the shell as a filter.  If @var{file} is
5451NULL, then standard input is read.@refill
5452
5453The @var{length} argument (an integer scalar) gives the number of items
5454to read.  If it's NULL, the entire file is read.  Otherwise, it should
5455be a non-negative integer.  A vector is returned that contains the data
5456that was read.  If @code{fread} reaches the end of the file before
5457having read @var{length} elements, then the vector it returns will
5458contain fewer than @var{length} elements.@refill
5459
5460The @var{type} argument is an optional table; its member's names specify
5461the type of data to read and, implicitly, the type of the returned
5462array.  (The values of this table's members are inconsequential; only
5463their names are important.)  These names may include any of the C
5464language types:
5465@table @code
5466@item char
5467Each is cast to an Algae @code{integer}.
5468@item int
5469Same as an Algae @code{integer}.
5470@item float
5471Each is cast to an Algae @code{real}.
5472@item double
5473Same as an Algae @code{real}.
5474@end table
5475
5476The C language type qualifiers are also accepted in @var{type}:
5477@table @code
5478@item long
5479A qualifier for @code{int} and @code{double} types.  Both are cast
5480to @code{real}.@refill
5481@item short
5482A qualifier for @code{int}.  Casts to @code{integer}.
5483@item signed
5484A qualifier for @code{char} and @code{int}.  Casts to @code{integer}.
5485@item unsigned
5486A qualifier for @code{char} and @code{int}.  An @code{unsigned char}
5487casts to @code{integer}, while an @code{unsigned int} casts to
5488@code{real}.@refill
5489@end table
5490Combinations that are disallowed in C (such as @code{unsigned double})
5491are disallowed here, too.  If @var{type} is NULL or empty, @code{double}
5492is assumed.@refill
5493
5494Besides the C language type qualifiers just described, the following
5495special qualifiers are also accepted:
5496@table @code
5497@item big
5498Specifies the so-called "big endian" byte order.
5499@item little
5500Specifies the so-called "little endian" byte order.
5501@item ieee
5502Specifies the IEEE 754 binary floating point format.
5503@end table
5504@end defun
5505
5506@node fprintf, fwrite, fread, Basic I/O
5507
5508@cindex Printing formatted output
5509@cindex Formatted output
5510@cindex Output, formatted
5511@defun fprintf ( file; format; @dots{} )
5512The @code{fprintf} function prints formatted output to @var{file}.  The
5513@var{format} argument is a character string that contains two types of
5514objects: characters and conversion specifications.  Characters are
5515printed directly; conversion specifications cause the next argument to
5516be formatted and printed.@refill
5517
5518Conversion specifications are introduced using the percent sign
5519@samp{%}.  Although extensions are planned, the conversion
5520specifications are currently identical to those for the ``fprintf''
5521function of the ANSI C language.@refill
5522
5523@cindex Pipes
5524@cindex Exclamation mark
5525@cindex Input filters
5526@cindex Output filters
5527If the first character of @var{file} is an exclamation mark, then the
5528rest of @var{file} is given to the shell as a filter to which the
5529printed output of @code{fprintf} is sent.  For example, the command
5530@code{fprintf("!sort";"a\nc\nb\n");close("!sort");} sends ``a'', ``c'',
5531and ``b'', each on a separate line, to the system's sort function, which
5532then presumably sorts and prints it.  If @var{file} is NULL, stdout is
5533used.@refill
5534
5535See also @code{message}, @code{print}, @code{printf}, @code{sprintf},
5536and @code{put}.@refill
5537@end defun
5538
5539@node fwrite, message, fprintf, Basic I/O
5540
5541@cindex Binary output
5542@cindex Output, binary
5543@defun fwrite ( file; v; type )
5544The @code{fwrite} function writes binary data to a file from a numeric
5545array.  This is a low-level routine, and it requires that you specify
5546precisely the format of the data being written.  To write an entity for
5547use in Algae, you'll probably want to use @code{put} instead.@refill
5548
5549The @var{file} argument (a character scalar) is the file name.  As with
5550any file name, if its first character is an exclamation mark then the
5551rest of the string is given to the shell as a filter.  If @var{file} is
5552NULL, then the data is written to standard output.@refill
5553
5554The data to be written is given in the argument @var{v}, a numeric
5555vector.@refill
5556
5557The @var{type} argument is an optional table; its member's names specify
5558the type of data to write.  (The values of this table's members are
5559inconsequential; only their names are important.)  These names may
5560include any of the C language types and qualifiers, and a few others.
5561See @code{fread} for details.@refill
5562@end defun
5563
5564@node message, print, fwrite, Basic I/O
5565
5566@cindex Error messages
5567@cindex stderr
5568@defun message ( fmt; @dots{} )
5569The @code{message} function is used to write error messages to stderr.
5570Its arguments are exactly like @code{printf}, except that a maximum of
557110 arguments is allowed.  The message written includes the program and
5572file names as well as the line number.@refill
5573
5574See also @code{printf}.
5575@end defun
5576
5577@node print, printf, message, Basic I/O
5578
5579@defun print ( x; file )
5580The @code{print} function prints its argument @var{x} to a file named by
5581@var{file}.  This output goes through the same formatting that
5582Algae uses to print entities to the screen.  In particular, the
5583variable @code{$term_width} controls the width of this output, and the
5584@code{$digits} variable specifies the number of significant digits
5585printed for real and complex numbers.@refill
5586
5587If @var{file} is NULL, then the output is written to stdout.
5588
5589See also @code{digits}, @code{fprintf}, @code{printf}, @code{sprintf},
5590and @code{put}.@refill
5591@end defun
5592
5593@node printf, read, print, Basic I/O
5594
5595@cindex Printing formatted output
5596@cindex Formatted output
5597@cindex Output, formatted
5598@defun printf ( format; @dots{} )
5599The @code{printf} function prints formatted output to stdout.  It is
5600exactly the same as calling @code{fprintf} with NULL as the first
5601argument.@refill
5602
5603See also @code{fprintf}, @code{message}, @code{print}, @code{put}, and
5604@code{sprintf}.@refill
5605@end defun
5606
5607@node read, readnum, printf, Basic I/O
5608
5609@cindex Reading text
5610@cindex Input, character
5611@defun read ( file )
5612This function reads a line of text and returns it as a character string.
5613The argument @var{file} may be a file name or a pipe; see @code{fprintf}
5614for details.  If @var{file} is NULL, the text is read from standard
5615input.@refill
5616
5617When @code{read} reaches the end of file, it returns NULL.@refill
5618
5619See also @code{get} and @code{readnum}.@refill
5620@end defun
5621
5622@node readnum, sprintf, read, Basic I/O
5623
5624@cindex Reading numbers
5625@cindex Input, numeric
5626@defun readnum ( shape; file )
5627This function reads real numbers from a file named @var{file}.  The vector
5628@var{shape} specifies the form of the output.  If @var{shape} is NULL or
5629has zero length, a scalar is returned.  If @var{shape} has length one,
5630then a vector with @code{shape[1]} elements is returned.  If @var{shape}
5631has two elements, then a matrix is returned with @code{shape[1]} rows and
5632@code{shape[2]} columns.@refill
5633
5634The values are read from @var{file}, or from stdin if @var{file} is NULL
5635or not given.  The @samp{#} symbol is special---it and all remaining
5636characters on a line are ignored.  If the end of file is reached before
5637the specified number of values is read, then the result is filled out
5638with zeros.  After a call to @code{readnum}, the number of values actually
5639read is contained in the variable @code{$read}.@refill
5640
5641For example, let's say you have a file called @file{jnk} that contains
5642the following:@refill
5643
5644@example
5645# this line is ignored -- numbers like 1.23 are skipped
5646the first two numbers are 42 and 99.
56473.14 is the next one
5648@end example
5649
5650In the following interaction we read the numbers from the file into a
5651matrix:@refill
5652
5653@example
5654> x = readnum (2,4; "jnk")?
5655        [         42.00        99.00        3.140        0.000 ]
5656        [         0.000        0.000        0.000        0.000 ]
5657> $read?
5658        3
5659> readnum (3; "jnk")?
5660        (        0.000,       0.000,       0.000 )
5661@end example
5662
5663As you can see, anything that doesn't look like a number is simply
5664skipped.  The @code{readnum} function found three numbers and filled in
5665the rest of the matrix with zeros.  The global variable @code{$read} was
5666set to 3 -- the number of values actually read.@refill
5667
5668Subsequent calls to @code{readnum} with the same file name simply
5669continue reading from the last position in the file.  In the last
5670statement of the previous example, no more numbers were found so the
5671vector was filled with zeros.  To read again from the start of the file,
5672you must first close the file with the @code{close} function.@refill
5673
5674The @code{readnum} function recognizes integers and floating point
5675numbers.  A floating point number consists of an optionally signed
5676integer part, a decimal point, a fraction part, an @samp{e} or @samp{E},
5677and an optionally signed integer exponent.  All of the following
5678examples are recognized as numbers: @samp{1}, @samp{-1.2}, @samp{1e2},
5679@samp{-1.e2}, @samp{.1e2}, @samp{-1.2e3}, and @samp{1.2e-3}.@refill
5680
5681Fortran users take note!  A Fortran double precision number such as
5682@samp{1.23D4} will not be read by @code{readnum} as a single number.
5683The character @samp{D} is not recognized as part of a floating point
5684number, so @code{readline} will read this as the two numbers @samp{1.23}
5685and @samp{4}.@refill
5686@end defun
5687
5688@node sprintf, tmp_file, readnum, Basic I/O
5689
5690@defun sprintf ( format; @dots{} )
5691The @code{sprintf} function writes formatted output to a character
5692scalar.  It works the same as @code{printf}, except that the output is
5693returned instead of printed.  For example, @code{x=sprintf("y=%d";1)}
5694puts the string ``y=1'' in the scalar @var{x}.@refill
5695
5696See also @code{fprintf}, @code{printf}, and @code{put}.@refill
5697@end defun
5698
5699@node tmp_file, , sprintf, Basic I/O
5700
5701@cindex Temporary files
5702@defun tmp_file ( )
5703The @code{tmp_file} function creates a temporary file and returns its
5704name.  This file will be deleted automatically when Algae
5705exits.@refill
5706
5707By default, Algae writes temporary files in the directory
5708@file{/tmp}.  You can override that with an environment variable called
5709@code{TMPDIR}.  For example, if you use the Bourne shell and put the
5710lines@refill
5711
5712@example
5713TMPDIR=/usr/tmp
5714export TMPDIR
5715@end example
5716
5717@noindent
5718in your @file{~/.profile} file, then Algae will put its temporary
5719files in the @file{/usr/tmp} directory.@refill
5720
5721This function not only creates the file, but opens it for output.  If
5722you want to read from the temporary file, then you should close it
5723first.  (Of course, you'll need to arrange to get something in it,
5724first.)  Notice that temporary files are not deleted when closed, but
5725only when Algae exits.@refill
5726@end defun
5727
5728@node Entity I/O, Execution, Basic I/O, Standard Functions
5729@section Entity I/O
5730
5731@ifinfo
5732@menu
5733* get::		get an entity from a binary file
5734* getdyn::	get a matrix from a DYNASTY file
5735* getmat::	get a matrix from a MATLAB file
5736* load::	load variables from file
5737* put::		put an entity to a binary file
5738* putdyn::	put a matrix to a DYNASTY file
5739* putmat::	put a matrix to a MATLAB file
5740* save::	save variables to file
5741@end menu
5742@end ifinfo
5743
5744@node get, getdyn, Entity I/O, Entity I/O
5745
5746@cindex Reading entities
5747@defun get ( file )
5748The @code{get} function reads an Algae entity from a binary file named
5749@var{file}.  If no argument is given, standard input is used.  Use this
5750function to read files written with @code{put}.  The file name can
5751specify a pipe; see @code{fprintf} for more details.@refill
5752
5753NULL is returned if an error occurs in reading the file; otherwise
5754@code{get} returns the entity it read.@refill
5755@end defun
5756
5757@node getdyn, getmat, get, Entity I/O
5758
5759@defun getdyn ( fname )
5760This function reads matrices from the DYNASTY file @var{fname}.
5761(DYNASTY is the name of a software package used at Boeing for dynamic
5762analysis.)  A table is returned, containing the matrices as
5763members.@refill
5764
5765The file name can specify a pipe; see @code{fprintf} for more
5766details.@refill
5767@end defun
5768
5769@node getmat, load, getdyn, Entity I/O
5770
5771@cindex MATLAB
5772@defun getmat ( fname )
5773The @code{getmat} function reads matrices from a MATLAB binary file
5774named @var{fname}.  It returns the matrices in a table.@refill
5775
5776The file name can specify a pipe; see @code{fprintf} for more
5777details.@refill
5778
5779Notice that @code{getmat} doesn't assign the matrices to the global
5780symbol table as MATLAB's ``load'' function does.  To do that, you might
5781use something like the following:@refill
5782
5783@example
5784Load = function (fname)
5785@{
5786  local (t; n);
5787  t = getmat (fname);
5788  for (n in members (t))
5789  @{
5790    $$.(n) = t.(n);
5791  @}
5792@};
5793@end example
5794
5795The @code{getmat} function reads the MATLAB v.4 "Level-1 MAT-file"
5796format.  MATLAB can read and write in this format, but its default for
5797writing is now Level-2.  Using the newer format would require us to link
5798to their libraries, meaning that you'd need to actually have MATLAB on
5799that machine.  We'll stick with the older format.@refill
5800
5801One unfortunate consequence of using the older file format is that
5802matrices cannot be written in sparse form.  To get around this, convert
5803the matrix to coordinate form (which is dense) within MATLAB and then
5804change it back to sparse form in Algae with the @code{mksparse}
5805function.@refill
5806
5807See also @code{get}, @code{put}, and @code{putmat}.@refill
5808@end defun
5809
5810@node load, put, getmat, Entity I/O
5811
5812@defun load ( fname )
5813The @code{load} function reads a table from a file named @var{fname} and
5814assigns its members as global variables.  This can be used, for example,
5815to restore an Algae session that was saved with the @code{save}
5816function.@refill
5817
5818If an error occurs in reading the file, @code{load} returns 0; otherwise
5819it returns 1.@refill
5820
5821See also @code{get}, @code{put}, and @code{save}.@refill
5822@end defun
5823
5824@node put, putdyn, load, Entity I/O
5825
5826@cindex Writing entities
5827@defun put ( x; fname )
5828The @code{put} function writes @var{x} to a binary file named
5829@var{fname} (or standard output if @var{fname} is NULL).  This binary
5830file can be read with @code{get}.  The file name can specify a pipe; see
5831@code{fprintf} for more details.@refill
5832
5833NULL is returned if an error occurs in writing the file; otherwise a 1
5834is returned.@refill
5835@end defun
5836
5837@node putdyn, putmat, put, Entity I/O
5838
5839@defun putdyn ( x; fname )
5840This function writes the members of the table @var{x} to a DYNASTY file
5841named @var{fname}.  (DYNASTY is the name of a software package used at
5842Boeing for dynamic analysis.)  The file name may specify a pipe; see
5843@code{fprintf} for more details.@refill
5844
5845The file is not closed when @code{putdyn} finishes, so subsequent writes
5846to the same file will append data to the end of it unless you close it
5847first.  On some machines, this could be used to build a complete DYNASTY
5848file with several different calls to @code{putdyn}.  The disadvantage,
5849though, is that the DYNASTY file format doesn't allow this on all
5850machines.@refill
5851@end defun
5852
5853@node putmat, save, putdyn, Entity I/O
5854
5855@cindex MATLAB
5856@defun putmat ( t; fname )
5857The @code{putmat} function writes a table of matrices @var{t} to a
5858MATLAB binary file named @var{fname}.  The file name can specify a pipe;
5859see @code{fprintf} for more details.@refill
5860
5861NULL is returned if an error occurs in writing the file; otherwise a 1
5862is returned.@refill
5863
5864NULL members in @var{t} are skipped; otherwise each member is converted
5865to a matrix if necessary and then written to the file.@refill
5866
5867The @code{putmat} function writes in the MATLAB v.4 "Level-1 MAT-file"
5868format.  MATLAB can read and write in this format, but its default for
5869writing is now Level-2.  Using the newer format would require us to link
5870to their libraries, meaning that you'd need to actually have MATLAB on
5871that machine.  We'll stick with the older format.@refill
5872
5873One unfortunate consequence of using the older file format is that
5874matrices cannot be written in sparse form.  To get around this, use the
5875@code{exsparse} function to convert the matrix to coordinate form (which
5876is dense) and then change it back to sparse form within MATLAB.@refill
5877
5878See also @code{get}, @code{getmat}, and @code{put}.@refill
5879@end defun
5880
5881@node save, , putmat, Entity I/O
5882
5883@defun save ( fname )
5884The @code{save} function writes all non-NULL global variables as a table
5885to a file named @var{fname}.  This can be used, for example, to save an
5886Algae session that you wish to start again later using the
5887@code{load} function.@refill
5888
5889NULL is returned if an error occurs in writing the file; otherwise
5890@code{save} returns 1.@refill
5891
5892See also @code{get}, @code{load}, and @code{put}.
5893@end defun
5894
5895@node Execution, Special Tools, Entity I/O, Standard Functions
5896@section Execution
5897
5898@ifinfo
5899@menu
5900* autosrc::     define an autosrc function
5901* builtin::	link a new builtin function
5902* cd::          change directory
5903* eval::        evaluate a string as an expression
5904* exception::	raise an exception
5905* exec::        parse and execute a string
5906* exit::        terminate Algae
5907* file::        current file name
5908* get_path::    get a path list
5909* getenv::      get the value of an environment variable
5910* line::        current line number
5911* provide::     provide a feature
5912* require::     require a feature
5913* search_path:: search for a file
5914* source::	read source file (low level)
5915* sources::	read source files, with file name generation
5916* src::         read source file
5917* strip::       strip line and file info from a function
5918* system::	execute a shell command
5919@end menu
5920@end ifinfo
5921
5922@node autosrc, builtin, Execution, Execution
5923
5924@cindex Autosrc functions
5925@defun autosrc ( name; file )
5926This function creates an @dfn{autosrc} function named @var{name}.  When
5927this new function is later called, it replaces itself with a definition
5928that it reads by calling the @code{src} function with the file name
5929@var{file}.  In this way, you can put off reading a function's
5930definition until it is actually called.@refill
5931
5932If @var{file} is @code{NULL}, then @code{autosrc} uses the value of
5933@var{name} for the file name.@refill
5934
5935For example, consider the following code:@refill
5936
5937@example
5938autosrc ("yow");
5939yow ();
5940@end example
5941
5942@noindent
5943The first line defines an autosrc function named @code{yow}.  When
5944@code{yow} is called on the second line, it reads the real definition of
5945@code{yow} by calling @code{src} with the file name @code{"yow"}.  It
5946then calls its replacement (with the same arguments, of course).@refill
5947
5948The current implementation of @code{autosrc} restricts the number of
5949arguments to 10.  (It's an ugly restriction, but if you need that many
5950arguments perhaps you should be using a table, instead.)  A zero
5951returned indicates success.@refill
5952@end defun
5953
5954@node builtin, cd, autosrc, Execution
5955
5956@cindex Dynamic linking
5957@cindex Linking, dynamic
5958@cindex Shared objects
5959@defun builtin ( file; symbol )
5960On machines that support dymamic linking, this function creates a new
5961builtin function by linking to a shared object named by @var{file} and
5962locating the symbol named by @var{symbol}.@refill
5963
5964Suppose you have some old Fortran code that computes your chances of
5965being hit by a comet.  You can write a C wrapper for it, link them as a
5966shared object, use @code{builtin} to attach it, and, voila!, it's a
5967builtin function.@refill
5968
5969Unlike other functions in Algae that deal with files, @code{builtin} does
5970not accept the special ``bang'' type file names.  (These are file names
5971that begin with an exclamation point and are given to the shell as a
5972command.)@refill
5973
5974It isn't hard to create shared objects for @code{builtin}, but currently
5975there's no documentation for it.  Perhaps you can find some code to
5976imitate.@refill
5977@end defun
5978
5979@node cd, eval, builtin, Execution
5980
5981@cindex Directory, changing
5982@cindex Change directory
5983@defun cd ( path )
5984The @code{cd} function changes the current default directory to that
5985specified by the character scalar @var{path}.  If @var{path} is NULL,
5986the directory is changed to that given by the @code{HOME} environment
5987variable.@refill
5988
5989An exception is raised if an error occurs; otherwise, @code{cd} returns
5990the integer 1.@refill
5991@end defun
5992
5993@node eval, exception, cd, Execution
5994
5995@cindex Evaluation
5996@defun eval ( s )
5997The @code{eval} function evaluates the string @var{s} as an expression
5998and returns its value.  Variable references, if any, have global scope.
5999For example, consider the following interaction:@refill
6000
6001@example
6002> x = 0.5;
6003> str = "sin(x)";
6004> eval (str)
6005        0.4794
6006> x = 1.0;
6007> eval (str)
6008        0.8415
6009@end example
6010
6011@noindent
6012Although the value of @code{str} remains @code{"sin(x)"}, the result of
6013@code{eval(str)} changes when the value of @code{x} changes.@refill
6014
6015Unlike its prominent place in some matrix programming languages,
6016@code{eval} is rarely necessary in Algae.  Most examples of its use are
6017rather contrived.  Here's some code which evaluates an expression typed
6018in by the user:@refill
6019
6020@example
6021x = eval (read ("!echo -n \"expression?  \" 1>&2 ; head -1"))
6022@end example
6023
6024One use for @code{eval} that may not be quite so contrived involves
6025building a function within a function---something that you can't do
6026directly in Algae.  Here's an example:@refill
6027
6028@example
6029add_const = function (c)
6030@{
6031  return eval (sprintf ("function (x) @{ return x+%g; @}"; c));
6032@};
6033@end example
6034
6035@noindent
6036This could then be used as follows:@refill
6037
6038@example
6039> ten_more = add_const( 10 );
6040> ten_more(1)?
6041        11
6042@end example
6043
6044Probably the most common mistake made with @code{eval} is giving it a
6045statement instead of an expression.  If that's really what you want to
6046do, use the @code{exec} function instead.@refill
6047
6048Remember, too, that all variable references are at global scope.  For
6049example, the function@refill
6050
6051@example
6052function( a; b ) @{ return eval( "a + b" ); @}
6053@end example
6054
6055@noindent
6056returns the sum of the global variables @code{a} and @code{b}; it
6057completely ignores the function's arguments, as they are local
6058variables.@refill
6059
6060See also @code{exec}.
6061@end defun
6062
6063@node exception, exec, eval, Execution
6064
6065@cindex Exceptions
6066@defun exception ( )
6067This function ``raises an exception'', meaning that Algae makes an error
6068return.  If execution is interactive, control returns to the user.
6069Otherwise, Algae exits.@refill
6070@end defun
6071
6072@node exec, exit, exception, Execution
6073
6074@cindex Evaluation
6075@defun exec ( s )
6076The @code{exec} function causes Algae to parse and execute the
6077Algae statements contained in the character string @var{s}.  Execution
6078begins at global scope, even if @code{exec} is called from a function.
6079It returns a negative integer if an error occurs, and zero otherwise.@refill
6080
6081See also @code{eval} and @code{source}.
6082@end defun
6083
6084@node exit, file, exec, Execution
6085
6086@cindex Terminating Algae
6087@cindex Exiting
6088@defun exit ( status )
6089This function terminates Algae.  The optional argument @var{status}
6090specifies the exit status that Algae returns.  On most computer
6091platforms, the exit status is expected to be a small, positive integer.
6092The @var{status} argument to @code{exit} should be numeric scalar.  If
6093@code{exit} is called with anything else, Algae returns 0 as its exit
6094status.@refill
6095
6096A call to @code{exit} is not mandatory in your Algae programs.  Algae
6097terminates when it reaches the end of its input, returning exit status
60980.  If an error causes Algae to terminate, exit status 1 is returned.@refill
6099@end defun
6100
6101@node file, get_path, exit, Execution
6102
6103@defun file ( )
6104The @code{file} function returns the name of the file from which
6105statements are currently being executed.@refill
6106@end defun
6107
6108@node get_path, getenv, file, Execution
6109
6110@cindex Path lists
6111@defun get_path ( env; def )
6112The @code{get_path} function returns a path list, for use in file
6113searching.  The argument @var{env}, if it isn't NULL, gives the name of
6114an environment variable containing a colon-separated list of paths.  The
6115@var{def} argument gives a default value, in case @var{env} isn't given
6116or doesn't exist.@refill
6117
6118See also @code{search_path} and @code{src}.
6119@end defun
6120
6121@node getenv, line, get_path, Execution
6122
6123@cindex Environment variables
6124@cindex Variables, environment
6125@defun getenv ( ename )
6126The @code{getenv} function returns a character scalar that contains the
6127value of the environment variable named by @var{ename}.  If no such
6128variable exists, NULL is returned.@refill
6129@end defun
6130
6131@node line, provide, getenv, Execution
6132
6133@defun line ( )
6134The @code{line} function returns the line number from which it is
6135called.@refill
6136@end defun
6137
6138@node provide, require, line, Execution
6139
6140@cindex Features
6141@defun provide ( feature )
6142A @dfn{feature} is simply a name that stands for a particular collection
6143of functions or other entities.  A program announces that a feature is
6144present by calling the @code{provide} function with @var{feature}, the
6145name of that feature.  This means that the facilities associated with
6146@var{feature} have been made available for other Algae programs.@refill
6147
6148Programs that require a particular feature can source the appropriate
6149file with the @code{require} function.@refill
6150
6151The argument @var{feature} must be a character scalar.  It is added to
6152the global variable @code{$features} if it is not already present in
6153that vector.  The @code{provide} function returns @var{feature}.@refill
6154@end defun
6155
6156@node require, search_path, provide, Execution
6157
6158@defun require ( feature; filename )
6159A @dfn{feature} is simply a name that stands for a particular collection
6160of functions or other entities.  A program that needs the collection may
6161ensure that they are defined by calling @code{require} with the name of
6162that feature.  The use of named features simplifies the task of
6163determining whether required assignments have been made.@refill
6164
6165The @code{require} function checks for the feature named @var{feature}
6166in the current Algae session; if it isn't present, then @code{require}
6167reads the source file @var{filename} with @code{src}.  If @var{filename}
6168is @code{NULL}, then the value of @var{feature} is used as the file
6169name.@refill
6170
6171Before it finishes, the source file read by @code{require} is expected
6172to call the @code{provide} function, indicating that the desired feature
6173has been provided.  An exception is raised if the source file cannot be
6174read or does not provide the feature named @var{feature}.@refill
6175@end defun
6176
6177@node search_path, source, require, Execution
6178
6179@defun search_path ( fn; suffices; path )
6180The @code{search_path} function searches for a file in the directories
6181named in @var{path}.  The file name begins with the string given by
6182@var{fn}, with one of the suffices given by @var{suffices}.@refill
6183@end defun
6184
6185@node source, sources, search_path, Execution
6186
6187@defun source ( fname )
6188This function causes Algae to parse and execute the file named
6189@var{fname}.  Execution begins at global scope, even if @code{source} is
6190called from a function.  It returns NULL if it has a problem opening
6191@var{fname}, a negative integer if a parse or run time error occurs, and
6192zero otherwise.@refill
6193
6194The file is closed after it is read.@refill
6195
6196See also @code{exec} and @code{sources}.
6197@end defun
6198
6199@node sources, src, source, Execution
6200
6201@defun sources ( fname )
6202The @code{sources} function causes Algae to parse and execute
6203specified files.  The character scalar @var{fname} is passed through
6204sh(1) to ls(1), so file name generation is available and multiple names
6205may be given.  For example,@refill
6206
6207@example
6208sources( "*.A" );
6209@end example
6210
6211@noindent
6212sources all of the files ending with @file{.A} in your working
6213directory.  Although you could use the @code{source} function to do this
6214as@refill
6215
6216@example
6217source( "!cat *.A" );
6218@end example
6219
6220@noindent
6221using @code{sources} is preferable because it maintains the correct file
6222and line information for the interpreter.@refill
6223
6224The ``pipe'' capability normally available to Algae I/O functions is not
6225permitted in @code{sources}.  Command substitution works, though, as
6226demonstrated here:@refill
6227
6228@example
6229sources( "`find $HOME -name '*.A' -print`" );
6230@end example
6231
6232@noindent
6233This example sources every file ending with @file{.A} found in any
6234subdirectory under your home directory.@refill
6235@end defun
6236
6237@node src, strip, sources, Execution
6238
6239@cindex Source files
6240@defun src ( filename )
6241The @code{src} function finds and opens a file of Algae code, executes
6242the statements within it at global scope, and then closes the file.
6243This function, rather than @code{source} or @code{sources}, is intended
6244to be the normal way to source files directly.  Other functions that may
6245be used to source files are @code{require} and @code{autosrc}.@refill
6246
6247To find the file, @code{src} looks first for a file named
6248@file{@var{filename}.A}, that is, it appends @samp{.A} to the name given
6249by the argument @var{filename}.  If a file with that name exists, it is
6250sourced; otherwise, @code{src} looks for a file named @var{filename}
6251with nothing appended, and sources it if it exists.@refill
6252
6253@cindex File searching
6254@cindex Relative file name
6255If @var{filename} is a relative file name, such as @file{foo} or
6256@file{foo/bar.A}, @code{src} searches for the file using the variable
6257@code{$src_path}.  It appends @var{filename} to each of the directories
6258listed in the character vector @code{$src_path} (both with and without
6259the @samp{.A}), and sources the first file it finds whose name matches.
6260The current default directory is tried only if it is specified in
6261@code{$src_path}.@refill
6262
6263@cindex Absolute file name
6264No directory searching is performed if @var{filename} is an absolute
6265file name.  File names that begin with @samp{/}, @samp{./}, @samp{../},
6266or @samp{~/} are absolute.  If the file name begins with @samp{~/}, the
6267tilde is replaced with the value of the @code{HOME} environment
6268variable.@refill
6269
6270@cindex Pipes
6271@cindex Input filters
6272@cindex Output filters
6273A file name that begins with the @samp{!} character is a pipe; the rest
6274of the file name is given as a command line to the shell, the standard
6275output of which is then read by @code{src}.  For example,@refill
6276
6277@example
6278src("!m4 foo.A")
6279@end example
6280
6281@noindent
6282runs the file @file{foo.A} through the @code{m4} macro preprocessor
6283first before @code{src} reads it.@refill
6284
6285@cindex @code{ALGAE_SRC_PATH} environment variable
6286The @code{$src_path}
6287vector is initialized from the environment variable
6288@code{ALGAE_SRC_PATH}, if it exists.  It may be modified in either of
6289the startup files @file{/usr/local/lib/algae/VERSION_NUMBER/algae.A} or
6290@file{$HOME/.algae}.  (@xref{Startup Files}.)@refill
6291
6292The syntax of @code{ALGAE_SRC_PATH} is the same as that of @code{PATH} for
6293the shell; fields are separated by @samp{:}, and @samp{.} is used for
6294the current default directory.  To set @code{ALGAE_SRC_PATH} in the Bourne
6295shell, type something like the following:@refill
6296
6297@example
6298export ALGAE_SRC_PATH
6299ALGAE_SRC_PATH=.:~/algae:/usr/local/lib/algae
6300@end example
6301
6302Execution of the Algae code in @var{filename} begins at global scope.
6303For example, if the source file contains the single statement
6304@code{x=1}, the assignment is made to the global variable @var{x}
6305regardless of whether @code{src} was called from within a function or
6306not.@refill
6307
6308The @code{src} function raises an exception if @var{filename} cannot be
6309found. It returns @code{NULL} if it cannot be opened, a negative integer
6310if a parse or run-time error occurs, and 0 otherwise.@refill
6311@end defun
6312
6313@node strip, system, src, Execution
6314
6315@defun strip ( f )
6316The @code{strip} function removes all file and line information from the
6317given function @var{f}.  The parser ordinarily includes this information
6318so that, for example, run-time error messages can identify the line on
6319which they occurred.  If an error occurs in a function that has been
6320stripped, then the error is attributed instead to the calling
6321expression.@refill
6322
6323This function may also be useful in conjunction with profiling.  Any
6324time spent in a call to a stripped function gets charged to the file and
6325line from which it was called.@refill
6326
6327All members of @var{f} are left unchanged as members of the return value.
6328@end defun
6329
6330@node system, , strip, Execution
6331
6332@defun system ( s )
6333This function passes the string @var{s} to the command processor for
6334execution.  On a UNIX system, for example, the statement
6335@code{system("ls")} lists the files in the current directory.  If the
6336call succeeds, the exit status is returned; otherwise a --1 is returned.@refill
6337@end defun
6338
6339@node Special Tools, Miscellaneous, Execution, Standard Functions
6340@section Special Tools
6341
6342@ifinfo
6343@menu
6344* npsol::	nonlinear optimization
6345* plot::	plot curves
6346* replot::      modify a plot
6347* splot::       plot surfaces
6348* umin::        unconstrained minimization
6349* unplot::      terminate plots
6350@end menu
6351@end ifinfo
6352
6353@node npsol, plot, Special Tools, Special Tools
6354
6355@defun npsol ( objective; start; constraints; options; state )
6356The @code{npsol} function uses a sequential quadratic programming method
6357to minimize a given objective function subject to given constraints.
6358The domain of the objective function is called the ``design space'', and
6359the coordinates of the design space are called ``design
6360variables''.@refill
6361
6362This function uses the NPSOL package of Fortran routines developed and
6363sold by Stanford University.  Your version of Algae might not have the
6364@code{npsol} builtin function; if not, it probably means that you don't
6365have a license for NPSOL or that there was some problem installing it on
6366your computer.@refill
6367
6368The @code{npsol} function may not be called recursively.@refill
6369
6370The @var{objective} argument may be either a function or a table.  If a
6371function, then it's assumed to take one argument, a vector of design
6372variables, and return the value of the objective at that point.  If
6373@var{objective} is a table, it may have the following members:@refill
6374
6375@table @code
6376@item objf
6377A function that returns the value of the objective function for the
6378vector of design variables given as its first argument.  If the member
6379@code{params} exists in @var{objective}, then it is passed as a second
6380argument to @code{objf}.@refill
6381
6382@item objgrd
6383A function that returns the sensitivities of the objective function;
6384that is, the first derivatives with respect to the design variables.
6385Its arguments are the same as for @code{objf}.@refill
6386
6387@item params
6388This member, if it exists, is passed as the second argument to
6389@code{objf} and @code{objgrd}, providing a means for passing additional
6390parameters to those functions.@refill
6391@end table
6392
6393Only the @code{objf} member is required.  If the objective derivatives
6394are not provided, you must ensure that @code{derivative_level} is set
6395accordingly.@refill
6396
6397The @var{start} argument is a vector that specifies the starting
6398point.@refill
6399
6400The @var{constraints} argument is a table that may contain any of all of
6401the following members:@refill
6402
6403@table @code
6404@item side_constraints
6405A matrix that specifies upper and lower constraints on values of the
6406design variables.  This matrix has two columns, the first column giving
6407lower bounds and the second column giving upper bounds.  If this member
6408is not given, then a default is provided using 1.0E10 as ``infinity''.
6409In that case, you should be aware that NPSOL will take these values
6410literally if you also use the ``infinite_bound'' option (in
6411@var{options}) with a value greater than 1.0E10.@refill
6412
6413@item linear_constraints
6414A table that may contain any or all of the following members:@refill
6415
6416@table @code
6417@item coefficients
6418A matrix of the linear constraint coefficients.  The i-th row contains
6419the coefficients for the i-th linear constraint.@refill
6420
6421@item bounds
6422A matrix, like @code{side_constraints}, that gives the upper and lower
6423bounds for the linear constraints.  If not given, defaults are provided
6424as with @code{side_constraints}.@refill
6425@end table
6426
6427@item nonlinear_constraints
6428A table that may contain any or all of the following members:
6429
6430@table @code
6431@item values
6432Either a function that computes the vector of nonlinear constraint
6433function values at the given point, or a table in which member
6434@code{conf} is a function returning the values and @code{congrd} is a
6435function returning the gradients.  The constraint gradients, if
6436provided, should be given as a matrix in which the rows correspond to
6437the constraints and the columns correspond to the design variables.  As
6438in @var{objectives}, a member called @code{params} may also be
6439included.@refill
6440
6441@item bounds
6442A matrix, like @code{side_constraints}, that gives the upper and lower
6443bounds for the nonlinear constraints.  If not given, defaults are
6444provided as with @code{side_constraints}.@refill
6445@end table
6446
6447If the constraint derivatives are not provided, you must ensure that
6448@code{derivative_level} is set accordingly.@refill
6449
6450The @var{options} argument is a table that may contain any of the valid
6451NPSOL options.  For example, @code{@{ hessian = "yes" @}} specifies the
6452corresponding option in NPSOL.  Use an underscore instead of blanks
6453between words, as in @code{@{ major_print_level = 1 @}}.  The valid
6454options are:@refill
6455
6456@table @code
6457@item central_difference_interval
6458If the algorithm switches to central differences because the
6459forward-difference approximation is not sufficiently accurate, this value
6460is used as the difference interval for every variable.@refill
6461
6462@item cold_start
6463@itemx warm_start
6464These flags control the specification of the initial working set in
6465both the procedure for finding a feasible point for the linear
6466constraints and bounds, and in the first QP subproblem thereafter.  With
6467a @code{cold_start}, the first working set is chosen by @code{npsol}
6468based on the values of the variables and constraints at the initial
6469point.  Broadly speaking, the initial working set will include equality
6470constraints and bounds or inequality constraints that violate or
6471``nearly'' satisfy their bounds within @code{crash_tolerance}.  With a
6472@code{warm_start}, the user must provide the @code{state} table.  A warm
6473start will be advantageous if a good estimate of the initial working set
6474is available---for example, when @code{npsol} is called repeatedly to
6475solve related problems.@refill
6476
6477@item crash_tolerance
6478This value is used in conjunction with the optional parameter
6479@code{cold_start}, which is the default.  When making a cold start, the
6480QP algorithm in @code{npsol} must select an initial working set.  The
6481initial working set will include, if possible, bounds or general
6482inequality constraints that lie within @code{crash_tolerance} of their
6483bounds.  The default value is 0.01.  If @code{crash_tolerance} is less
6484than zero or greater than one, the default value is used.@refill
6485
6486@item derivative_level
6487This value indicates which objective and constraint derivatives are
6488provided by the user.  The choices are as follows:
6489
6490@table @code
6491@item 0
6492Neither objective nor constraint derivatives are provided.@refill
6493
6494@item 1
6495The objective derivatives are provided by the @code{objgrd} function in
6496argument @var{objective}.  Constraint derivatives are not
6497provided.@refill
6498
6499@item 2
6500The nonlinear constraint derivatives are provided by the @code{congrd}
6501function in argument @var{constraints}.  Objective derivatives are not
6502provided.@refill
6503
6504@item 3
6505The objective derivatives are provided by the @code{objgrd} function in
6506argument @var{objective}, and the nonlinear constraint derivatives are
6507provided by the @code{congrd} function in argument @var{constraints}.@refill
6508@end table
6509
6510The value 3 is the default, and should be used whenever possible, since
6511@code{npsol} is more reliable and will usually be more efficient when
6512all derivatives are exact.@refill
6513
6514If @code{derivative_level} is 0 or 2, @code{npsol} will estimate the
6515objective gradients using finite differences.  The computation of
6516finite-difference approximations usually increases the total run time,
6517since a call to the objective function is required for each constraint.
6518Furthermore, less accuracy can be attained in the solution.@refill
6519
6520If @code{derivative_level} is 0 or 1, @code{npsol} will approximate the
6521constraint gradients.  One call to the constraint function is required
6522for each variable.  At times, central differences are used rather than
6523forward differences, in which case twice as many calls to the objective
6524and constraint functions are needed.  The switch to central differences
6525is not under the user's control.@refill
6526
6527@item difference_interval
6528This value defines an interval used to estimate gradients by finite
6529differences in the following circumstances: (1) for verifying the
6530objective and constraint gradients, and (2) for estimating the objective
6531or constraint derivatives.  If a difference interval is not specified by
6532the user, a finite difference interval will be computed automatically
6533for each variable by a procedure that requires up to six calls of the
6534objective and constraint functions for each component.  This option is
6535recommended if the function is badly scaled or the user wishes to have
6536@code{npsol} determine constant elements in the objective and constraint
6537gradients.@refill
6538
6539@item feasibility_tolerance
6540This value defines the maximum acceptable absolute violations in linear
6541and nonlinear constraints at a ``feasible'' point; i.e., a constraint is
6542considered satisfied if its violation does not exceed this value.  The
6543default value is the square root of machine precision.@refill
6544
6545@item function_precision
6546This value is intended to be a measure of the accuracy with which the
6547objective and constraint functions can be computed.  It acts as a
6548relative precision when the magnitude is large, and as an absolute
6549precision when the magnitude is small.  For example, if the objective
6550function is typically on the order of 1000 and the first 6 digits are
6551known to be correct, then @code{function_precision} should be set to
65521.0E--6. In contrast, if the objective function is typically on the
6553order of 1.0E--4 and the first 6 digits are known to be correct, then
6554@code{function_precision} should be set to 1.0E--10.  The choice of
6555@code{function_precision} can be quite complicated for badly scaled
6556problems.  The default value is machine precision raised to the 0.9
6557power; this is appropriate for most simple functions that are computed
6558with full accuracy.  However, when the accuracy of the computed function
6559values is known to be significantly worse than full precision, then
6560@code{function_precision} should be large enough that @code{npsol} will
6561not attempt to distinguish between function values that differ by less
6562than the error inherent in the calculation.@refill
6563
6564@item hessian
6565This option must be either @code{"yes"} or @code{"no"}.  (The default is
6566@code{"no"}).  This option controls the contents of the @code{R} matrix
6567in @var{state}.  The user should set @code{hessian} to @code{"yes"} if
6568the @code{state} table returned is to be used for a subsequent warm
6569start.@refill
6570
6571@item infinite_bound_size
6572If this value is greater than zero, it defines the ``infinite'' bound
6573in the definition of the problem constraints.  Any upper bound greater
6574than or equal to this value will be regarded as positive infinity.  Any
6575lower bound less than or equal to the negative of this value will be
6576regarded as negative infinity.  The default value is 1.0E10.@refill
6577
6578@item infinite_step_size
6579This value specifies the magnitude of the change in variables that is
6580treated as a step to an unbounded solution.  If the change in any
6581variable during an iteration would exceed the value of
6582@code{infinite_step_size}, the objective function is considered to be
6583unbounded below in the feasible region.  The default is the greater of
6584@code{infinite_bound_size} and 1.0E10.@refill
6585
6586@item iteration_limit
6587This value specifies the maximum number of major iterations allowed
6588before termination.@refill
6589
6590@item linear_feasibility_tolerance
6591@itemx nonlinear_feasibility_tolerance
6592These values define the maximum acceptable absolute violations in linear
6593and nonlinear constraints at a ``feasible'' point.  A constraint is
6594considered satisfied if its violation does not exceed this value.  The
6595default value for both options is the square root of machine
6596precision.@refill
6597
6598On entry to @code{npsol}, an iterative procedure is executed in order to
6599find a point that satisfies the linear constraints and bounds on the
6600variables to within @code{linear_feasibility_tolerance}.  All subsequent
6601iterates will satisfy the linear constraints to within the same
6602tolerance, unless this value is comparable to the finite difference
6603interval.@refill
6604
6605For nonlinear constraints, @code{nonlinear_feasibility_tolerance}
6606defines the largest constraint violation that is acceptable at an
6607optimal point.  Since nonlinear constraints are generally not satisfied
6608until the final iterate, this value acts as a partial termination
6609criterion for the iterative sequence.@refill
6610
6611These tolerances should reflect the precision of the corresponding
6612constraints.  for example, if the variables and the coefficients in the
6613linear constraints are of order unity, and the latter are correct to
6614about 6 decimal digits, it would be appropriate to specify
6615@code{linear_feasibility_tolerance} as 1.0E--6.@refill
6616
6617@item linesearch_tolerance
6618This value controls the accuracy with which a step taken during each
6619iteration approximates a minimum of the merit function along the search
6620direction.  The smaller the value, the more accurate the line search.
6621The default value is 0.9; it requests an inaccurate search that is
6622appropriate for most problems, particularly those with any nonlinear
6623constraints.@refill
6624
6625If there are non nonlinear constraints, a more accurate search may be
6626appropriate when it is desirable to reduce the number of major
6627iterations---for example, if the objective function is cheap to evaluate
6628or if the gradients are not specified.@refill
6629
6630@item list
6631If this flag is given, all of the options and their values are
6632printed.@refill
6633
6634@item print_level
6635This value controls the amount of printed output produced by the major
6636iterations of @code{npsol}.  The levels are as follows:@refill
6637
6638@table @code
6639@item 0
6640No output.  This is the default.
6641
6642@item 1
6643The final solution only.
6644
6645@item 5
6646One line of output for each major iteration, but no final
6647solution.@refill
6648
6649@item 10
6650The final solution and one line of output for each iteration.@refill
6651
6652@item 20
6653At each major iteration, the objective function, the Euclidean norm of
6654the nonlinear constraint violations, the value of the nonlinear
6655constraints, the values of the linear constraints, and the current
6656values of the variables.@refill
6657@end table
6658
6659@item minor_iteration_limit
6660This value specifies the maximum number of iterations for the optimality
6661phase of each QP subproblem.@refill
6662
6663@item minor_print_level
6664This value controls the amount of printout produced by the minor
6665iterations of @code{npsol}.  The levels are as follows:@refill
6666
6667@table @code
6668@item 0
6669No output.  This is the default.@refill
6670
6671@item 1
6672The final QP solution.
6673
6674@item 5
6675One line of output for each minor iteration, but no final QP
6676solution.@refill
6677
6678@item 10
6679The final QP solution and one line of output for each minor iteration.
6680
6681@item 20
6682At each minor iteration, the current estimates of the QP multipliers,
6683the current estimate of the QP search direction, the QP constraint
6684values, and the status of each QP constraint.@refill
6685@end table
6686
6687@item optimality_tolerance
6688This value specifies the accuracy to which the user wishes the final
6689iterate to approximate a solution of the problem.  Broadly speaking, it
6690indicates the number of correct figures desired in the objective
6691function at the solution.  For example, if @code{optimality_tolerance}
6692is 1.0E--6 and @code{npsol} terminates successfully, the final value of
6693the objective function should have approximately 6 correct figures.  The
6694@code{npsol} function will terminate successfully if the iterative
6695sequence is judged to have converged and the final point satisfies the
6696first-order optimality conditions.@refill
6697
6698@item verify_level
6699This value refers to finite-difference checks on the gradients computed
6700by the user function @code{objgrd} and @code{congrd}.  It may take on
6701one of the following values:@refill
6702
6703@table @code
6704@item -1
6705No checks are made.
6706
6707@item 0
6708Perform only a very inexpensive check, involving one call to the
6709objective function and one call to the constraint function.@refill
6710
6711@item 1
6712Perform a reliable but expensive check on the objective
6713gradients.@refill
6714
6715@item 2
6716Perform a reliable but expensive check on the constraint
6717gradients.@refill
6718
6719@item 3
6720Perform reliable but expensive checks on both the objective and the
6721constraint gradients.@refill
6722@end table
6723
6724@noindent
6725These checks are recommended whenever a new function routine is being
6726developed.@refill
6727@end table
6728
6729The @var{state} argument is used only when the NPSOL ``warm_start''
6730option is requested.  It may be obtained from the return of a previous
6731call to @code{npsol}.  Its members are:@refill
6732
6733@table @code
6734@item ISTATE
6735A vector describing the status of the constraints.
6736
6737@item CLAMDA
6738The Lagrange multiplier estimates for the nonlinear constraints.
6739
6740@item R
6741The factored Hessian of the Lagrangian function.
6742@end table
6743
6744The @code{npsol} function returns a table containing the following
6745members:@refill
6746
6747@table @code
6748@item objective
6749The value of the objective function at the final iterate.
6750
6751@item solution
6752The solution vector (or final estimate) for the problem.
6753
6754@item inform
6755The INFORM value (success/error indicator) returned by NPSOL.  The
6756possibilities are:@refill
6757
6758@table @code
6759@item 0
6760The iterates have converged to a point that satisfies the first-order
6761optimality conditions to the accuracy requested by the optional
6762parameter @code{optimality_tolerance}, i.e., the projected gradient and
6763active constraint residuals are negligible.  (Success.)@refill
6764
6765@item 1
6766The final iterate satisfies the first-order optimality conditions to the
6767accuracy requested, but the sequence of iterates has not yet converged.
6768NPSOL was terminated because no further improvement could be made in the
6769merit function.  (Probable success.)@refill
6770
6771@item 2
6772No feasible point could be found for the linear constraints and bounds.
6773The problem has no feasible solution.@refill
6774
6775@item 3
6776No feasible point could be found for the nonlinear constraints.  The
6777problem may have no feasible solution.@refill
6778
6779@item 4
6780The limiting number of iterations, determined by the optional parameter
6781@code{major_iteration_limit}, has been reached.@refill
6782
6783@item 6
6784The current point does not satisfy the first-order optimality
6785conditions, and no improved point for the merit function could be found
6786during the final line search.@refill
6787
6788@item 7
6789The user-provided derivatives of the objective function and/or nonlinear
6790constraints appear to be incorrect.@refill
6791
6792@item 9
6793An input parameter is invalid.
6794@end table
6795
6796@item iter
6797The number of major iterations performed.
6798
6799@item state
6800The @code{state} table described above.
6801@end table
6802@end table
6803@end defun
6804
6805@node plot, replot, npsol, Special Tools
6806
6807@defun plot ( @dots{} )
6808The @code{plot}, @code{splot}, @code{replot}, and @code{unplot}
6809functions provide an interface to the gnuplot program for plotting
6810data.  Use @code{plot} for plotting lines in two or three dimensions;
6811@code{splot} is for plotting surfaces in three dimensions.@refill
6812
6813To use these plotting functions effectively, you will probably need some
6814familiarity with the gnuplot commands.  For example, to add a title to an
6815existing plot, you'd type something like @code{replot("set title 'Good
6816Stuff'")}.  Read the gnuplot manual or its on-line help for more
6817information.@refill
6818
6819The @code{plot} function accepts as many as three arguments.  If either
6820or both of the first two arguments are (or can be converted to)
6821character vectors, then their elements are sent, each on a separate
6822line, to gnuplot as commands.  For example, @code{plot("set term X11")}
6823causes gnuplot to generate X11 output.  Even commands that request
6824information from gnuplot, like @code{plot("show term")} are acceptable
6825(although you might temporarily lose sight of Algae's prompt).  Don't use
6826the ``exit'' or ``quit'' commands of gnuplot---they cause gnuplot to
6827exit without Algae knowing about it.@refill
6828
6829If more than one argument is given to @code{plot} and the last one is an
6830integer scalar, then it is taken to be an identifier for the plot
6831process.  This allows you to have more than one plot open at a time.  If
6832no identifier is given, then the active plot is killed and replaced by a
6833new one with the same identifier.  The ``active'' plot is the one last
6834referenced, or 1 if there are no plots open.  The @code{replot} function
6835may be used to modify an open plot.@refill
6836
6837Any other arguments given to @code{plot} are taken to be data to be
6838plotted.  Vectors are plotted using their element values as ordinates
6839and their labels for the abscissae.  Matrices with 2 columns are plotted
6840using the second column for ordinates and the first column for
6841abscissae.  A matrix with 3 columns is plotted as a curve in three
6842dimensions, with the third column specifying the ordinates.  Surface
6843plots are obtained using the @code{splot} function.@refill
6844
6845If the data given to @code{plot} is a vector, but has no labels, then
6846the element indices are used instead of the labels.@refill
6847
6848Multiple curves may be shown on the same plot, either by giving
6849@code{plot} two data arguments or (better yet) supplying the data in a
6850table.  When data is given in a table (even if it contains only one
6851member), the member name is used in the plot legend.  Otherwise,
6852@code{plot} uses the names ``y_1'' and ``y_2''.@refill
6853
6854If the data is given in a table, any members that are tables themselves
6855are given to gnuplot in a single data file.  This means that the same
6856line and point type is used.  For example, if @code{x} and @code{y} are
6857vectors to be plotted, then @code{plot(@{x;y@})} plots the two, each
6858with a different line and point type and described by name in the
6859legend.  On the other hand, @code{plot(@{z=@{x;y@}@})} plots them with
6860the same line and point type and names the combination ``z'' in the
6861legend.@refill
6862
6863If @code{plot} is called with no arguments, it returns a vector of the
6864open plot identifiers.  This vector is sorted from most to least
6865recently referenced, so the ``active'' plot is first.@refill
6866
6867Here's an example that simulates the Van der Pol system and plots the
6868results:@refill
6869
6870@example
6871xdot = function( t; x ) @{
6872    return x[1]*(1-x[2]^2)-x[2], x[1];
6873@}
6874x = ode4( xdot; 0; 20; 0,.25 );
6875plot( "set data style lines"; @{ x1=x[1;]; x2=x[2;] @} );
6876@end example
6877
6878See also @code{splot}, @code{replot}, and @code{unplot}.
6879@end defun
6880
6881@node replot, splot, plot, Special Tools
6882
6883@defun replot ( @dots{} )
6884The @code{replot} function is used to modify or redisplay plots created
6885with either the @code{plot} or @code{splot} functions.  It takes at most
68862 arguments.  If the first argument has character type, it is passed to
6887gnuplot as commands.@refill
6888
6889The last argument is the optional plot identifier.  If not given, the
6890active plot is used by default.@refill
6891
6892See also @code{plot}, @code{splot}, and @code{unplot}.
6893@end defun
6894
6895@node splot, umin, replot, Special Tools
6896
6897@defun splot ( @dots{} )
6898The @code{splot} function is used to plot surfaces in three dimensions.
6899Except for the form of the data, its input is identical to that of the
6900@code{plot} function.  The data is specifed as a matrix of ordinates.
6901The labels of the matrix, or the corresponding indices if the labels
6902don't exist, are used for the abscissae.@refill
6903
6904See also @code{plot}, @code{replot}, and @code{unplot}.
6905@end defun
6906
6907@node umin, unplot, splot, Special Tools
6908
6909@defun umin ( objective; start; options )
6910The @code{umin} function performs unconstrained minimization using the
6911Nelder-Mead direct search method.  It does not have the features or
6912sophistication of @code{npsol}, but it works well for some
6913cases---particularly when the objective surface is not smooth.@refill
6914
6915The @var{objective} argument is a function that takes one or two
6916arguments and returns the value of the objective at that point.  The
6917first argument is a vector of design variables.  The second
6918argument, which is optional, is passed unchanged from the @var{params}
6919member of the @var{options} argument to @code{umin} itself.@refill
6920
6921The @var{start} argument is an integer or real vector that specifies the
6922starting point.@refill
6923
6924The @var{options} augument may be either NULL or a table containing
6925convergence and other specifications.  The meaningful options are:@refill
6926
6927@table @code
6928@item bound
6929The minimum value permitted for the objective function.  The default is
6930--1e32.@refill
6931
6932@item display
6933A function called at each ``successful'' iteration with the current design
6934point as its only argument.  This may be used, for example, to plot the
6935design as it changes.@refill
6936
6937@item evals
6938The maximum number of objective function evaluations permitted.  The
6939default value is 1000.@refill
6940
6941@item iter
6942The maximum number of iterations permitted.  The default value is
6943100.@refill
6944
6945@item params
6946The value of this member is passed as the second argument to the
6947objective function.@refill
6948
6949@item right
6950If this member exists, then the initial simplex has right angles.  By
6951default, the initial simplex has sides of equal length.@refill
6952
6953@item size
6954The initial size of the simplex.  By default, this is the greater of 1
6955and the infinity norm of the starting vector.@refill
6956
6957@item tol
6958The relative size of the simplex, below which the iteration is taken to
6959have converged.  The tolerance is 1e--6 by default.@refill
6960
6961@item verbose
6962If this member exists, then information is printed at each ``successful''
6963iteration.@refill
6964@end table
6965
6966The return value from @code{umin} is a table with the following
6967members:@refill
6968
6969@table @code
6970@item evals
6971The number of objective function evaluations.@refill
6972
6973@item inform
6974A return code specifying success or failure:@refill
6975
6976@table @code
6977@item 0
6978success
6979
6980@item 1
6981failure, objective bound reached
6982
6983@item 2
6984failure, function evaluation limit exceeded
6985
6986@item 3
6987failure, iteration limit exceeded
6988@end table
6989
6990@item iter
6991The number of iterations performed.@refill
6992
6993@item msg
6994A message corresponding to the inform code.@refill
6995
6996@item obj
6997The final objective value.@refill
6998
6999@item sol
7000The final design point.@refill
7001@end table
7002
7003This code is based on @code{nmsmax}, a MATLAB function by Nick
7004Higham.@refill
7005
7006See also @code{npsol}.
7007@end defun
7008
7009@node unplot, , umin, Special Tools
7010
7011@defun unplot ( id )
7012The @code{unplot} function is used to terminate plots created with the
7013@code{plot} or @code{splot} functions.  The integer scalar or vector
7014argument @var{id} specifies the identifiers of the plots to be
7015terminated.  If no @var{id} is given, the active plot is terminated.
7016You can terminate all open plots with @code{unplot(plot())}.@refill
7017
7018See also @code{plot}, @code{replot}, and @code{splot}.
7019@end defun
7020
7021@node Miscellaneous, , Special Tools, Standard Functions
7022@section Miscellaneous
7023
7024@ifinfo
7025@menu
7026* all::         test all elements
7027* atof::        convert string to number
7028* char::        vector to character string
7029* class::	entity class
7030* equal::	test for equality
7031* members::	members of a table
7032* info::        documentation browsing system
7033* prof::        summarize profiler output
7034* show::	show entity information
7035* split::       split string into fields
7036* string::      convert to character type
7037* substr::      return a substring
7038* test::	truth test
7039* time::        user time
7040* tolower::     convert strings to lower case
7041* toupper::     convert strings to upper case
7042* what::	list functions
7043* who::		list variables
7044@end menu
7045@end ifinfo
7046
7047@node all, atof, Miscellaneous, Miscellaneous
7048
7049@defun all ( x )
7050The @code{all} function evaluates the ``truth'' of its argument @var{x}
7051in the same way that the function @code{test} does, except that vectors
7052and matrices are ``true'' only if all of their elements are ``true''.
7053For example, @code{all(1,0)} returns 0 while @code{test(1,0)} returns
70541.  If @var{x} has no elements, @code{all} returns 0.@refill
7055
7056See also @code{test} and @code{equal}.
7057@end defun
7058
7059@node atof, char, all, Miscellaneous
7060
7061@defun atof ( s )
7062The @code{atof} function converts character strings to real numbers.
7063The argument @var{s} may be a scalar, vector, or matrix.  The function
7064reads only up to the first unrecognized character of each string, and
7065ignores anything that remains.  If the first character of a string is
7066unrecognized, then the value is taken to be zero.@refill
7067@end defun
7068
7069@node char, class, atof, Miscellaneous
7070
7071@defun char ( v )
7072The @code{char} function converts the vector @var{v} into a character
7073string; each element of @var{v} contributes a single character according
7074to its ASCII value.  For example, @code{char(65,66,67)} returns the
7075string @code{"ABC"}.@refill
7076
7077If an element of @var{v} is less than 0 or greater than 255, then it
7078will ``wrap'' (modulo 256).  Thus @code{char(65)} and
7079@code{char(65+256)} both return the string @code{"A"}.@refill
7080
7081Algae's character strings are terminated with a NUL (0) character.  For
7082the @code{char} function, that means that if an element of @var{v} is
7083zero (or a multiple of 256) then the string is terminated at that
7084point.  For example, @code{char(65,0,66)} yields the string
7085@code{"A"}.@refill
7086@end defun
7087
7088@node class, equal, char, Miscellaneous
7089
7090@defun class ( x )
7091The @code{class} function returns a character string (such as ``scalar''
7092or ``table'') that describes the class of @var{x}.@refill
7093@end defun
7094
7095@node equal, members, class, Miscellaneous
7096
7097@defun equal ( a; b )
7098This function tests @var{a} and @var{b} for equality.  For vectors and
7099matrices, it returns true (1) only if every pair of corresponding
7100elements is equal, and false (0) otherwise.  For all other classes, this
7101function returns the same value as the expression @code{a==b}
7102would.@refill
7103
7104See also @code{test}.
7105@end defun
7106
7107@node members, info, equal, Miscellaneous
7108
7109@defun members ( e )
7110This function returns a vector containing the names of the members of
7111@var{e}.@refill
7112@end defun
7113
7114@node info, prof, members, Miscellaneous
7115
7116@defun info ( topic )
7117This function starts up an interactive browser for Algae's
7118documentation.  The optional argument @var{topic} (a character scalar)
7119takes you directly to that topic.  For example, @code{info("sort")}
7120takes you directly to the description of the @code{sort}
7121function.@refill
7122
7123If possible, @code{info} uses an X-based html browser (like netscape
7124or mosaic).  Otherwise, a character-based html browser (like lynx)
7125will be tried.  As a final resort, the GNU Info browser is called.@refill
7126
7127The names of the available browsers are assigned by the startup code
7128(@pxref{Startup Files}) as members @code{xhtml}, @code{html}, and
7129@code{info} of the global table @code{$programs}.  To prevent
7130Algae from using a particular browser, simply set the
7131appropriate member of @code{$programs} to a zero-length string.  If
7132you prefer to use Info, for example, you could simply put the
7133line@refill
7134
7135@example
7136$programs.xhtml = $programs.html = "";
7137@end example
7138
7139in your @file{.algae} file.
7140@end defun
7141
7142@node prof, show, info, Miscellaneous
7143
7144@cindex Execution profiling
7145@cindex Profiling
7146@cindex algae.out
7147@defun prof ( infile; outfile; threshold )
7148The @code{prof} function reads an @file{algae.out} file produced by
7149Algae's execution profiler (the @samp{-p} option), and summarizes
7150it by file and by line number.  The @var{infile} argument specifies the
7151file name.  @var{outfile} specifies the output file; if it's NULL,
7152stdout is used.@refill
7153
7154The @var{threshold} argument may be used to truncate the summary
7155listings.  The truncation occurs after enough entries have been printed
7156to account for @var{threshold} percent of the total number of hits.  If
7157@var{threshold} is NULL, no truncation is performed.@refill
7158
7159Below is an example of @code{prof} output, obtained with the command
7160@code{prof("algae.out";;50);}.@refill
7161
7162@example
7163Algae execution profile listing.
7164
7165628 total hits
7166
7167--- by file ---
7168
7169      hits   % hits    cum %   file
7170       201    32.01    32.01   lqrtest.A
7171       127    20.22    52.23   /usr/local/lib/algae/ode.A
7172
7173--- by line ---
7174
7175      hits   % hits    cum %   line   file
7176       130    20.70    20.70     88   lqrtest.A
7177        42     6.69    27.39      1   /usr/local/lib/algae/plot.A
7178        40     6.37    33.76     38   lqrtest.A
7179        21     3.34    37.10      1   /usr/local/lib/algae/ode.A
7180        17     2.71    39.81     44   /usr/local/lib/algae/ode.A
7181        15     2.39    42.20     42   /usr/local/lib/algae/ode.A
7182        15     2.39    44.59     41   /usr/local/lib/algae/ode.A
7183        14     2.23    46.82      1   /usr/local/lib/algae/ode4.A
7184        12     1.91    48.73      1   /usr/local/lib/algae/spline.A
7185        10     1.59    50.32      1   lqrtest.A
7186@end example
7187
7188First, notice that the number of hits counted in this example was only
7189628.  Four digits of precision in the statistics are clearly unjustifed
7190with such a small sample.  The first column reports the number of
7191profiler hits counted toward each particular file or line number.  The
7192second column restates that as a percentage of the total number of hits.
7193The third column gives the cumulative percentage.@refill
7194
7195All profiler hits that occur while Algae is parsing a file are
7196counted toward its first line.  This is normally insignificant compared
7197to execution, but it explains why line 1 shows up so often in the ``by
7198line'' report in the example above.@refill
7199
7200No files are closed in @code{prof}.  Normally, this means that you must
7201close them yourself if @code{prof} is to be called more than
7202once.@refill
7203@end defun
7204
7205@node show, split, prof, Miscellaneous
7206
7207@defun show ( e )
7208This function prints information about the entity @var{e} and its
7209members.@refill
7210@end defun
7211
7212@node split, string, show, Miscellaneous
7213
7214@cindex Splitting into tokens
7215@cindex Tokens, splitting
7216@defun split ( s; w )
7217The @code{split} function takes a character scalar argument @var{s},
7218splits it into tokens, and returns the tokens in a character vector.
7219Each token is delimited by one or more characters from @var{w}.  For
7220example, @code{split("/bin:/usr/bin";":")} returns the vector@refill
7221
7222@example
7223(  "/bin"    , "/usr/bin" )
7224@end example
7225
7226If @var{w} is NULL, the string @code{" \t\n"} is used.  Thus
7227@code{split("This is a test.")} returns the vector@refill
7228
7229@example
7230(  "This" , "is"   , "a"    , "test." )
7231@end example
7232@end defun
7233
7234@node string, substr, split, Miscellaneous
7235
7236@cindex Strings
7237@cindex Character strings
7238@defun string ( e )
7239The @code{string} function converts its argument @var{e} to character
7240type.  If @var{e} is NULL, a zero-length character scalar is returned.
7241For example, @code{string(1/(1:3))} returns the vector@refill
7242
7243@example
7244(  "1"       , "0.5"     , "0.333333" )
7245@end example
7246
7247Currently, the output format cannot be changed.
7248@end defun
7249
7250@node substr, test, string, Miscellaneous
7251
7252@cindex Substrings
7253@cindex Character strings
7254@defun substr ( c; start; length )
7255The @code{substr} function returns the substring of the character string
7256@var{c}, beginning at index @var{start}, with length @var{length}.  The
7257integer @var{start} must be greater than zero; if it exceeds the length
7258of @var{c}, then a zero-length string is returned.  If @var{length} is
7259NULL, then all of the remaining characters of @var{c} are returned;
7260otherwise, @var{length} must not be negative.@refill
7261
7262See also @code{dice}, @code{split}, and @code{string}.@refill
7263@end defun
7264
7265@node test, time, substr, Miscellaneous
7266
7267@defun test ( e )
7268The @code{test} function evaluates the ``truth'' of @var{e} in the same
7269way that Algae's @code{if} statement would, returning 1 for true and 0
7270for false.  The following entities are false:@refill
7271
7272@itemize @bullet
7273@item
7274NULL.
7275
7276@item
7277Numeric arrays in which every element is zero.
7278
7279@item
7280Character arrays in which every element is @code{""}.
7281
7282@item
7283Vectors and matrices with no elements.
7284
7285@item
7286Tables with no members.
7287@end itemize
7288
7289@noindent
7290All others are true.  Notice that if @var{e} is an array
7291(@code{scalar}, @code{vector}, or @code{matrix}), then @code{test}
7292returns true if any element of @var{e} is nonzero (or has nonzero
7293length, for character type).@refill
7294
7295An example of the use of @code{test} is Algae's @code{equal} function,
7296which is written as@refill
7297
7298@example
7299equal = function( a; b ) @{ return !test( a != b ); @}
7300@end example
7301
7302@noindent
7303If @code{a} and @code{b} are both matrices, then @code{a!=b} returns a
7304matrix that is all zeros only if every element pair is equal.  In that
7305case, @code{test} returns 0 and @code{!} changes that to 1.@refill
7306
7307See also @code{equal} and @code{all}.
7308@end defun
7309
7310@node time, tolower, test, Miscellaneous
7311
7312@defun time ( )
7313The @code{time} function returns the number of seconds of user time that
7314the current process has used.  On most machines, its precision is not
7315much more than 1/10 of a second.@refill
7316@end defun
7317
7318@node tolower, toupper, time, Miscellaneous
7319
7320@cindex Lower case
7321@cindex Case
7322@defun tolower ( s )
7323The @code{tolower} function converts strings to lower case.  Every
7324letter is converted as appropriate for the current locale.  The argument
7325@var{S} may be a character scalar, vector, or matrix.@refill
7326
7327See also @code{toupper}.
7328@end defun
7329
7330@node toupper, what, tolower, Miscellaneous
7331
7332@cindex Upper case
7333@cindex Case
7334@defun toupper ( s )
7335The @code{toupper} function converts strings to upper case.  Every
7336letter is converted as appropriate for the current locale.  The argument
7337@var{S} may be a character scalar, vector, or matrix.@refill
7338
7339See also @code{tolower}.
7340@end defun
7341
7342@node what, who, toupper, Miscellaneous
7343
7344@defun what ( )
7345The @code{what} function returns a table containing all of the global
7346functions.  See also @code{who}.@refill
7347@end defun
7348
7349@node who, , what, Miscellaneous
7350
7351@defun who ( opt )
7352The @code{who} function returns a table containing all global variables
7353that are neither functions nor NULL.  Variables with names that begin
7354with @samp{$} are excluded, unless the optional argument @var{opt}
7355equals @code{"$"}.  See also @code{what}.@refill
7356@end defun
7357
7358@node Running Algae, Projects, Standard Functions, Top
7359@comment  node-name,  next,  previous,  up
7360@chapter Running Algae
7361@cindex Interpreter
7362
7363The Algae interpreter assembles your Algae statements into its own
7364opcodes and then executes them.  When you are working interactively,
7365it does this one statement (or one block of statements) at a time.  When
7366its input comes from a file, the entire file is assembled before
7367execution of it begins.@refill
7368
7369@menu
7370* Startup Files::
7371* Command Line::
7372* Errors::
7373* Prompt::
7374* Signals::
7375@end menu
7376
7377@node Startup Files, Command Line, Running Algae, Running Algae
7378@section Startup Files
7379@cindex Startup files
7380@cindex Beginning execution
7381
7382When Algae begins execution, it normally tries to read and
7383execute two startup files.  The first one it tries is the file in
7384which it expects some of its standard functions to be defined.  A
7385default name for this file is given when Algae is
7386compiled---usually it's something like
7387@file{/usr/local/lib/algae/VERSION_NUMBER/algae.A}.  That name can be
7388overridden with an environment variable called @code{ALGAE_RC0}.@refill
7389
7390Without this file, some of Algae's standard functions will be
7391missing.  For this reason, Algae will emit an error message and
7392quit if it can't find the file.  (That is, unless the @samp{-S} option
7393is specified on the command line.)@refill
7394
7395After Algae reads its standard functions, it looks for the file
7396@file{.algae} in your home directory and executes it if it's there.  This
7397file's name can be overridden with the @code{ALGAE_RC1} environment
7398variable.  Execution of this file is inhibited by the @samp{-s} command
7399line option.  No startup files at all are read if the @samp{-S} option
7400is given.@refill
7401
7402@node Command Line, Errors, Startup Files, Running Algae
7403@section The Command Line
7404@cindex Command line arguments
7405@cindex Arguments, command line
7406@cindex Options on the command line
7407@cindex Files on the command line
7408
7409Algae supports command line arguments to request various actions.
7410Arguments starting with @samp{-} are @dfn{options}.  Other arguments
7411specify files to execute.@refill
7412
7413Option flags always begin with a hyphen.  Algae supports both traditional
7414single-letter options and mnemonic long option names.  Long option names
7415are indicated with @samp{--} instead of @samp{-}.  Abbreviations for
7416option names are allowed as long as they are unique.@refill
7417
7418Options which change Algae's behavior take effect before any files are
7419executed.  The order of the arguments is unimportant, with the following
7420two exceptions:@refill
7421@enumerate
7422@item
7423Any input scripts given (with the @samp{-e} or @samp{--script} option)
7424are executed in the order that they appear on the command line.  This
7425occurs after the startup files are executed and before any other files
7426are executed.@refill
7427
7428@item
7429Any input files named on the command line are executed in the order in
7430which they appear.@refill
7431@end enumerate
7432
7433Below is a list of options accepted by Algae.  Both the short and long
7434option names are indicated.@refill
7435
7436@table @samp
7437@item -D
7438@itemx --disassemble
7439@cindex Disassembler
7440This option turns on the disassembler, which prints Algae's
7441opcodes to stderr in a form like assembly language.  You'll probably
7442want to combine this with the @samp{-S} option; otherwise, you'll get
7443more than 800 lines of opcodes from the standard functions.@refill
7444
7445@item -d @var{i}
7446@itemx --debug @var{i}
7447@cindex Debug level
7448This option sets the debug level to @var{i}, where @var{i} is an
7449integer.  It is normally of use only for debugging the Algae
7450implementation.@refill
7451
7452@item -e @var{commands}
7453@itemx --script @var{commands}
7454This option allows you to provide a script for Algae to execute
7455from the command line, rather than from a file or from standard input.
7456Such a script is executed after any startup files but before any other
7457files are executed.  Any number of @samp{-e} (or @samp{--script})
7458options may be given, and the specified scripts are executed in the
7459order in which they appear on the command line.@refill
7460
7461@item -h
7462@itemx --help
7463Print a brief description of the command line arguments.
7464
7465@item -i
7466@itemx --interactive
7467@cindex Standard input
7468@cindex stdin
7469@cindex Interactive mode
7470This option causes Algae to use interactive mode when reading from
7471the standard input device ``stdin''.  Without this option, Algae
7472uses interactive mode only when its input appears to be from a terminal.
7473In interactive mode, input is parsed a line at a time and exceptions do
7474not cause Algae to exit.@refill
7475
7476@item -n
7477@itemx --nowhite
7478This option changes the way that scalars are displayed.  The printing
7479statements (that is, statements that are terminated by either a newline
7480or a @samp{?} character) normally precede the scalar's value with a tab,
7481and follow it with a newline.  With this option set, neither the tab nor
7482the newline is printed.  (For character scalars, the quotation marks are
7483also omitted.)  This option affects the printing statements only, and
7484has no effect on the functions like @code{printf}.@refill
7485
7486@item -p
7487@itemx --profile
7488@cindex Execution profiling
7489@cindex Profiling
7490@cindex algae.out
7491This option enables execution profiling---a means for determining the
7492execution time characteristics of your Algae program.  When profiling is
7493enabled, the profiler periodically interrupts Algae and records
7494the line that is currently being executed.  When Algae exits, it
7495records this data in the file @file{algae.out} in the current
7496directory.@refill
7497
7498Use the @code{prof} function to read the @file{algae.out} file and
7499summarize it by file and by line number.@refill
7500
7501You may wish to use the @code{strip} function in conjunction with
7502profiling.  Since @code{strip} removes the line and file information
7503from a function, any time spent in a call to that function gets charged
7504to the line from which it was called.@refill
7505
7506We've encountered several systems on which operating system bugs prevent
7507the execution profiler from working correctly.  These include a
7508DECstation and a Titan, both with MIPS architectures.  If you have such
7509a system, then Algae should have been installed with the execution
7510profiler disabled.  In that case, you'll get an error message if you try
7511to use the @samp{-p} option.@refill
7512
7513@item -R
7514@itemx --restrict
7515@cindex Restricted execution
7516@cindex Pipes
7517@cindex Input filters
7518@cindex Output filters
7519This option causes Algae to run in restricted mode.  The
7520@code{system} function is disabled, as are "pipes" (i.e., file names
7521that begin with the @samp{!} character).@refill
7522
7523Restricted mode should be used whenever you deal with untrusted Algae
7524code.  Without it, a malicious provider of such code could cause major
7525damage.@refill
7526
7527@item -r
7528@itemx --noreadline
7529@cindex Readline facility
7530@cindex Emacs
7531@cindex vi
7532If the GNU Readline facility is available, Algae normally uses it
7533for interactive command line editing and history.  The @samp{-r} option
7534forces Algae to skip Readline processing.  Readline's editing
7535commands are similar to emacs: @kbd{C-f} forward, @kbd{C-b} backward,
7536@kbd{C-p} up, and @kbd{C-n} down.  You can change to @code{vi} style by
7537typing @kbd{M-C-j}.@refill
7538
7539@item -S
7540@itemx --nostartup
7541If this option is given, none of Algae's startup files are read.
7542This means that many of the standard functions will be unavailable.@refill
7543
7544@item -s
7545@itemx --norc
7546This option skips reading the user's startup file.
7547
7548@item -V
7549@itemx --version
7550@cindex Version
7551This option prints version and date information.
7552
7553@item -x
7554@itemx --nostdin
7555@cindex stdin
7556This option causes Algae not to read stdin by default when no
7557file names are given on the command line.
7558@end table
7559
7560Any file names given on the command line are executed as input to Algae.
7561If no file names are given (and the @code{-x} option is not present),
7562input comes from stdin.  You can specify stdin explicitly with a single
7563hyphen, so a command line like@refill
7564
7565@example
7566algae init.A -
7567@end example
7568
7569@noindent
7570has Algae execute @file{init.A} first and then read from standard
7571input.@refill
7572
7573@node Errors, Prompt, Command Line, Running Algae
7574@section Errors
7575@cindex Error messages
7576@cindex Messages, error
7577
7578Several types of errors may be encountered when running Algae.
7579The two most common are @dfn{parse} errors and @dfn{run time} errors.
7580Parse errors occur while Algae is parsing its input statements.
7581Run time errors occur while Algae is executing its code.  In both
7582cases, Algae prints a file name and line number associated with
7583the error.@refill
7584
7585@node Prompt, Signals, Errors, Running Algae
7586@section The algae Prompt
7587@cindex Prompt
7588
7589When executing interactively, Algae displays the primary prompt
7590when it is ready to read a command, and the secondary prompt when it
7591needs more input to complete a command.  You can customize the prompt
7592simply by assigning a character vector to the global variable
7593@code{$prompt}.  Its first two elements specify the primary and
7594secondary prompts.  By default, @code{$prompt} is @code{( "> ", " " )}.
7595Assigning something other than a character vector to @code{$prompt} is
7596not an error---Algae just won't give you a prompt.  (Wouldn't it
7597be fun to accept a function?  Hmm, maybe someday.)@refill
7598
7599If the GNU Readline facility is available (that is, linked with
7600Algae during installation), Algae normally uses it for
7601interactive command line editing and history.  Readline's editing
7602commands are similar to emacs: @kbd{C-f} forward, @kbd{C-b} backward,
7603@kbd{C-p} up, and @kbd{C-n} down.  You can change to @code{vi} style by
7604typing @kbd{M-C-j}.  The @samp{-r} command line option forces
7605Algae to skip Readline processing.@refill
7606
7607@node Signals, , Prompt, Running Algae
7608@section Signals
7609@cindex Signals
7610
7611@cindex SIGINT
7612@cindex Interrupt signal
7613@cindex Killing Algae
7614If Algae receives an interrupt signal (because you pressed a
7615@kbd{C-c} on the keyboard, for example), it stops what it's doing and
7616returns to the prompt.  (If it isn't running interactively, it simply
7617exits.)  On Unix systems, you can also use the @code{kill} command to
7618send a signal to a process.@refill
7619
7620The implementation of interrupt signal handling in Algae is
7621necessarily a compromise.  We want it to respond promptly, but not at
7622the expense of our performance.  As a result, it sometimes happens that
7623Algae does not respond promptly to an interrupt signal.  (If you
7624find a case like this; please report it.  Sometimes it's the result of
7625an oversight.)@refill
7626
7627@cindex SIGQUIT
7628@cindex Quit signal
7629Sending Algae a quit signal causes an immediate, clean exit.
7630There are various other signals which will cause Algae to
7631terminate, but this is the one to use if you want your files closed
7632properly, etc.@refill
7633
7634@node Projects, Bugs, Running Algae, Top
7635@comment  node-name,  next,  previous,  up
7636@chapter Projects
7637@cindex Projects
7638@cindex Future of Algae
7639
7640Below is a list of improvements that we'd like to make to Algae.  These
7641items run the gamut from specific changes that would take only an hour
7642or so to implement to vague, half-baked ideas that might take months.
7643The items are in no particular order---we haven't identified priorities
7644on most of them.  We'd be very happy to have some help.@refill
7645
7646@itemize @bullet
7647@comment Done in version 3.7.1
7648@ignore
7649@item
7650Algae should incorporate the ARPACK sparse matrix routines.  This will
7651be a bit of work, but pretty straightforward.  I consider this a high
7652priority.@refill
7653@end ignore
7654
7655@comment Done in version 4.3.0
7656@ignore
7657@item
7658Algae's FFT routines are old and crusty, but they work well.  Still, we
7659ought to take a look at the FFTW code and consider using it.@refill
7660@end ignore
7661
7662@item
7663The @code{atan} and @code{atanh} functions need improvement for complex
7664arguments.  They are based on simple formulas, but better algorithms are
7665available that are faster, more accurate, and less prone to
7666overflow.@refill
7667
7668@item
7669In the old days, getting Readline to do context-based completion (as on
7670variable names) was nearly impossible.  This may have changed -- we
7671ought to take a new look at it.@refill
7672
7673@item
7674The @code{printf} and related functions should be given additional
7675capabilities to accept array arguments.@refill
7676
7677@item
7678I'm interested in exploring a better arrangement for the help system.
7679Users should be able to tie in documentation for their own code.@refill
7680
7681@comment Done in version 2.2.0.
7682@ignore
7683@item
7684We should fix up the @code{get} and @code{put} functions to maintain
7685their own internal references.  For example, the statement @code{A=B=C}
7686results in three variables that point to the same entity in memory.  But
7687if you then type @code{put(@{A;B;C@})}, that entity winds up being written
7688three times.@refill
7689@end ignore
7690
7691@comment Done in version 3.0.3.
7692@ignore
7693@item
7694We ought to provide a capability for reporting the global variables used
7695or modified by functions.  A simple implementation would be very
7696easy.@refill
7697@end ignore
7698
7699@item
7700With the @code{builtin} function, Algae has dynamic linking
7701capability.  To make this useful, though, we have to document the
7702interface and reorganize the header files.@refill
7703
7704@item
7705Wouldn't a @uref{http://www.gtk.org/, GTK+} interface be nice?@refill
7706
7707@item
7708We need to complete the @code{fread} and @code{fwrite} implementation,
7709and we'll probably want an @code{fseek} function as well.@refill
7710
7711@item
7712Symbolic debugging of Algae code would be very helpful.
7713
7714@comment Hmm, now this seems like a dumb idea.
7715@ignore
7716@item
7717We've considered implicit operations on array elements.  For example,
7718@code{A[+;]} would sum each row of the matrix @code{A}.  Likewise,
7719@code{V[cos]} would apply the @code{cos} function to each element of the
7720vector @code{V}.@refill
7721@end ignore
7722
7723@comment What's wrong with `pick'?
7724@ignore
7725@item
7726A couple of additional operators would be useful for making
7727``selections''; that is, partition one array based on boolean values of
7728a selection vector.@refill
7729@end ignore
7730@end itemize
7731
7732@node Bugs, Concept Index, Projects, Top
7733@comment  node-name,  next,  previous,  up
7734@chapter Bugs
7735@cindex Bugs
7736
7737Your bug reports play an essential role in making Algae reliable.
7738By reporting a bug, you may or may not get a timely solution to your
7739problem.  Either way, bug reports help us to make the next version of
7740Algae better.  In addition, your comments or criticisms on
7741Algae or the Algae language are also welcomed.@refill
7742
7743@cindex Detours
7744The Algae interpreter is incomplete.  There are several operations
7745that it should be able to perform but that have not yet been
7746implemented.  These cases elicit a ``detour'' message from Algae.
7747Since they're not bugs, you don't need to tell us about them.  Still,
7748complaining about them might get them fixed.@refill
7749
7750@menu
7751* Reporting Bugs::
7752* Reported Bugs::
7753@end menu
7754
7755@node Reporting Bugs, Reported Bugs, Bugs, Bugs
7756@section Reporting Bugs
7757@cindex Reporting bugs
7758
7759In order for a bug report to serve its purpose, you must include the
7760information we need to fix it.  As the GNU people say, ``report all the
7761facts''.  But never mind Joe Friday---the more information the better.
7762It usually doesn't pay to explore the ``envelope'' of the bug; that is,
7763changes to the input that affect it.  Providing a simple example is the
7764best way to get a bug fixed.@refill
7765
7766You should include the following information with your bug report:
7767
7768@itemize @bullet
7769@item
7770The version of Algae.  You can get this by running it with the
7771@samp{-V} option.@refill
7772
7773@item
7774A complete input file that will reproduce the bug.  A single statement
7775is generally not sufficient.@refill
7776
7777@item
7778The type of machine you are using, and the operating system name and
7779version number.@refill
7780
7781@item
7782A description of what behavior you observe that you believe is
7783incorrect.@refill
7784@end itemize
7785
7786Send bug reports to:
7787
7788@example
7789ksh@@sideslip.org
7790@end example
7791
7792@noindent
7793or, as a last resort, mail them to:
7794
7795@example
7796Algae Bugs
7797Attn: Scott Hunziker
7798The Boeing Company
7799P.O. Box 3707, MC 8K-26
7800Seattle, WA  98124-2207
7801@end example
7802
7803@node Reported Bugs, , Reporting Bugs, Bugs
7804@section Reported Bugs
7805@cindex Known bugs
7806@cindex Reported bugs
7807
7808Below is a list of bugs that are known to exist in the current version
7809of Algae and are waiting to be fixed.@refill
7810
7811@table @asis
7812@item 1
7813Recurse deep enough, and Algae dumps core.  For example, the
7814expression@refill
7815
7816@example
7817function () @{ return self(); @} ()
7818@end example
7819
7820@noindent
7821will not return gracefully.  (I just tried it, and I had to reboot my
7822machine!)  It usually takes more than 500 levels of recursion to hit
7823this bug, though, so you'll probably only encounter it with runaway
7824functions.@refill
7825
7826@comment Fixed, in the sense that we no longer say anything about $print.
7827@ignore
7828@item 2
7829The @code{$print} variable doesn't control printing as it is said to.
7830@end ignore
7831
7832@comment Fixed (at least I don't know any others that are wrong). 6/26/92
7833@ignore
7834@item 3
7835Many of the builtin functions don't play by the rules when it comes to
7836variable length argument lists.  For example, the @code{union} function
7837works fine on @code{union(v)} and @code{union(v;w)}, but raises an
7838exception on @code{union(v;NULL)}.  Since @code{union} takes at least
7839two arguments, @code{union(v)} and @code{union(v;NULL)} are supposed to
7840be equivalent.@refill
7841@end ignore
7842
7843@comment Fixed, 8/31/93.
7844@ignore
7845@item 4
7846The @samp{+=} and @samp{-=} operators give a syntax error when their
7847left operand contains an element reference.  For example, @code{x[1]+=1}
7848doesn't work.@refill
7849@end ignore
7850
7851@comment Fixed 5/7/92.
7852@ignore
7853@item 5
7854A @code{local} declaration outside a function dumps core.
7855@end ignore
7856
7857@comment Fixed 8/31/93 by claiming that it's a feature instead of a bug.
7858@ignore
7859@item 6
7860The @samp{+=} and @samp{-=} operators screw up when member references
7861are on the right-hand side.  For example,@refill
7862
7863@example
7864a.(b+=1) += c;
7865@end example
7866
7867@noindent
7868is coded exactly like
7869
7870@example
7871a.(b+=1) = a.(b+=1) + c;
7872@end example
7873
7874@noindent
7875which results in @code{b} getting incremented twice.  Instead, it should
7876code as@refill
7877
7878@example
7879b+=1; a.(b) = a.(b) + c;
7880@end example
7881@end ignore
7882
7883@comment Fixed (9/3/93), in that we no longer read two startup files.
7884@ignore
7885@item 7
7886Initialization file reading should be smart enough not to read the same
7887file more than once.@refill
7888@end ignore
7889
7890@comment Fixed 7/5/93.
7891@ignore
7892@item 8
7893This is more like a phylum than a bug, but right now we don't handle
7894floating point exceptions.@refill
7895@end ignore
7896
7897@comment Fixed 6/23/92.
7898@ignore
7899@item 9
7900Normalization in @code{fft} and @code{ifft} is not done the way the
7901documentation says it is.  The expression @code{ifft(fft(v))} returns
7902@code{v} divided by two pi.
7903@end ignore
7904
7905@comment Fixed (as far as I know) 5/11/93.
7906@ignore
7907@item 10
7908The ``pile'' operations (and doubtless many others) do not check for fat
7909sparse arrays.
7910@end ignore
7911
7912@comment Fixed 5/11/93.
7913@ignore
7914@item 11
7915The random number code is botched.  It's supposed to allow you to
7916specify which generator to use (like "rand" or "random") when you
7917install Algae.  Problem is, they have different return types.
7918@end ignore
7919
7920@comment Fixed, 8/31/93.
7921@ignore
7922@item 12
7923An expression like @code{$$.(x)=0}, which would set to zero the global
7924variable named by @code{x}, currently gives a parse error.  This would
7925be a useful thing to have, and should be fixed.@refill
7926@end ignore
7927
7928@comment Fixed, 11/5/94.
7929@ignore
7930@item 13
7931The @code{solve} function should warn about ill-conditioning.  The
7932@code{factor} function does this now, but @code{solve} uses LAPACK
7933``driver'' routines which don't estimate the condition number.  We
7934should use the ``expert'' routines, instead.
7935@end ignore
7936
7937@comment Fixed, at long last, 3/22/97.
7938@ignore
7939@item 14
7940The parser has trouble with comments that are on the last line of a file
7941and are not followed by a newline.@refill
7942@end ignore
7943
7944@comment Fixed 7/25/93.
7945@ignore
7946@item 15
7947Though I doubt that it's a very useful feature, Algae does support
7948sparse, character arrays.  They're buggy, though, so you should avoid
7949them.  For example, `sparse(fill(5,5);"")' dumps core.@refill
7950@end ignore
7951
7952@item 16
7953We have problems when a parse error occurs in a recursive call to the
7954parser.  Local variables created in the recursive call are left in an
7955invalid state.  This happens, for example, if you call the @code{source}
7956function from an interactive session and encounter a parse error in the
7957process.@refill
7958
7959@comment Fixed, by calling it a feature.
7960@ignore
7961@item 17
7962The @code{return} statement never prints its result.
7963@end ignore
7964
7965@comment Fixed 6/24/96.
7966@ignore
7967@item 18
7968The execution profiler appears to have trouble with the line numbers
7969that it reports.  File charging looks OK, but hits are occasionally
7970charged to the wrong line.  We're looking into it.@refill
7971@end ignore
7972
7973@comment Moved to Projects, 3/29/94.
7974@ignore
7975@item 19
7976The ``submatrix assignment'' code (for handling statements like
7977@code{A[u;v]=B}) is terribly inefficient.  It's not a matter of
7978how many percent faster it could be, but more like how many orders of
7979magnitude.@refill
7980@end ignore
7981
7982@comment Unfortunate, but not a bug.  (10/24/94)
7983@ignore
7984@item 20
7985If @code{x} is a hermitian matrix, then @code{x+real(x)} should also be
7986hermitian.  Presently, it goes to general symmetry.@refill
7987@end ignore
7988
7989@comment Fixed 10/25/01.
7990@ignore
7991@item 21
7992The logical operations don't keep matrices sparse when they could.  For
7993example, @code{a&a} should be sparse if @code{a} is sparse; instead,
7994it's converted to dense.@refill
7995@end ignore
7996
7997@item 22
7998Every time Algae parses a file, it leaks the memory in which the name of
7999that file is stored.  The names are kept around because user functions
8000refer to them.  Instead, we should arrange for the names to be stored
8001with each user function so that they get deleted when the function is
8002deleted.@refill
8003
8004@item 23
8005When Algae reads a binary file that contains a user function, it
8006allocates memory for every string constant in that function.  If you
8007then delete that function, this memory is leaked.@refill
8008
8009@item 24
8010We use the texi2html program to make Algae's HTML documentation from the
8011texinfo source.  Among its numerous deficiencies, it sometimes splits an
8012anchor from the text with which it is supposed to be associated.  For
8013example (from algae-3.5.0), the anchor for the section named ``Running
8014Algae'' is put at the bottom of the file @file{algae_6.html} instead of
8015at the top of @file{algae_7.html} where it belongs.  For this reason,
8016the Algae @code{info} function may not take you to the right place in
8017the document.@refill
8018@end table
8019
8020@node Concept Index, Function Index, Bugs, Top
8021@comment  node-name,  next,  previous,  up
8022@unnumbered Concept Index
8023
8024If you can't find what you're looking for here, please send us a bug
8025report.  We'll try to include an entry for it in the next release of
8026this manual.@refill
8027
8028@printindex cp
8029
8030@node Function Index, , Concept Index, Top
8031@comment  node-name,  next,  previous,  up
8032@unnumbered Function Index
8033
8034@printindex fn
8035
8036@contents
8037@bye
8038