~ubuntu-branches/debian/sid/octave3.0/sid

« back to all changes in this revision

Viewing changes to doc/interpreter/octave.info-2

  • Committer: Bazaar Package Importer
  • Author(s): Rafael Laboissiere
  • Date: 2007-12-23 16:04:15 UTC
  • Revision ID: james.westby@ubuntu.com-20071223160415-n4gk468dihy22e9v
Tags: upstream-3.0.0
ImportĀ upstreamĀ versionĀ 3.0.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
This is octave.info, produced by makeinfo version 4.11 from ./octave.texi.
 
2
 
 
3
START-INFO-DIR-ENTRY
 
4
* Octave: (octave).     Interactive language for numerical computations.
 
5
END-INFO-DIR-ENTRY
 
6
 
 
7
   Copyright (C) 1996, 1997, 1999, 2000, 2001, 2002, 2005, 2006, 2007
 
8
John W. Eaton.
 
9
 
 
10
   Permission is granted to make and distribute verbatim copies of this
 
11
manual provided the copyright notice and this permission notice are
 
12
preserved on all copies.
 
13
 
 
14
   Permission is granted to copy and distribute modified versions of
 
15
this manual under the conditions for verbatim copying, provided that
 
16
the entire resulting derived work is distributed under the terms of a
 
17
permission notice identical to this one.
 
18
 
 
19
   Permission is granted to copy and distribute translations of this
 
20
manual into another language, under the above conditions for modified
 
21
versions.
 
22
 
 
23
 
 
24
File: octave.info,  Node: Organization of Functions,  Prev: Commands,  Up: Functions and Scripts
 
25
 
 
26
11.11 Organization of Functions Distributed with Octave
 
27
=======================================================
 
28
 
 
29
Many of Octave's standard functions are distributed as function files.
 
30
They are loosely organized by topic, in subdirectories of
 
31
`OCTAVE-HOME/lib/octave/VERSION/m', to make it easier to find them.
 
32
 
 
33
   The following is a list of all the function file subdirectories, and
 
34
the types of functions you will find there.
 
35
 
 
36
`audio'
 
37
     Functions for playing and recording sounds.
 
38
 
 
39
`control'
 
40
     Functions for design and simulation of automatic control systems.
 
41
 
 
42
`elfun'
 
43
     Elementary functions.
 
44
 
 
45
`finance'
 
46
     Functions for computing interest payments, investment values, and
 
47
     rates of return.
 
48
 
 
49
`general'
 
50
     Miscellaneous matrix manipulations, like `flipud', `rot90', and
 
51
     `triu', as well as other basic functions, like `ismatrix',
 
52
     `nargchk', etc.
 
53
 
 
54
`image'
 
55
     Image processing tools.  These functions require the X Window
 
56
     System.
 
57
 
 
58
`io'
 
59
     Input-ouput functions.
 
60
 
 
61
`linear-algebra'
 
62
     Functions for linear algebra.
 
63
 
 
64
`miscellaneous'
 
65
     Functions that don't really belong anywhere else.
 
66
 
 
67
`optimization'
 
68
     Minimization of functions.
 
69
 
 
70
`path'
 
71
     Functions to manage the directory path Octave uses to find
 
72
     functions.
 
73
 
 
74
`pkg'
 
75
     Install external packages of functions in Octave.
 
76
 
 
77
`plot'
 
78
     Functions for displaying and printing two- and three-dimensional
 
79
     graphs.
 
80
 
 
81
`polynomial'
 
82
     Functions for manipulating polynomials.
 
83
 
 
84
`set'
 
85
     Functions for creating and manipulating sets of unique values.
 
86
 
 
87
`signal'
 
88
     Functions for signal processing applications.
 
89
 
 
90
`sparse'
 
91
     Functions for handling sparse matrices.
 
92
 
 
93
`specfun'
 
94
     Special functions.
 
95
 
 
96
`special-matrix'
 
97
     Functions that create special matrix forms.
 
98
 
 
99
`startup'
 
100
     Octave's system-wide startup file.
 
101
 
 
102
`statistics'
 
103
     Statistical functions.
 
104
 
 
105
`strings'
 
106
     Miscellaneous string-handling functions.
 
107
 
 
108
`testfun'
 
109
     Perform unit tests on other functions.
 
110
 
 
111
`time'
 
112
     Functions related to time keeping.
 
113
 
 
114
 
 
115
File: octave.info,  Node: Errors and Warnings,  Next: Debugging,  Prev: Functions and Scripts,  Up: Top
 
116
 
 
117
12 Errors and Warnings
 
118
**********************
 
119
 
 
120
Octave includes several functions for printing error and warning
 
121
messages.  When you write functions that need to take special action
 
122
when they encounter abnormal conditions, you should print the error
 
123
messages using the functions described in this chapter.
 
124
 
 
125
   Since many of Octave's functions use these functions, it is also
 
126
useful to understand them, so that errors and warnings can be handled.
 
127
 
 
128
* Menu:
 
129
 
 
130
* Handling Errors::
 
131
* Handling Warnings::
 
132
 
 
133
 
 
134
File: octave.info,  Node: Handling Errors,  Next: Handling Warnings,  Up: Errors and Warnings
 
135
 
 
136
12.1 Handling Errors
 
137
====================
 
138
 
 
139
An error is something that occurs when a program is in a state where it
 
140
doesn't make sense to continue.  An example is when a function is
 
141
called with too few input arguments.  In this situation the function
 
142
should abort with an error message informing the user of the lacking
 
143
input arguments.
 
144
 
 
145
   Since an error can occur during the evaluation of a program, it is
 
146
very convenient to be able to detect that an error occurred, so that
 
147
the error can be fixed.  This is possible with the `try' statement
 
148
described in *note The try Statement::.
 
149
 
 
150
* Menu:
 
151
 
 
152
* Raising Errors::
 
153
* Catching Errors::
 
154
 
 
155
 
 
156
File: octave.info,  Node: Raising Errors,  Next: Catching Errors,  Up: Handling Errors
 
157
 
 
158
12.1.1 Raising Errors
 
159
---------------------
 
160
 
 
161
The most common use of errors is for checking input arguments to
 
162
functions.  The following example calls the `error' function if the
 
163
function `f' is called without any input arguments.
 
164
 
 
165
     function f (arg1)
 
166
       if (nargin == 0)
 
167
         error("not enough input arguments");
 
168
       endif
 
169
     endfunction
 
170
 
 
171
   When the `error' function is called, it prints the given message and
 
172
returns to the Octave prompt.  This means that no code following a call
 
173
to `error' will be executed.
 
174
 
 
175
 -- Built-in Function:  error (TEMPLATE, ...)
 
176
 -- Built-in Function:  error (ID, TEMPLATE, ...)
 
177
     Format the optional arguments under the control of the template
 
178
     string TEMPLATE using the same rules as the `printf' family of
 
179
     functions (*note Formatted Output::) and print the resulting
 
180
     message on the `stderr' stream.  The message is prefixed by the
 
181
     character string `error: '.
 
182
 
 
183
     Calling `error' also sets Octave's internal error state such that
 
184
     control will return to the top level without evaluating any more
 
185
     commands.  This is useful for aborting from functions or scripts.
 
186
 
 
187
     If the error message does not end with a new line character,
 
188
     Octave will print a traceback of all the function calls leading to
 
189
     the error.  For example, given the following function definitions:
 
190
 
 
191
          function f () g (); end
 
192
          function g () h (); end
 
193
          function h () nargin == 1 || error ("nargin != 1"); end
 
194
 
 
195
     calling the function `f' will result in a list of messages that
 
196
     can help you to quickly locate the exact location of the error:
 
197
 
 
198
          f ()
 
199
          error: nargin != 1
 
200
          error: evaluating index expression near line 1, column 30
 
201
          error: evaluating binary operator `||' near line 1, column 27
 
202
          error: called from `h'
 
203
          error: called from `g'
 
204
          error: called from `f'
 
205
 
 
206
     If the error message ends in a new line character, Octave will
 
207
     print the message but will not display any traceback messages as
 
208
     it returns control to the top level.  For example, modifying the
 
209
     error message in the previous example to end in a new line causes
 
210
     Octave to only print a single message:
 
211
 
 
212
          function h () nargin == 1 || error ("nargin != 1\n"); end
 
213
          f ()
 
214
          error: nargin != 1
 
215
 
 
216
   Since it is common to use errors when there is something wrong with
 
217
the input to a function, Octave supports functions to simplify such
 
218
code.  When the `print_usage' function is called, it reads the help text
 
219
of the function calling `print_usage', and presents a useful error.  If
 
220
the help text is written in Texinfo it is possible to present an error
 
221
message that only contains the function prototypes as described by the
 
222
`@deftypefn' parts of the help text.  When the help text isn't written
 
223
in Texinfo, the error message contains the entire help message.
 
224
 
 
225
   Consider the following function.
 
226
     ## -*- texinfo -*-
 
227
     ## @deftypefn {Function File} f (@var{arg1})
 
228
     ## Function help text goes here...
 
229
     ## @end deftypefn
 
230
     function f (arg1)
 
231
       if (nargin == 0)
 
232
         print_usage ();
 
233
       endif
 
234
     endfunction
 
235
 
 
236
When it is called with no input arguments it produces the following
 
237
error.
 
238
 
 
239
     f ()
 
240
          -| Invalid call to f.  Correct usage is:
 
241
          -|
 
242
          -|  -- Function File: f (ARG1)
 
243
          -|
 
244
          -|
 
245
          -|
 
246
          -| error: evaluating if command near line 6, column 3
 
247
          -| error: called from `f' in file `/home/jwe/octave/f.m'
 
248
 
 
249
 -- Loadable Function:  print_usage ()
 
250
     Print the usage message for the currently executing function.  The
 
251
     `print_usage' function is only intended to work inside a
 
252
     user-defined function.
 
253
 
 
254
     *See also:* help.
 
255
 
 
256
 -- Built-in Function:  usage (MSG)
 
257
     Print the message MSG, prefixed by the string `usage: ', and set
 
258
     Octave's internal error state such that control will return to the
 
259
     top level without evaluating any more commands.  This is useful for
 
260
     aborting from functions.
 
261
 
 
262
     After `usage' is evaluated, Octave will print a traceback of all
 
263
     the function calls leading to the usage message.
 
264
 
 
265
     You should use this function for reporting problems errors that
 
266
     result from an improper call to a function, such as calling a
 
267
     function with an incorrect number of arguments, or with arguments
 
268
     of the wrong type.  For example, most functions distributed with
 
269
     Octave begin with code like this
 
270
 
 
271
          if (nargin != 2)
 
272
            usage ("foo (a, b)");
 
273
          endif
 
274
 
 
275
     to check for the proper number of arguments.
 
276
 
 
277
 -- Function File:  beep ()
 
278
     Produce a beep from the speaker (or visual bell).
 
279
 
 
280
     *See also:* puts, fputs, printf, fprintf.
 
281
 
 
282
 -- Built-in Function: VAL = beep_on_error ()
 
283
 -- Built-in Function: OLD_VAL = beep_on_error (NEW_VAL)
 
284
     Query or set the internal variable that controls whether Octave
 
285
     will try to ring the terminal bell before printing an error
 
286
     message.
 
287
 
 
288
 
 
289
File: octave.info,  Node: Catching Errors,  Prev: Raising Errors,  Up: Handling Errors
 
290
 
 
291
12.1.2 Catching Errors
 
292
----------------------
 
293
 
 
294
When an error occurs, it can be detected and handled using the `try'
 
295
statement as described in *note The try Statement::.  As an example,
 
296
the following piece of code counts the number of errors that occurs
 
297
during a `for' loop.
 
298
 
 
299
     number_of_errors = 0;
 
300
     for n = 1:100
 
301
       try
 
302
         ...
 
303
       catch
 
304
         number_of_errors++;
 
305
       end_try_catch
 
306
     endfor
 
307
 
 
308
   The above example treats all errors the same.  In many situations it
 
309
can however be necessary to discriminate between errors, and take
 
310
different actions depending on the error.  The `lasterror' function
 
311
returns a structure containing information about the last error that
 
312
occurred.  As an example, the code above could be changed to count the
 
313
number of errors related to the `*' operator.
 
314
 
 
315
     number_of_errors = 0;
 
316
     for n = 1:100
 
317
       try
 
318
         ...
 
319
       catch
 
320
         msg = lasterror.message;
 
321
         if (strfind (msg, "operator *"))
 
322
           number_of_errors++;
 
323
         endif
 
324
       end_try_catch
 
325
     endfor
 
326
 
 
327
 -- Built-in Function: ERR = lasterror (ERR)
 
328
 -- Built-in Function:  lasterror ('reset')
 
329
     Returns or sets the last error message. Called without any
 
330
     arguments returns a structure containing the last error message,
 
331
     as well as other information related to this error. The elements
 
332
     of this structure are:
 
333
 
 
334
    'message'
 
335
          The text of the last error message
 
336
 
 
337
    'identifier'
 
338
          The message identifier of this error message
 
339
 
 
340
    'stack'
 
341
          A structure containing information on where the message
 
342
          occurred. This might be an empty structure if this in the
 
343
          case where this information can not be obtained. The fields
 
344
          of this structure are:
 
345
 
 
346
         'file'
 
347
               The name of the file where the error occurred
 
348
 
 
349
         'name'
 
350
               The name of function in which the error occurred
 
351
 
 
352
         'line'
 
353
               The line number at which the error occurred
 
354
 
 
355
         'column'
 
356
               An optional field with the column number at which the
 
357
               error occurred
 
358
 
 
359
     The ERR structure may also be passed to `lasterror' to set the
 
360
     information about the last error. The only constraint on ERR in
 
361
     that case is that it is a scalar structure. Any fields of ERR that
 
362
     match the above are set to the value passed in ERR, while other
 
363
     fields are set to their default values.
 
364
 
 
365
     If `lasterror' is called with the argument 'reset', all values take
 
366
     their default values.
 
367
 
 
368
 -- Built-in Function: [MSG, MSGID] = lasterr (MSG, MSGID)
 
369
     Without any arguments, return the last error message.  With one
 
370
     argument, set the last error message to MSG.  With two arguments,
 
371
     also set the last message identifier.
 
372
 
 
373
   When an error has been handled it is possible to raise it again.
 
374
This can be useful when an error needs to be detected, but the program
 
375
should still abort.  This is possible using the `rethrow' function.  The
 
376
previous example can now be changed to count the number of errors
 
377
related to the `*' operator, but still abort of another kind of error
 
378
occurs.
 
379
 
 
380
     number_of_errors = 0;
 
381
     for n = 1:100
 
382
       try
 
383
         ...
 
384
       catch
 
385
         msg = lasterror.message;
 
386
         if (strfind (msg, "operator *"))
 
387
           number_of_errors++;
 
388
         else
 
389
           rethrow (lasterror);
 
390
         endif
 
391
       end_try_catch
 
392
     endfor
 
393
 
 
394
 -- Built-in Function:  rethrow (ERR)
 
395
     Reissues a previous error as defined by ERR. ERR is a structure
 
396
     that must contain at least the 'message' and 'identifier' fields.
 
397
     ERR can also contain a field 'stack' that gives information on the
 
398
     assumed location of the error. Typically ERR is returned from
 
399
     `lasterror'.
 
400
 
 
401
     *See also:* lasterror, lasterr, error.
 
402
 
 
403
 -- Built-in Function: ERR = errno ()
 
404
 -- Built-in Function: ERR = errno (VAL)
 
405
 -- Built-in Function: ERR = errno (NAME)
 
406
     Return the current value of the system-dependent variable errno,
 
407
     set its value to VAL and return the previous value, or return the
 
408
     named error code given NAME as a character string, or -1 if NAME
 
409
     is not found.
 
410
 
 
411
 -- Built-in Function:  errno_list ()
 
412
     Return a structure containing the system-dependent errno values.
 
413
 
 
414
 
 
415
File: octave.info,  Node: Handling Warnings,  Prev: Handling Errors,  Up: Errors and Warnings
 
416
 
 
417
12.2 Handling Warnings
 
418
======================
 
419
 
 
420
Like an error, a warning is issued when something unexpected happens.
 
421
Unlike an error, a warning doesn't abort the currently running program.
 
422
A simple example of a warning is when a number is divided by zero.  In
 
423
this case Octave will issue a warning and assign the value `Inf' to the
 
424
result.
 
425
 
 
426
     a = 1/0
 
427
          -| warning: division by zero
 
428
          => a = Inf
 
429
 
 
430
* Menu:
 
431
 
 
432
* Issuing Warnings::
 
433
* Enabling and Disabling Warnings::
 
434
 
 
435
 
 
436
File: octave.info,  Node: Issuing Warnings,  Next: Enabling and Disabling Warnings,  Up: Handling Warnings
 
437
 
 
438
12.2.1 Issuing Warnings
 
439
-----------------------
 
440
 
 
441
It is possible to issue warnings from any code using the `warning'
 
442
function. In its most simple form, the `warning' function takes a
 
443
string describing the warning as its input argument. As an example, the
 
444
following code controls if the variable `a' is non-negative, and if not
 
445
issues a warning and sets `a' to zero.
 
446
 
 
447
     a = -1;
 
448
     if (a < 0)
 
449
       warning ("'a' must be non-negative. Setting 'a' to zero.");
 
450
       a = 0;
 
451
     endif
 
452
          -| 'a' must be non-negative. Setting 'a' to zero.
 
453
 
 
454
   Since warnings aren't fatal to a running program, it is not possible
 
455
to catch a warning using the `try' statement or something similar.  It
 
456
is however possible to access the last warning as a string using the
 
457
`lastwarn' function.
 
458
 
 
459
   It is also possible to assign an identification string a a warning.
 
460
If a warning has such an ID the user can enable and disable this warning
 
461
as will be described in the next section.  To assign an ID to a warning,
 
462
simply call `warning' with two string arguments, where the first is the
 
463
identification string, and the second is the actual warning.
 
464
 
 
465
 -- Built-in Function:  warning (TEMPLATE, ...)
 
466
 -- Built-in Function:  warning (ID, TEMPLATE, ...)
 
467
     Format the optional arguments under the control of the template
 
468
     string TEMPLATE using the same rules as the `printf' family of
 
469
     functions (*note Formatted Output::) and print the resulting
 
470
     message on the `stderr' stream.  The message is prefixed by the
 
471
     character string `warning: '.  You should use this function when
 
472
     you want to notify the user of an unusual condition, but only when
 
473
     it makes sense for your program to go on.
 
474
 
 
475
     The optional message identifier allows users to enable or disable
 
476
     warnings tagged by ID.  The special identifier `"all"' may be used
 
477
     to set the state of all warnings.
 
478
 
 
479
 -- Built-in Function:  warning ("on", ID)
 
480
 -- Built-in Function:  warning ("off", ID)
 
481
 -- Built-in Function:  warning ("error", ID)
 
482
 -- Built-in Function:  warning ("query", ID)
 
483
     Set or query the state of a particular warning using the identifier
 
484
     ID.  If the identifier is omitted, a value of `"all"' is assumed.
 
485
     If you set the state of a warning to `"error"', the warning named
 
486
     by ID is handled as if it were an error instead.
 
487
 
 
488
     *See also:* warning_ids.
 
489
 
 
490
 -- Built-in Function: [MSG, MSGID] = lastwarn (MSG, MSGID)
 
491
     Without any arguments, return the last warning message.  With one
 
492
     argument, set the last warning message to MSG.  With two arguments,
 
493
     also set the last message identifier.
 
494
 
 
495
 
 
496
File: octave.info,  Node: Enabling and Disabling Warnings,  Prev: Issuing Warnings,  Up: Handling Warnings
 
497
 
 
498
12.2.2 Enabling and Disabling Warnings
 
499
--------------------------------------
 
500
 
 
501
The `warning' function also allows you to control which warnings are
 
502
actually printed to the screen.  If the `warning' function is called
 
503
with a string argument that is either `"on"' or `"off"' all warnings
 
504
will be enabled or disabled.
 
505
 
 
506
   It is also possible to enable and disable individual warnings through
 
507
their string identifications.  The following code will issue a warning
 
508
 
 
509
     warning ("non-negative-variable",
 
510
              "'a' must be non-negative. Setting 'a' to zero.");
 
511
 
 
512
while the following won't issue a warning
 
513
 
 
514
     warning ("off", "non-negative-variable");
 
515
     warning ("non-negative-variable",
 
516
              "'a' must be non-negative. Setting 'a' to zero.");
 
517
 
 
518
   The functions distributed with Octave can issue one of the following
 
519
warnings.
 
520
 
 
521
`Octave:array-to-scalar'
 
522
     If the `Octave:array-to-scalar' warning is enabled, Octave will
 
523
     warn when an implicit conversion from an array to a scalar value is
 
524
     attempted.  By default, the `Octave:array-to-scalar' warning is
 
525
     disabled.
 
526
 
 
527
`Octave:array-to-vector'
 
528
     If the `Octave:array-to-vector' warning is enabled, Octave will
 
529
     warn when an implicit conversion from an array to a vector value is
 
530
     attempted.  By default, the `Octave:array-to-vector' warning is
 
531
     disabled.
 
532
 
 
533
`Octave:assign-as-truth-value'
 
534
     If the `Octave:assign-as-truth-value' warning is enabled, a
 
535
     warning is issued for statements like
 
536
 
 
537
          if (s = t)
 
538
            ...
 
539
 
 
540
     since such statements are not common, and it is likely that the
 
541
     intent was to write
 
542
 
 
543
          if (s == t)
 
544
            ...
 
545
 
 
546
     instead.
 
547
 
 
548
     There are times when it is useful to write code that contains
 
549
     assignments within the condition of a `while' or `if' statement.
 
550
     For example, statements like
 
551
 
 
552
          while (c = getc())
 
553
            ...
 
554
 
 
555
     are common in C programming.
 
556
 
 
557
     It is possible to avoid all warnings about such statements by
 
558
     disabling the `Octave:assign-as-truth-value' warning, but that may
 
559
     also let real errors like
 
560
 
 
561
          if (x = 1)  # intended to test (x == 1)!
 
562
            ...
 
563
 
 
564
     slip by.
 
565
 
 
566
     In such cases, it is possible suppress errors for specific
 
567
     statements by writing them with an extra set of parentheses.  For
 
568
     example, writing the previous example as
 
569
 
 
570
          while ((c = getc()))
 
571
            ...
 
572
 
 
573
     will prevent the warning from being printed for this statement,
 
574
     while allowing Octave to warn about other assignments used in
 
575
     conditional contexts.
 
576
 
 
577
     By default, the `Octave:assign-as-truth-value' warning is enabled.
 
578
 
 
579
`Octave:associativity-change'
 
580
     If the `Octave:associativity-change' warning is enabled, Octave
 
581
     will warn about possible changes in the meaning of some code due
 
582
     to changes in associativity for some operators.  Associativity
 
583
     changes have typically been made for MATLAB compatibility.  By
 
584
     default, the `Octave:associativity-change' warning is enabled.
 
585
 
 
586
`Octave:divide-by-zero'
 
587
     If the `Octave:divide-by-zero' warning is enabled, a warning is
 
588
     issued when Octave encounters a division by zero.  By default, the
 
589
     `Octave:divide-by-zero' warning is enabled.
 
590
 
 
591
`Octave:empty-list-elements'
 
592
     If the `Octave:empty-list-elements' warning is enabled, a warning
 
593
     is issued when an empty matrix is found in a matrix list.  For
 
594
     example,
 
595
 
 
596
          a = [1, [], 3, [], 5]
 
597
 
 
598
     By default, the `Octave:empty-list-elements' warning is enabled.
 
599
 
 
600
`Octave:fortran-indexing'
 
601
     If the `Octave:fortran-indexing' warning is enabled, a warning is
 
602
     printed for expressions which select elements of a two-dimensional
 
603
     matrix using a single index.  By default, the
 
604
     `Octave:fortran-indexing' warning is disabled.
 
605
 
 
606
`Octave:function-name-clash'
 
607
     If the `Octave:function-name-clash' warning is enabled, a warning
 
608
     is issued when Octave finds that the name of a function defined in
 
609
     a function file differs from the name of the file.  (If the names
 
610
     disagree, the name declared inside the file is ignored.)  By
 
611
     default, the `Octave:function-name-clash' warning is enabled.
 
612
 
 
613
`Octave:future-time-stamp'
 
614
     If the `Octave:future-time-stamp' warning is enabled, Octave will
 
615
     print a warning if it finds a function file with a time stamp that
 
616
     is in the future.  By default, the `Octave:future-time-stamp'
 
617
     warning is enabled.
 
618
 
 
619
`Octave:imag-to-real'
 
620
     If the `Octave:imag-to-real' warning is enabled, a warning is
 
621
     printed for implicit conversions of complex numbers to real
 
622
     numbers.  By default, the `Octave:imag-to-real' warning is
 
623
     disabled.
 
624
 
 
625
`Octave:matlab-incompatible'
 
626
     Print warnings for Octave language features that may cause
 
627
     compatibility problems with MATLAB.
 
628
 
 
629
`Octave:missing-semicolon'
 
630
     If the `Octave:missing-semicolon' warning is enabled, Octave will
 
631
     warn when statements in function definitions don't end in
 
632
     semicolons.  By default the `Octave:missing-semicolon' warning is
 
633
     disabled.
 
634
 
 
635
`Octave:neg-dim-as-zero'
 
636
     If the `Octave:neg-dim-as-zero' warning is enabled, print a warning
 
637
     for expressions like
 
638
 
 
639
          eye (-1)
 
640
 
 
641
     By default, the `Octave:neg-dim-as-zero' warning is disabled.
 
642
 
 
643
`Octave:num-to-str'
 
644
     If the `Octave:num-to-str' warning is enable, a warning is printed
 
645
     for implicit conversions of numbers to their ASCII character
 
646
     equivalents when strings are constructed using a mixture of
 
647
     strings and numbers in matrix notation.  For example,
 
648
 
 
649
          [ "f", 111, 111 ]
 
650
          => "foo"
 
651
     elicits a warning if the `Octave:num-to-str' warning is enabled.
 
652
     By default, the `Octave:num-to-str' warning is enabled.
 
653
 
 
654
`Octave:precedence-change'
 
655
     If the `Octave:precedence-change' warning is enabled, Octave will
 
656
     warn about possible changes in the meaning of some code due to
 
657
     changes in precedence for some operators.  Precedence changes have
 
658
     typically been made for MATLAB compatibility.  By default, the
 
659
     `Octave:precedence-change' warning is enabled.
 
660
 
 
661
`Octave:reload-forces-clear'
 
662
     If several functions have been loaded from the same file, Octave
 
663
     must clear all the functions before any one of them can be
 
664
     reloaded.  If the `Octave:reload-forces-clear' warning is enabled,
 
665
     Octave will warn you when this happens, and print a list of the
 
666
     additional functions that it is forced to clear.  By default, the
 
667
     `Octave:reload-forces-clear' warning is enabled.
 
668
 
 
669
`Octave:resize-on-range-error'
 
670
     If the `Octave:resize-on-range-error' warning is enabled, print a
 
671
     warning when a matrix is resized by an indexed assignment with
 
672
     indices outside the current bounds.  By default, the
 
673
     `Octave:resize-on-range-error' warning is disabled.
 
674
 
 
675
`Octave:separator-insert'
 
676
     Print warning if commas or semicolons might be inserted
 
677
     automatically in literal matrices.
 
678
 
 
679
`Octave:single-quote-string'
 
680
     Print warning if a signle quote character is used to introduce a
 
681
     string constant.
 
682
 
 
683
`Octave:str-to-num'
 
684
     If the `Octave:str-to-num' warning is enabled, a warning is printed
 
685
     for implicit conversions of strings to their numeric ASCII
 
686
     equivalents.  For example,
 
687
          "abc" + 0
 
688
          => 97 98 99
 
689
     elicits a warning if the `Octave:str-to-num' warning is enabled.
 
690
     By default, the `Octave:str-to-num' warning is disabled.
 
691
 
 
692
`Octave:string-concat'
 
693
     If the `Octave:string-concat' warning is enabled, print a warning
 
694
     when concatenating a mixture of double and single quoted strings.
 
695
     By default, the `Octave:string-concat' warning is disabled.
 
696
 
 
697
`Octave:undefined-return-values'
 
698
     If the `Octave:undefined-return-values' warning is disabled, print
 
699
     a warning if a function does not define all the values in the
 
700
     return list which are expected.  By default, the
 
701
     `Octave:undefined-return-values' warning is enabled.
 
702
 
 
703
`Octave:variable-switch-label'
 
704
     If the `Octave:variable-switch-label' warning is enabled, Octave
 
705
     will print a warning if a switch label is not a constant or
 
706
     constant expression.  By default, the
 
707
     `Octave:variable-switch-label' warning is disabled.
 
708
 
 
709
 
 
710
File: octave.info,  Node: Debugging,  Next: Input and Output,  Prev: Errors and Warnings,  Up: Top
 
711
 
 
712
13 Debugging
 
713
************
 
714
 
 
715
Octave includes a built-in debugger to aid in the development of
 
716
scripts. This can be used to interrupt the execution of an Octave script
 
717
at a certain point, or when certain conditions are met. Once execution
 
718
has stopped, and debug mode is entered, the symbol table at the point
 
719
where execution has stopped can be examined and modified to check for
 
720
errors.
 
721
 
 
722
   The normal commandline editing and history functions are available in
 
723
debug mode. However, one limitation on the debug mode is that commands
 
724
entered at the debug prompt are evaluated as strings, rather than being
 
725
handled by the Octave parser. This means that all commands in debug
 
726
mode must be contained on a single line. That is, it is alright to write
 
727
 
 
728
     debug> for i = 1:n, foo(i); endfor
 
729
 
 
730
in debug mode. However, writing the above in three lines will not be
 
731
correctly evaluated. To leave the debug mode, you should simply type
 
732
either `quit', `exit', `return' or `dbcont'.
 
733
 
 
734
* Menu:
 
735
 
 
736
* Entering Debug Mode::
 
737
* Breakpoints::
 
738
* Debug Mode::
 
739
 
 
740
 
 
741
File: octave.info,  Node: Entering Debug Mode,  Next: Breakpoints,  Up: Debugging
 
742
 
 
743
13.1 Entering Debug Mode
 
744
========================
 
745
 
 
746
There are two basic means of interrupting the execution of an Octave
 
747
script. These are breakpoints *note Breakpoints::, discussed in the next
 
748
section and interruption based on some condition.
 
749
 
 
750
   Octave supports three means to stop execution based on the values
 
751
set in the functions `debug_on_interrupt', `debug_on_warning' and
 
752
`debug_on_error'.
 
753
 
 
754
 -- Built-in Function: VAL = debug_on_interrupt ()
 
755
 -- Built-in Function: OLD_VAL = debug_on_interrupt (NEW_VAL)
 
756
     Query or set the internal variable that controls whether Octave
 
757
     will try to enter debugging mode when it receives an interrupt
 
758
     signal (typically generated with `C-c').  If a second interrupt
 
759
     signal is received before reaching the debugging mode, a normal
 
760
     interrupt will occur.
 
761
 
 
762
 -- Built-in Function: VAL = debug_on_warning ()
 
763
 -- Built-in Function: OLD_VAL = debug_on_warning (NEW_VAL)
 
764
     Query or set the internal variable that controls whether Octave
 
765
     will try to enter the debugger when a warning is encountered.
 
766
 
 
767
 -- Built-in Function: VAL = debug_on_error ()
 
768
 -- Built-in Function: OLD_VAL = debug_on_error (NEW_VAL)
 
769
     Query or set the internal variable that controls whether Octave
 
770
     will try to enter the debugger when an error is encountered.  This
 
771
     will also inhibit printing of the normal traceback message (you
 
772
     will only see the top-level error message).
 
773
 
 
774
 
 
775
File: octave.info,  Node: Breakpoints,  Next: Debug Mode,  Prev: Entering Debug Mode,  Up: Debugging
 
776
 
 
777
13.2 Breakpoints
 
778
================
 
779
 
 
780
Breakpoints can be set in any Octave function, using the `dbstop'
 
781
function.
 
782
 
 
783
 -- Loadable Function: rline = dbstop (FUNC, LINE, ...)
 
784
     Set a breakpoint in a function
 
785
    `func'
 
786
          String representing the function name.  When already in debug
 
787
          mode this should be left out and only the line should be
 
788
          given.
 
789
 
 
790
    `line'
 
791
          Line you would like the breakpoint to be set on. Multiple
 
792
          lines might be given as separate arguments or as a vector.
 
793
 
 
794
     The rline returned is the real line that the breakpoint was set at.
 
795
 
 
796
     *See also:* dbclear, dbstatus, dbnext.
 
797
 
 
798
Note that breakpoints can not be set in built-in functions (eg. `sin',
 
799
etc) or dynamically loaded function (ie. oct-files). To set a
 
800
breakpoint immediately on entering a function, the breakpoint should be
 
801
set to line 1. The leading comment block will be ignored and the
 
802
breakpoint will be set to the first executable statement in the
 
803
function. For example
 
804
 
 
805
     dbstop ("asind", 1)
 
806
     => 27
 
807
 
 
808
Note that the return value of `27' means that the breakpoint was
 
809
effectively set to line 27. The status of breakpoints in a function can
 
810
be queried with the `dbstatus' function.
 
811
 
 
812
 -- Loadable Function: lst = dbstatus (FUNC)
 
813
     Return a vector containing the lines on which a function has
 
814
     breakpoints set.
 
815
    `func'
 
816
          String representing the function name.  When already in debug
 
817
          mode this should be left out.
 
818
 
 
819
 
 
820
     *See also:* dbclear, dbwhere.
 
821
 
 
822
Taking the above as an example, `dbstatus ("asind")' should return 27.
 
823
The breakpoints can then be cleared with the `dbclear' function
 
824
 
 
825
 -- Loadable Function:  dbclear (FUNC, LINE, ...)
 
826
     Delete a breakpoint in a function
 
827
    `func'
 
828
          String representing the function name.  When already in debug
 
829
          mode this should be left out and only the line should be
 
830
          given.
 
831
 
 
832
    `line'
 
833
          Line where you would like to remove the breakpoint. Multiple
 
834
          lines might be given as separate arguments or as a vector.
 
835
     No checking is done to make sure that the line you requested is
 
836
     really a breakpoint. If you get the wrong line nothing will happen.
 
837
 
 
838
     *See also:* dbstop, dbstatus, dbwhere.
 
839
 
 
840
To clear all of the breakpoints in a function the recommended means,
 
841
following the above example, is then
 
842
 
 
843
     dbclear ("asind", dbstatus ("asind"));
 
844
 
 
845
   Another simple means of setting a breakpoint in an Octave script is
 
846
the use of the `keyboard' function.
 
847
 
 
848
 -- Built-in Function:  keyboard (PROMPT)
 
849
     This function is normally used for simple debugging.  When the
 
850
     `keyboard' function is executed, Octave prints a prompt and waits
 
851
     for user input.  The input strings are then evaluated and the
 
852
     results are printed.  This makes it possible to examine the values
 
853
     of variables within a function, and to assign new values to
 
854
     variables.  No value is returned from the `keyboard' function, and
 
855
     it continues to prompt for input until the user types `quit', or
 
856
     `exit'.
 
857
 
 
858
     If `keyboard' is invoked without any arguments, a default prompt of
 
859
     `debug> ' is used.
 
860
 
 
861
The `keyboard' function is typically placed in a script at the point
 
862
where the user desires that the execution is stopped. It automatically
 
863
sets the running script into the debug mode.
 
864
 
 
865
 
 
866
File: octave.info,  Node: Debug Mode,  Prev: Breakpoints,  Up: Debugging
 
867
 
 
868
13.3 Debug Mode
 
869
===============
 
870
 
 
871
There are two additional support functions that allow the user to
 
872
interrogate where in the execution of a script Octave entered the debug
 
873
mode and to print the code in the script surrounding the point where
 
874
Octave entered debug mode.
 
875
 
 
876
 -- Loadable Function:  dbwhere ()
 
877
     Show where we are in the code
 
878
 
 
879
     *See also:* dbclear, dbstatus, dbstop.
 
880
 
 
881
 -- Loadable Function:  dbtype ()
 
882
     List script file with line numbers.
 
883
 
 
884
     *See also:* dbclear, dbstatus, dbstop.
 
885
 
 
886
   Debug mode equally allows single line stepping through a function
 
887
using the commands `dbstep' and `dbnext'.  These differ slightly in the
 
888
way they treat the next executable line if the next line itself is a
 
889
function defined in an m-file.  The `dbnext' command will execute the
 
890
next line, while staying in the existing function being debugged.  The
 
891
`dbstep' command will step in to the new function.
 
892
 
 
893
 
 
894
File: octave.info,  Node: Input and Output,  Next: Plotting,  Prev: Debugging,  Up: Top
 
895
 
 
896
14 Input and Output
 
897
*******************
 
898
 
 
899
Octave supports several ways of reading and writing data to or from the
 
900
prompt or a file.  The most simple functions for data Input and Output
 
901
(I/O) are easy to use, but only provides a limited control of how data
 
902
is processed.  For more control, a set of functions modelled after the
 
903
C standard library are also provided by Octave.
 
904
 
 
905
* Menu:
 
906
 
 
907
* Basic Input and Output::
 
908
* C-Style I/O Functions::
 
909
 
 
910
 
 
911
File: octave.info,  Node: Basic Input and Output,  Next: C-Style I/O Functions,  Up: Input and Output
 
912
 
 
913
14.1 Basic Input and Output
 
914
===========================
 
915
 
 
916
* Menu:
 
917
 
 
918
* Terminal Output::
 
919
* Terminal Input::
 
920
* Simple File I/O::
 
921
* Rational Approximations::
 
922
 
 
923
 
 
924
File: octave.info,  Node: Terminal Output,  Next: Terminal Input,  Up: Basic Input and Output
 
925
 
 
926
14.1.1 Terminal Output
 
927
----------------------
 
928
 
 
929
Since Octave normally prints the value of an expression as soon as it
 
930
has been evaluated, the simplest of all I/O functions is a simple
 
931
expression.  For example, the following expression will display the
 
932
value of `pi'
 
933
 
 
934
     pi
 
935
          -| pi = 3.1416
 
936
 
 
937
   This works well as long as it is acceptable to have the name of the
 
938
variable (or `ans') printed along with the value.  To print the value
 
939
of a variable without printing its name, use the function `disp'.
 
940
 
 
941
   The `format' command offers some control over the way Octave prints
 
942
values with `disp' and through the normal echoing mechanism.
 
943
 
 
944
 -- Automatic Variable: ans
 
945
     The most recently computed result that was not explicitly assigned
 
946
     to a variable.  For example, after the expression
 
947
 
 
948
          3^2 + 4^2
 
949
 
 
950
     is evaluated, the value returned by `ans' is 25.
 
951
 
 
952
 -- Built-in Function:  disp (X)
 
953
     Display the value of X.  For example,
 
954
 
 
955
          disp ("The value of pi is:"), disp (pi)
 
956
 
 
957
               -| the value of pi is:
 
958
               -| 3.1416
 
959
 
 
960
     Note that the output from `disp' always ends with a newline.
 
961
 
 
962
     If an output value is requested, `disp' prints nothing and returns
 
963
     the formatted output in a string.
 
964
 
 
965
     *See also:* fdisp.
 
966
 
 
967
 -- Command: format options
 
968
     Control the format of the output produced by `disp' and Octave's
 
969
     normal echoing mechanism.  Valid options are listed in the
 
970
     following table.
 
971
 
 
972
    `short'
 
973
          Octave will try to print numbers with at least 5 significant
 
974
          figures within a field that is a maximum of 10 characters
 
975
          wide (not counting additional spacing that is added between
 
976
          columns of a matrix).
 
977
 
 
978
          If Octave is unable to format a matrix so that columns line
 
979
          up on the decimal point and all the numbers fit within the
 
980
          maximum field width, it switches to an `e' format.
 
981
 
 
982
    `long'
 
983
          Octave will try to print numbers with at least 15 significant
 
984
          figures within a field that is a maximum of 20 characters
 
985
          wide (not counting additional spacing that is added between
 
986
          columns of a matrix).
 
987
 
 
988
          As will the `short' format, Octave will switch to an `e'
 
989
          format if it is unable to format a matrix so that columns
 
990
          line up on the decimal point and all the numbers fit within
 
991
          the maximum field width.
 
992
 
 
993
    `long e'
 
994
    `short e'
 
995
          The same as `format long' or `format short' but always display
 
996
          output with an `e' format.  For example, with the `short e'
 
997
          format, `pi' is displayed as `3.14e+00'.
 
998
 
 
999
    `long E'
 
1000
    `short E'
 
1001
          The same as `format long e' or `format short e' but always
 
1002
          display output with an uppercase `E' format.  For example,
 
1003
          with the `long E' format, `pi' is displayed as
 
1004
          `3.14159265358979E+00'.
 
1005
 
 
1006
    `long g'
 
1007
    `short g'
 
1008
          Choose between normal `long' (or `short') and `long e' (or
 
1009
          `short e') formats based on the magnitude of the number.  For
 
1010
          example, with the `short g' format, `pi .^ [2; 4; 8; 16; 32]'
 
1011
          is displayed as
 
1012
 
 
1013
               ans =
 
1014
 
 
1015
                     9.8696
 
1016
                     97.409
 
1017
                     9488.5
 
1018
                 9.0032e+07
 
1019
                 8.1058e+15
 
1020
 
 
1021
    `long G'
 
1022
    `short G'
 
1023
          The same as `format long g' or `format short g' but use an
 
1024
          uppercase `E' format.  For example, with the `short G' format,
 
1025
          `pi .^ [2; 4; 8; 16; 32]' is displayed as
 
1026
 
 
1027
               ans =
 
1028
 
 
1029
                     9.8696
 
1030
                     97.409
 
1031
                     9488.5
 
1032
                 9.0032E+07
 
1033
                 8.1058E+15
 
1034
 
 
1035
    `free'
 
1036
    `none'
 
1037
          Print output in free format, without trying to line up
 
1038
          columns of matrices on the decimal point.  This also causes
 
1039
          complex numbers to be formatted like this `(0.604194,
 
1040
          0.607088)' instead of like this `0.60419 + 0.60709i'.
 
1041
 
 
1042
    `bank'
 
1043
          Print in a fixed format with two places to the right of the
 
1044
          decimal point.
 
1045
 
 
1046
    `+'
 
1047
    `+ CHARS'
 
1048
    `plus'
 
1049
    `plus CHARS'
 
1050
          Print a `+' symbol for nonzero matrix elements and a space
 
1051
          for zero matrix elements.  This format can be very useful for
 
1052
          examining the structure of a large matrix.
 
1053
 
 
1054
          The optional argument CHARS specifies a list of 3 characters
 
1055
          to use for printing values greater than zero, less than zero
 
1056
          and equal to zero.  For example, with the `+ "+-."' format,
 
1057
          `[1, 0, -1; -1, 0, 1]' is displayed as
 
1058
 
 
1059
               ans =
 
1060
 
 
1061
               +.-
 
1062
               -.+
 
1063
 
 
1064
    `native-hex'
 
1065
          Print the hexadecimal representation numbers as they are
 
1066
          stored in memory.  For example, on a workstation which stores
 
1067
          8 byte real values in IEEE format with the least significant
 
1068
          byte first, the value of `pi' when printed in `hex' format is
 
1069
          `400921fb54442d18'.  This format only works for numeric
 
1070
          values.
 
1071
 
 
1072
    `hex'
 
1073
          The same as `native-hex', but always print the most
 
1074
          significant byte first.
 
1075
 
 
1076
    `native-bit'
 
1077
          Print the bit representation of numbers as stored in memory.
 
1078
          For example, the value of `pi' is
 
1079
 
 
1080
               01000000000010010010000111111011
 
1081
               01010100010001000010110100011000
 
1082
 
 
1083
          (shown here in two 32 bit sections for typesetting purposes)
 
1084
          when printed in bit format on a workstation which stores 8
 
1085
          byte real values in IEEE format with the least significant
 
1086
          byte first.  This format only works for numeric types.
 
1087
 
 
1088
    `bit'
 
1089
          The same as `native-bit', but always print the most
 
1090
          significant bits first.
 
1091
 
 
1092
    `compact'
 
1093
          Remove extra blank space around column number labels.
 
1094
 
 
1095
    `loose'
 
1096
          Insert blank lines above and below column number labels (this
 
1097
          is the default).
 
1098
 
 
1099
    `rat'
 
1100
          Print a rational approximation. That is the values are
 
1101
          approximated by one small integer divided by another.
 
1102
 
 
1103
     By default, Octave will try to print numbers with at least 5
 
1104
     significant figures within a field that is a maximum of 10
 
1105
     characters wide.
 
1106
 
 
1107
     If Octave is unable to format a matrix so that columns line up on
 
1108
     the decimal point and all the numbers fit within the maximum field
 
1109
     width, it switches to an `e' format.
 
1110
 
 
1111
     If `format' is invoked without any options, the default format
 
1112
     state is restored.
 
1113
 
 
1114
 -- Built-in Function: VAL = print_answer_id_name ()
 
1115
 -- Built-in Function: OLD_VAL = print_answer_id_name (NEW_VAL)
 
1116
     Query or set the internal variable that controls whether variable
 
1117
     names are printed along with results produced by evaluating an
 
1118
     expression.
 
1119
 
 
1120
* Menu:
 
1121
 
 
1122
* Paging Screen Output::
 
1123
 
 
1124
 
 
1125
File: octave.info,  Node: Paging Screen Output,  Up: Terminal Output
 
1126
 
 
1127
14.1.1.1 Paging Screen Output
 
1128
.............................
 
1129
 
 
1130
When running interactively, Octave normally sends any output intended
 
1131
for your terminal that is more than one screen long to a paging program,
 
1132
such as `less' or `more'.  This avoids the problem of having a large
 
1133
volume of output stream by before you can read it.  With `less' (and
 
1134
some versions of `more') you can also scan forward and backward, and
 
1135
search for specific items.
 
1136
 
 
1137
   Normally, no output is displayed by the pager until just before
 
1138
Octave is ready to print the top level prompt, or read from the
 
1139
standard input (for example, by using the `fscanf' or `scanf'
 
1140
functions).  This means that there may be some delay before any output
 
1141
appears on your screen if you have asked Octave to perform a
 
1142
significant amount of work with a single command statement.  The
 
1143
function `fflush' may be used to force output to be sent to the pager
 
1144
(or any other stream) immediately.
 
1145
 
 
1146
   You can select the program to run as the pager using the `PAGER'
 
1147
function, and you can turn paging off by using the function `more'.
 
1148
 
 
1149
 -- Command: more
 
1150
 -- Command: more on
 
1151
 -- Command: more off
 
1152
     Turn output pagination on or off.  Without an argument, `more'
 
1153
     toggles the current state.
 
1154
 
 
1155
 -- Built-in Function: VAL = PAGER ()
 
1156
 -- Built-in Function: OLD_VAL = PAGER (NEW_VAL)
 
1157
     Query or set the internal variable that specifies the program to
 
1158
     use to display terminal output on your system.  The default value
 
1159
     is normally `"less"', `"more"', or `"pg"', depending on what
 
1160
     programs are installed on your system.  *Note Installation::.
 
1161
 
 
1162
     *See also:* more, page_screen_output, page_output_immediately,
 
1163
     PAGER_FLAGS.
 
1164
 
 
1165
 -- Built-in Function: VAL = PAGER_FLAGS ()
 
1166
 -- Built-in Function: OLD_VAL = PAGER_FLAGS (NEW_VAL)
 
1167
     Query or set the internal variable that specifies the options to
 
1168
     pass to the pager.
 
1169
 
 
1170
     *See also:* PAGER.
 
1171
 
 
1172
 -- Built-in Function: VAL = page_screen_output ()
 
1173
 -- Built-in Function: OLD_VAL = page_screen_output (NEW_VAL)
 
1174
     Query or set the internal variable that controls whether output
 
1175
     intended for the terminal window that is longer than one page is
 
1176
     sent through a pager.  This allows you to view one screenful at a
 
1177
     time.  Some pagers (such as `less'--see *note Installation::) are
 
1178
     also capable of moving backward on the output.
 
1179
 
 
1180
 -- Built-in Function: VAL = page_output_immediately ()
 
1181
 -- Built-in Function: VAL = page_output_immediately (NEW_VAL)
 
1182
     Query or set the internal variable that controls whether Octave
 
1183
     sends output to the pager as soon as it is available.  Otherwise,
 
1184
     Octave buffers its output and waits until just before the prompt
 
1185
     is printed to flush it to the pager.
 
1186
 
 
1187
 -- Built-in Function:  fflush (FID)
 
1188
     Flush output to FID.  This is useful for ensuring that all pending
 
1189
     output makes it to the screen before some other event occurs.  For
 
1190
     example, it is always a good idea to flush the standard output
 
1191
     stream before calling `input'.
 
1192
 
 
1193
     `fflush' returns 0 on success and an OS dependent error value (-1
 
1194
     on unix) on error.
 
1195
 
 
1196
     *See also:* fopen, fclose.
 
1197
 
 
1198
 
 
1199
File: octave.info,  Node: Terminal Input,  Next: Simple File I/O,  Prev: Terminal Output,  Up: Basic Input and Output
 
1200
 
 
1201
14.1.2 Terminal Input
 
1202
---------------------
 
1203
 
 
1204
Octave has three functions that make it easy to prompt users for input.
 
1205
The `input' and `menu' functions are normally used for managing an
 
1206
interactive dialog with a user, and the `keyboard' function is normally
 
1207
used for doing simple debugging.
 
1208
 
 
1209
 -- Built-in Function:  input (PROMPT)
 
1210
 -- Built-in Function:  input (PROMPT, "s")
 
1211
     Print a prompt and wait for user input.  For example,
 
1212
 
 
1213
          input ("Pick a number, any number! ")
 
1214
 
 
1215
     prints the prompt
 
1216
 
 
1217
          Pick a number, any number!
 
1218
 
 
1219
     and waits for the user to enter a value.  The string entered by
 
1220
     the user is evaluated as an expression, so it may be a literal
 
1221
     constant, a variable name, or any other valid expression.
 
1222
 
 
1223
     Currently, `input' only returns one value, regardless of the number
 
1224
     of values produced by the evaluation of the expression.
 
1225
 
 
1226
     If you are only interested in getting a literal string value, you
 
1227
     can call `input' with the character string `"s"' as the second
 
1228
     argument.  This tells Octave to return the string entered by the
 
1229
     user directly, without evaluating it first.
 
1230
 
 
1231
     Because there may be output waiting to be displayed by the pager,
 
1232
     it is a good idea to always call `fflush (stdout)' before calling
 
1233
     `input'.  This will ensure that all pending output is written to
 
1234
     the screen before your prompt.  *Note Input and Output::.
 
1235
 
 
1236
 -- Function File:  menu (TITLE, OPT1, ...)
 
1237
     Print a title string followed by a series of options.  Each option
 
1238
     will be printed along with a number.  The return value is the
 
1239
     number of the option selected by the user.  This function is
 
1240
     useful for interactive programs.  There is no limit to the number
 
1241
     of options that may be passed in, but it may be confusing to
 
1242
     present more than will fit easily on one screen.
 
1243
 
 
1244
     *See also:* disp, printf, input.
 
1245
 
 
1246
   For `input', the normal command line history and editing functions
 
1247
are available at the prompt.
 
1248
 
 
1249
   Octave also has a function that makes it possible to get a single
 
1250
character from the keyboard without requiring the user to type a
 
1251
carriage return.
 
1252
 
 
1253
 -- Built-in Function:  kbhit ()
 
1254
     Read a single keystroke from the keyboard. If called with one
 
1255
     argument, don't wait for a keypress.  For example,
 
1256
 
 
1257
          x = kbhit ();
 
1258
 
 
1259
     will set X to the next character typed at the keyboard as soon as
 
1260
     it is typed.
 
1261
 
 
1262
          x = kbhit (1);
 
1263
 
 
1264
     identical to the above example, but don't wait for a keypress,
 
1265
     returning the empty string if no key is available.
 
1266
 
 
1267
 
 
1268
File: octave.info,  Node: Simple File I/O,  Next: Rational Approximations,  Prev: Terminal Input,  Up: Basic Input and Output
 
1269
 
 
1270
14.1.3 Simple File I/O
 
1271
----------------------
 
1272
 
 
1273
The `save' and `load' commands allow data to be written to and read
 
1274
from disk files in various formats.  The default format of files
 
1275
written by the `save' command can be controlled using the functions
 
1276
`default_save_options' and `save_precision'.
 
1277
 
 
1278
   As an example the following code creates a 3-by-3 matrix and saves it
 
1279
to the file `myfile.mat'.
 
1280
 
 
1281
     A = [ 1:3; 4:6; 7:9 ];
 
1282
     save myfile.mat A
 
1283
 
 
1284
   Once one or more variables have been saved to a file, they can be
 
1285
read into memory using the `load' command.
 
1286
 
 
1287
     load myfile.mat
 
1288
     A
 
1289
          -| A =
 
1290
          -|
 
1291
          -|    1   2   3
 
1292
          -|    4   5   6
 
1293
          -|    7   8   9
 
1294
 
 
1295
 -- Command: save options file V1 V2 ...
 
1296
     Save the named variables V1, V2, ..., in the file FILE.  The
 
1297
     special filename `-' can be used to write the output to your
 
1298
     terminal.  If no variable names are listed, Octave saves all the
 
1299
     variables in the current scope.  Valid options for the `save'
 
1300
     command are listed in the following table.  Options that modify
 
1301
     the output format override the format specified by
 
1302
     `default_save_options'.
 
1303
 
 
1304
     If save is invoked using the functional form
 
1305
 
 
1306
          save ("-option1", ..., "file", "v1", ...)
 
1307
 
 
1308
     then the OPTIONS, FILE, and variable name arguments (V1, ...) must
 
1309
     be specified as character strings.
 
1310
 
 
1311
    `-ascii'
 
1312
          Save a single matrix in a text file.
 
1313
 
 
1314
    `-binary'
 
1315
          Save the data in Octave's binary data format.
 
1316
 
 
1317
    `-float-binary'
 
1318
          Save the data in Octave's binary data format but only using
 
1319
          single precision.  You should use this format only if you
 
1320
          know that all the values to be saved can be represented in
 
1321
          single precision.
 
1322
 
 
1323
    `-V7'
 
1324
    `-v7'
 
1325
    `-7'
 
1326
    `-mat7-binary'
 
1327
          Save the data in MATLAB's v7 binary data format.
 
1328
 
 
1329
    `-V6'
 
1330
    `-v6'
 
1331
    `-6'
 
1332
    `-mat'
 
1333
    `-mat-binary'
 
1334
          Save the data in MATLAB's v6 binary data format.
 
1335
 
 
1336
    `-V4'
 
1337
    `-v4'
 
1338
    `-4'
 
1339
    `-mat4-binary'
 
1340
          Save the data in the binary format written by MATLAB version
 
1341
          4.
 
1342
 
 
1343
    `-hdf5'
 
1344
          Save the data in HDF5 format.  (HDF5 is a free, portable
 
1345
          binary format developed by the National Center for
 
1346
          Supercomputing Applications at the University of Illinois.)
 
1347
 
 
1348
    `-float-hdf5'
 
1349
          Save the data in HDF5 format but only using single precision.
 
1350
          You should use this format only if you know that all the
 
1351
          values to be saved can be represented in single precision.
 
1352
 
 
1353
    `-zip'
 
1354
    `-z'
 
1355
          Use the gzip algorithm to compress the file. This works
 
1356
          equally on files that are compressed with gzip outside of
 
1357
          octave, and gzip can equally be used to convert the files for
 
1358
          backward compatibility.
 
1359
 
 
1360
     The list of variables to save may include wildcard patterns
 
1361
     containing the following special characters:
 
1362
    `?'
 
1363
          Match any single character.
 
1364
 
 
1365
    `*'
 
1366
          Match zero or more characters.
 
1367
 
 
1368
    `[ LIST ]'
 
1369
          Match the list of characters specified by LIST.  If the first
 
1370
          character is `!' or `^', match all characters except those
 
1371
          specified by LIST.  For example, the pattern `[a-zA-Z]' will
 
1372
          match all lower and upper case alphabetic characters.
 
1373
 
 
1374
    `-text'
 
1375
          Save the data in Octave's text data format.
 
1376
 
 
1377
     Except when using the MATLAB binary data file format, saving global
 
1378
     variables also saves the global status of the variable, so that if
 
1379
     it is restored at a later time using `load', it will be restored
 
1380
     as a global variable.
 
1381
 
 
1382
     The command
 
1383
 
 
1384
          save -binary data a b*
 
1385
 
 
1386
     saves the variable `a' and all variables beginning with `b' to the
 
1387
     file `data' in Octave's binary format.
 
1388
 
 
1389
 -- Command: load options file v1 v2 ...
 
1390
     Load the named variables V1, V2, ..., from the file FILE.  As with
 
1391
     `save', you may specify a list of variables and `load' will only
 
1392
     extract those variables with names that match.  For example, to
 
1393
     restore the variables saved in the file `data', use the command
 
1394
 
 
1395
          load data
 
1396
 
 
1397
     If load is invoked using the functional form
 
1398
 
 
1399
          load ("-option1", ..., "file", "v1", ...)
 
1400
 
 
1401
     then the OPTIONS, FILE, and variable name arguments (V1, ...) must
 
1402
     be specified as character strings.
 
1403
 
 
1404
     If a variable that is not marked as global is loaded from a file
 
1405
     when a global symbol with the same name already exists, it is
 
1406
     loaded in the global symbol table.  Also, if a variable is marked
 
1407
     as global in a file and a local symbol exists, the local symbol is
 
1408
     moved to the global symbol table and given the value from the
 
1409
     file.  Since it seems that both of these cases are likely to be
 
1410
     the result of some sort of error, they will generate warnings.
 
1411
 
 
1412
     If invoked with a single output argument, Octave returns data
 
1413
     instead of inserting variables in the symbol table.  If the data
 
1414
     file contains only numbers (TAB- or space-delimited columns), a
 
1415
     matrix of values is returned.  Otherwise, `load' returns a
 
1416
     structure with members  corresponding to the names of the
 
1417
     variables in the file.
 
1418
 
 
1419
     The `load' command can read data stored in Octave's text and
 
1420
     binary formats, and MATLAB's binary format.  It will automatically
 
1421
     detect the type of file and do conversion from different floating
 
1422
     point formats (currently only IEEE big and little endian, though
 
1423
     other formats may added in the future).
 
1424
 
 
1425
     Valid options for `load' are listed in the following table.
 
1426
 
 
1427
    `-force'
 
1428
          The `-force' option is accepted but ignored for backward
 
1429
          compatibility. Octave now overwrites variables currently in
 
1430
          memory with the same name as those found in the file.
 
1431
 
 
1432
    `-ascii'
 
1433
          Force Octave to assume the file contains columns of numbers
 
1434
          in text format without any header or other information.  Data
 
1435
          in the file will be loaded as a single numeric matrix with
 
1436
          the name of the variable derived from the name of the file.
 
1437
 
 
1438
    `-binary'
 
1439
          Force Octave to assume the file is in Octave's binary format.
 
1440
 
 
1441
    `-mat'
 
1442
    `-mat-binary'
 
1443
    `-6'
 
1444
    `-v6'
 
1445
    `-7'
 
1446
    `-v7'
 
1447
          Force Octave to assume the file is in MATLAB's version 6 or 7
 
1448
          binary format.
 
1449
 
 
1450
    `-V4'
 
1451
    `-v4'
 
1452
    `-4'
 
1453
    `-mat4-binary'
 
1454
          Force Octave to assume the file is in the binary format
 
1455
          written by MATLAB version 4.
 
1456
 
 
1457
    `-hdf5'
 
1458
          Force Octave to assume the file is in HDF5 format.  (HDF5 is
 
1459
          a free, portable binary format developed by the National
 
1460
          Center for Supercomputing Applications at the University of
 
1461
          Illinois.)  Note that Octave can read HDF5 files not created
 
1462
          by itself, but may skip some datasets in formats that it
 
1463
          cannot support.
 
1464
 
 
1465
    `-import'
 
1466
          The `-import' is accepted but ignored for backward
 
1467
          compatibility.  Octave can now support multi-dimensional HDF
 
1468
          data and automatically modifies variable names if they are
 
1469
          invalid Octave identifiers.
 
1470
 
 
1471
    `-text'
 
1472
          Force Octave to assume the file is in Octave's text format.
 
1473
 
 
1474
   There are three functions that modify the behavior of `save'.
 
1475
 
 
1476
 -- Built-in Function: VAL = default_save_options ()
 
1477
 -- Built-in Function: OLD_VAL = default_save_options (NEW_VAL)
 
1478
     Query or set the internal variable that specifies the default
 
1479
     options for the `save' command, and defines the default format.
 
1480
     Typical values include `"-ascii"', `"-ascii -zip"'.  The default
 
1481
     value is `-ascii'.
 
1482
 
 
1483
     *See also:* save.
 
1484
 
 
1485
 -- Built-in Function: VAL = save_precision ()
 
1486
 -- Built-in Function: OLD_VAL = save_precision (NEW_VAL)
 
1487
     Query or set the internal variable that specifies the number of
 
1488
     digits to keep when saving data in text format.
 
1489
 
 
1490
 -- Built-in Function: VAL = save_header_format_string ()
 
1491
 -- Built-in Function: OLD_VAL = save_header_format_string (NEW_VAL)
 
1492
     Query or set the internal variable that specifies the format
 
1493
     string used for the comment line written at the beginning of
 
1494
     text-format data files saved by Octave.  The format string is
 
1495
     passed to `strftime' and should begin with the character `#' and
 
1496
     contain no newline characters.  If the value of
 
1497
     `save_header_format_string' is the empty string, the header
 
1498
     comment is omitted from text-format data files.  The default value
 
1499
     is
 
1500
 
 
1501
          "# Created by Octave VERSION, %a %b %d %H:%M:%S %Y %Z <USER@HOST>"
 
1502
 
 
1503
 
 
1504
     *See also:* strftime.
 
1505
 
 
1506
 -- Built-in Function:  native_float_format ()
 
1507
     Return the native floating point format as a string
 
1508
 
 
1509
   It is possible to write data to a file in a way much similar to the
 
1510
`disp' function for writing data to the screen.  The `fdisp' works just
 
1511
like `disp' except its first argument is a file pointer as created by
 
1512
`fopen'.  As an example, the following code writes to data `myfile.txt'.
 
1513
 
 
1514
     fid = fopen ("myfile.txt", "w");
 
1515
     fdisp (fid, "3/8 is ");
 
1516
     fdisp (fid, 3/8);
 
1517
     fclose (fid);
 
1518
 
 
1519
*Note Opening and Closing Files::, for details on how to use `fopen'
 
1520
and `fclose'.
 
1521
 
 
1522
 -- Built-in Function:  fdisp (FID, X)
 
1523
     Display the value of X on the stream FID.  For example,
 
1524
 
 
1525
          fdisp (stdout, "The value of pi is:"), fdisp (stdout, pi)
 
1526
 
 
1527
               -| the value of pi is:
 
1528
               -| 3.1416
 
1529
 
 
1530
     Note that the output from `fdisp' always ends with a newline.
 
1531
 
 
1532
     *See also:* disp.
 
1533
 
 
1534
* Menu:
 
1535
 
 
1536
* Saving Data on Unexpected Exits::
 
1537
 
 
1538
 
 
1539
File: octave.info,  Node: Saving Data on Unexpected Exits,  Up: Simple File I/O
 
1540
 
 
1541
14.1.3.1 Saving Data on Unexpected Exits
 
1542
........................................
 
1543
 
 
1544
If Octave for some reason exits unexpected it will by default save the
 
1545
variables available in the workspace to a file in the current directory.
 
1546
By default this file is named `octave-core' and can be loaded into
 
1547
memory with the `load' command.  While the default behaviour most often
 
1548
is reasonable it can be changed through the following functions.
 
1549
 
 
1550
 -- Built-in Function: VAL = crash_dumps_octave_core ()
 
1551
 -- Built-in Function: OLD_VAL = crash_dumps_octave_core (NEW_VAL)
 
1552
     Query or set the internal variable that controls whether Octave
 
1553
     tries to save all current variables to the file "octave-core" if it
 
1554
     crashes or receives a hangup, terminate or similar signal.
 
1555
 
 
1556
     *See also:* octave_core_file_limit, octave_core_file_name,
 
1557
     octave_core_file_options.
 
1558
 
 
1559
 -- Built-in Function: VAL = sighup_dumps_octave_core ()
 
1560
 -- Built-in Function: OLD_VAL = sighup_dumps_octave_core (NEW_VAL)
 
1561
     Query or set the internal variable that controls whether Octave
 
1562
     tries to save all current variables to the file "octave-core" if
 
1563
     it receives a hangup signal.
 
1564
 
 
1565
 -- Built-in Function: VAL = sigterm_dumps_octave_core ()
 
1566
 -- Built-in Function: OLD_VAL = sigterm_dumps_octave_core (NEW_VAL)
 
1567
     Query or set the internal variable that controls whether Octave
 
1568
     tries to save all current variables to the file "octave-core" if
 
1569
     it receives a terminate signal.
 
1570
 
 
1571
 -- Built-in Function: VAL = octave_core_file_options ()
 
1572
 -- Built-in Function: OLD_VAL = octave_core_file_options (NEW_VAL)
 
1573
     Query or set the internal variable that specifies the options used
 
1574
     for saving the workspace data if Octave aborts.  The value of
 
1575
     `octave_core_file_options' should follow the same format as the
 
1576
     options for the `save' function. The default value is Octave's
 
1577
     binary format.
 
1578
 
 
1579
     *See also:* crash_dumps_octave_core, octave_core_file_name,
 
1580
     octave_core_file_limit.
 
1581
 
 
1582
 -- Built-in Function: VAL = octave_core_file_limit ()
 
1583
 -- Built-in Function: OLD_VAL = octave_core_file_limit (NEW_VAL)
 
1584
     Query or set the internal variable that specifies the maximum
 
1585
     amount of memory (in kilobytes) of the top-level workspace that
 
1586
     Octave will attempt to save when writing data to the crash dump
 
1587
     file (the name of the file is specified by OCTAVE_CORE_FILE_NAME).
 
1588
     If OCTAVE_CORE_FILE_OPTIONS flags specify a binary format, then
 
1589
     OCTAVE_CORE_FILE_LIMIT will be approximately the maximum size of
 
1590
     the file.  If a text file format is used, then the file could be
 
1591
     much larger than the limit.  The default value is -1 (unlimited)
 
1592
 
 
1593
     *See also:* crash_dumps_octave_core, octave_core_file_name,
 
1594
     octave_core_file_options.
 
1595
 
 
1596
 -- Built-in Function: VAL = octave_core_file_name ()
 
1597
 -- Built-in Function: OLD_VAL = octave_core_file_name (NEW_VAL)
 
1598
     Query or set the internal variable that specifies the name of the
 
1599
     file used for saving data from the top-level workspace if Octave
 
1600
     aborts.  The default value is `"octave-core"'
 
1601
 
 
1602
     *See also:* crash_dumps_octave_core, octave_core_file_name,
 
1603
     octave_core_file_options.
 
1604
 
 
1605
 
 
1606
File: octave.info,  Node: Rational Approximations,  Prev: Simple File I/O,  Up: Basic Input and Output
 
1607
 
 
1608
14.1.4 Rational Approximations
 
1609
------------------------------
 
1610
 
 
1611
 -- Function File: S = rat (X, TOL)
 
1612
 -- Function File: [N, D] = rat (X, TOL)
 
1613
     Find a rational approximation to X within tolerance defined by TOL
 
1614
     using a continued fraction expansion. E.g,
 
1615
 
 
1616
          rat(pi) = 3 + 1/(7 + 1/16) = 355/113
 
1617
          rat(e) = 3 + 1/(-4 + 1/(2 + 1/(5 + 1/(-2 + 1/(-7)))))
 
1618
                 = 1457/536
 
1619
 
 
1620
     Called with two arguments returns the numerator and denominator
 
1621
     separately as two matrices.
 
1622
 
 
1623
 
 
1624
*See also:* rats.
 
1625
 
 
1626
 -- Built-in Function:  rats (X, LEN)
 
1627
     Convert X into a rational approximation represented as a string.
 
1628
     You can convert the string back into a matrix as follows:
 
1629
 
 
1630
             r = rats(hilb(4));
 
1631
             x = str2num(r)
 
1632
 
 
1633
     The optional second argument defines the maximum length of the
 
1634
     string representing the elements of X. By default LEN is 9.
 
1635
 
 
1636
     *See also:* format, rat.
 
1637
 
 
1638
 
 
1639
File: octave.info,  Node: C-Style I/O Functions,  Prev: Basic Input and Output,  Up: Input and Output
 
1640
 
 
1641
14.2 C-Style I/O Functions
 
1642
==========================
 
1643
 
 
1644
Octave's C-style input and output functions provide most of the
 
1645
functionality of the C programming language's standard I/O library.  The
 
1646
argument lists for some of the input functions are slightly different,
 
1647
however, because Octave has no way of passing arguments by reference.
 
1648
 
 
1649
   In the following, FILE refers to a file name and `fid' refers to an
 
1650
integer file number, as returned by `fopen'.
 
1651
 
 
1652
   There are three files that are always available.  Although these
 
1653
files can be accessed using their corresponding numeric file ids, you
 
1654
should always use the symbolic names given in the table below, since it
 
1655
will make your programs easier to understand.
 
1656
 
 
1657
 -- Built-in Function:  stdin ()
 
1658
     Return the numeric value corresponding to the standard input
 
1659
     stream.  When Octave is used interactively, this is filtered
 
1660
     through the command line editing functions.
 
1661
 
 
1662
     *See also:* stdout, stderr.
 
1663
 
 
1664
 -- Built-in Function:  stdout ()
 
1665
     Return the numeric value corresponding to the standard output
 
1666
     stream.  Data written to the standard output is normally filtered
 
1667
     through the pager.
 
1668
 
 
1669
     *See also:* stdin, stderr.
 
1670
 
 
1671
 -- Built-in Function:  stderr ()
 
1672
     Return the numeric value corresponding to the standard error
 
1673
     stream.  Even if paging is turned on, the standard error is not
 
1674
     sent to the pager.  It is useful for error messages and prompts.
 
1675
 
 
1676
     *See also:* stdin, stdout.
 
1677
 
 
1678
* Menu:
 
1679
 
 
1680
* Opening and Closing Files::
 
1681
* Simple Output::
 
1682
* Line-Oriented Input::
 
1683
* Formatted Output::
 
1684
* Output Conversion for Matrices::
 
1685
* Output Conversion Syntax::
 
1686
* Table of Output Conversions::
 
1687
* Integer Conversions::
 
1688
* Floating-Point Conversions::  Other Output Conversions::
 
1689
* Other Output Conversions::
 
1690
* Formatted Input::
 
1691
* Input Conversion Syntax::
 
1692
* Table of Input Conversions::
 
1693
* Numeric Input Conversions::
 
1694
* String Input Conversions::
 
1695
* Binary I/O::
 
1696
* Temporary Files::
 
1697
* EOF and Errors::
 
1698
* File Positioning::
 
1699
 
 
1700
 
 
1701
File: octave.info,  Node: Opening and Closing Files,  Next: Simple Output,  Up: C-Style I/O Functions
 
1702
 
 
1703
14.2.1 Opening and Closing Files
 
1704
--------------------------------
 
1705
 
 
1706
When reading data from a file it must be opened for reading first, and
 
1707
likewise when writing to a file.  The `fopen' function returns a
 
1708
pointer to an open file that is ready to be read or written.  Once all
 
1709
data has been read from or written to the opened file it should be
 
1710
closed.  The `fclose' function does this.  The following code
 
1711
illustrates the basic pattern for writing to a file, but a very similar
 
1712
pattern is used when reading a file.
 
1713
 
 
1714
     filename = "myfile.txt";
 
1715
     fid = fopen (filename, "w");
 
1716
     # Do the actual I/O here...
 
1717
     fclose (fid);
 
1718
 
 
1719
 -- Built-in Function: [FID, MSG] = fopen (NAME, MODE, ARCH)
 
1720
 -- Built-in Function: FID_LIST = fopen ("all")
 
1721
 -- Built-in Function: [FILE, MODE, ARCH] = fopen (FID)
 
1722
     The first form of the `fopen' function opens the named file with
 
1723
     the specified mode (read-write, read-only, etc.) and architecture
 
1724
     interpretation (IEEE big endian, IEEE little endian, etc.), and
 
1725
     returns an integer value that may be used to refer to the file
 
1726
     later.  If an error occurs, FID is set to -1 and MSG contains the
 
1727
     corresponding system error message.  The MODE is a one or two
 
1728
     character string that specifies whether the file is to be opened
 
1729
     for reading, writing, or both.
 
1730
 
 
1731
     The second form of the `fopen' function returns a vector of file
 
1732
     ids corresponding to all the currently open files, excluding the
 
1733
     `stdin', `stdout', and `stderr' streams.
 
1734
 
 
1735
     The third form of the `fopen' function returns information about
 
1736
     the open file given its file id.
 
1737
 
 
1738
     For example,
 
1739
 
 
1740
          myfile = fopen ("splat.dat", "r", "ieee-le");
 
1741
 
 
1742
     opens the file `splat.dat' for reading.  If necessary, binary
 
1743
     numeric values will be read assuming they are stored in IEEE
 
1744
     format with the least significant bit first, and then converted to
 
1745
     the native representation.
 
1746
 
 
1747
     Opening a file that is already open simply opens it again and
 
1748
     returns a separate file id.  It is not an error to open a file
 
1749
     several times, though writing to the same file through several
 
1750
     different file ids may produce unexpected results.
 
1751
 
 
1752
     The possible values `mode' may have are
 
1753
 
 
1754
    `r'
 
1755
          Open a file for reading.
 
1756
 
 
1757
    `w'
 
1758
          Open a file for writing.  The previous contents are discarded.
 
1759
 
 
1760
    `a'
 
1761
          Open or create a file for writing at the end of the file.
 
1762
 
 
1763
    `r+'
 
1764
          Open an existing file for reading and writing.
 
1765
 
 
1766
    `w+'
 
1767
          Open a file for reading or writing.  The previous contents are
 
1768
          discarded.
 
1769
 
 
1770
    `a+'
 
1771
          Open or create a file for reading or writing at the end of the
 
1772
          file.
 
1773
 
 
1774
     Append a "t" to the mode string to open the file in text mode or a
 
1775
     "b" to open in binary mode.  On Windows and Macintosh systems, text
 
1776
     mode reading and writing automatically converts linefeeds to the
 
1777
     appropriate line end character for the system (carriage-return
 
1778
     linefeed on Windows, carriage-return on Macintosh).  The default
 
1779
     if no mode is specified is binary mode.
 
1780
 
 
1781
     Additionally, you may append a "z" to the mode string to open a
 
1782
     gzipped file for reading or writing.  For this to be successful,
 
1783
     you must also open the file in binary mode.
 
1784
 
 
1785
     The parameter ARCH is a string specifying the default data format
 
1786
     for the file.  Valid values for ARCH are:
 
1787
 
 
1788
          `native' The format of the current machine (this is the
 
1789
          default).
 
1790
 
 
1791
          `ieee-be' IEEE big endian format.
 
1792
 
 
1793
          `ieee-le' IEEE little endian format.
 
1794
 
 
1795
          `vaxd' VAX D floating format.
 
1796
 
 
1797
          `vaxg' VAX G floating format.
 
1798
 
 
1799
          `cray' Cray floating format.
 
1800
 
 
1801
     however, conversions are currently only supported for `native'
 
1802
     `ieee-be', and `ieee-le' formats.
 
1803
 
 
1804
     *See also:* fclose, fread, fseek.
 
1805
 
 
1806
 -- Built-in Function:  fclose (FID)
 
1807
     Closes the specified file.  If successful, `fclose' returns 0,
 
1808
     otherwise, it returns -1.
 
1809
 
 
1810
     *See also:* fopen, fseek, ftell.
 
1811
 
 
1812
 
 
1813
File: octave.info,  Node: Simple Output,  Next: Line-Oriented Input,  Prev: Opening and Closing Files,  Up: C-Style I/O Functions
 
1814
 
 
1815
14.2.2 Simple Output
 
1816
--------------------
 
1817
 
 
1818
Once a file has been opened for writing a string can be written to the
 
1819
file using the `fputs' function.  The following example shows how to
 
1820
write the string `Free Software is needed for Free Science' to the file
 
1821
`free.txt'.
 
1822
 
 
1823
     filename = "free.txt";
 
1824
     fid = fopen (filename, "w");
 
1825
     fputs (fid, "Free Software is needed for Free Science");
 
1826
     fclose (fid);
 
1827
 
 
1828
 -- Built-in Function:  fputs (FID, STRING)
 
1829
     Write a string to a file with no formatting.
 
1830
 
 
1831
     Return a non-negative number on success and EOF on error.
 
1832
 
 
1833
   A function much similar to `fputs' is available for writing data to
 
1834
the screen.  The `puts' function works just like `fputs' except it
 
1835
doesn't take a file pointer as its input.
 
1836
 
 
1837
 -- Built-in Function:  puts (STRING)
 
1838
     Write a string to the standard output with no formatting.
 
1839
 
 
1840
     Return a non-negative number on success and EOF on error.
 
1841
 
 
1842
 
 
1843
File: octave.info,  Node: Line-Oriented Input,  Next: Formatted Output,  Prev: Simple Output,  Up: C-Style I/O Functions
 
1844
 
 
1845
14.2.3 Line-Oriented Input
 
1846
--------------------------
 
1847
 
 
1848
To read from a file it must be opened for reading using `fopen'.  Then
 
1849
a line can be read from the file using `fgetl' as the following code
 
1850
illustrates
 
1851
 
 
1852
     fid = fopen ("free.txt");
 
1853
     txt = fgetl (fid)
 
1854
          -| Free Software is needed for Free Science
 
1855
     fclose (fid);
 
1856
 
 
1857
This of course assumes that the file `free.txt' exists and contains the
 
1858
line `Free Software is needed for Free Science'.
 
1859
 
 
1860
 -- Built-in Function:  fgetl (FID, LEN)
 
1861
     Read characters from a file, stopping after a newline, or EOF, or
 
1862
     LEN characters have been read.  The characters read, excluding the
 
1863
     possible trailing newline, are returned as a string.
 
1864
 
 
1865
     If LEN is omitted, `fgetl' reads until the next newline character.
 
1866
 
 
1867
     If there are no more characters to read, `fgetl' returns -1.
 
1868
 
 
1869
     *See also:* fread, fscanf.
 
1870
 
 
1871
 -- Built-in Function:  fgets (FID, LEN)
 
1872
     Read characters from a file, stopping after a newline, or EOF, or
 
1873
     LEN characters have been read.  The characters read, including the
 
1874
     possible trailing newline, are returned as a string.
 
1875
 
 
1876
     If LEN is omitted, `fgets' reads until the next newline character.
 
1877
 
 
1878
     If there are no more characters to read, `fgets' returns -1.
 
1879
 
 
1880
     *See also:* fread, fscanf.
 
1881
 
 
1882
 
 
1883
File: octave.info,  Node: Formatted Output,  Next: Output Conversion for Matrices,  Prev: Line-Oriented Input,  Up: C-Style I/O Functions
 
1884
 
 
1885
14.2.4 Formatted Output
 
1886
-----------------------
 
1887
 
 
1888
This section describes how to call `printf' and related functions.
 
1889
 
 
1890
   The following functions are available for formatted output.  They are
 
1891
modelled after the C language functions of the same name, but they
 
1892
interpret the format template differently in order to improve the
 
1893
performance of printing vector and matrix values.
 
1894
 
 
1895
 -- Built-in Function:  printf (TEMPLATE, ...)
 
1896
     Print optional arguments under the control of the template string
 
1897
     TEMPLATE to the stream `stdout' and return the number of
 
1898
     characters printed.
 
1899
 
 
1900
     *See also:* fprintf, sprintf, scanf.
 
1901
 
 
1902
 -- Built-in Function:  fprintf (FID, TEMPLATE, ...)
 
1903
     This function is just like `printf', except that the output is
 
1904
     written to the stream FID instead of `stdout'.
 
1905
 
 
1906
     *See also:* printf, sprintf, fread, fscanf, fopen, fclose.
 
1907
 
 
1908
 -- Built-in Function:  sprintf (TEMPLATE, ...)
 
1909
     This is like `printf', except that the output is returned as a
 
1910
     string.  Unlike the C library function, which requires you to
 
1911
     provide a suitably sized string as an argument, Octave's `sprintf'
 
1912
     function returns the string, automatically sized to hold all of
 
1913
     the items converted.
 
1914
 
 
1915
     *See also:* printf, fprintf, sscanf.
 
1916
 
 
1917
   The `printf' function can be used to print any number of arguments.
 
1918
The template string argument you supply in a call provides information
 
1919
not only about the number of additional arguments, but also about their
 
1920
types and what style should be used for printing them.
 
1921
 
 
1922
   Ordinary characters in the template string are simply written to the
 
1923
output stream as-is, while "conversion specifications" introduced by a
 
1924
`%' character in the template cause subsequent arguments to be
 
1925
formatted and written to the output stream.  For example, 
 
1926
 
 
1927
     pct = 37;
 
1928
     filename = "foo.txt";
 
1929
     printf ("Processed %d%% of `%s'.\nPlease be patient.\n",
 
1930
             pct, filename);
 
1931
 
 
1932
produces output like
 
1933
 
 
1934
     Processed 37% of `foo.txt'.
 
1935
     Please be patient.
 
1936
 
 
1937
   This example shows the use of the `%d' conversion to specify that a
 
1938
scalar argument should be printed in decimal notation, the `%s'
 
1939
conversion to specify printing of a string argument, and the `%%'
 
1940
conversion to print a literal `%' character.
 
1941
 
 
1942
   There are also conversions for printing an integer argument as an
 
1943
unsigned value in octal, decimal, or hexadecimal radix (`%o', `%u', or
 
1944
`%x', respectively); or as a character value (`%c').
 
1945
 
 
1946
   Floating-point numbers can be printed in normal, fixed-point notation
 
1947
using the `%f' conversion or in exponential notation using the `%e'
 
1948
conversion.  The `%g' conversion uses either `%e' or `%f' format,
 
1949
depending on what is more appropriate for the magnitude of the
 
1950
particular number.
 
1951
 
 
1952
   You can control formatting more precisely by writing "modifiers"
 
1953
between the `%' and the character that indicates which conversion to
 
1954
apply.  These slightly alter the ordinary behavior of the conversion.
 
1955
For example, most conversion specifications permit you to specify a
 
1956
minimum field width and a flag indicating whether you want the result
 
1957
left- or right-justified within the field.
 
1958
 
 
1959
   The specific flags and modifiers that are permitted and their
 
1960
interpretation vary depending on the particular conversion.  They're all
 
1961
described in more detail in the following sections.
 
1962
 
 
1963
 
 
1964
File: octave.info,  Node: Output Conversion for Matrices,  Next: Output Conversion Syntax,  Prev: Formatted Output,  Up: C-Style I/O Functions
 
1965
 
 
1966
14.2.5 Output Conversion for Matrices
 
1967
-------------------------------------
 
1968
 
 
1969
When given a matrix value, Octave's formatted output functions cycle
 
1970
through the format template until all the values in the matrix have been
 
1971
printed.  For example,
 
1972
 
 
1973
     printf ("%4.2f %10.2e %8.4g\n", hilb (3));
 
1974
 
 
1975
          -| 1.00   5.00e-01   0.3333
 
1976
          -| 0.50   3.33e-01     0.25
 
1977
          -| 0.33   2.50e-01      0.2
 
1978
 
 
1979
   If more than one value is to be printed in a single call, the output
 
1980
functions do not return to the beginning of the format template when
 
1981
moving on from one value to the next.  This can lead to confusing output
 
1982
if the number of elements in the matrices are not exact multiples of the
 
1983
number of conversions in the format template.  For example,
 
1984
 
 
1985
     printf ("%4.2f %10.2e %8.4g\n", [1, 2], [3, 4]);
 
1986
 
 
1987
          -| 1.00   2.00e+00        3
 
1988
          -| 4.00
 
1989
 
 
1990
   If this is not what you want, use a series of calls instead of just
 
1991
one.
 
1992
 
 
1993
 
 
1994
File: octave.info,  Node: Output Conversion Syntax,  Next: Table of Output Conversions,  Prev: Output Conversion for Matrices,  Up: C-Style I/O Functions
 
1995
 
 
1996
14.2.6 Output Conversion Syntax
 
1997
-------------------------------
 
1998
 
 
1999
This section provides details about the precise syntax of conversion
 
2000
specifications that can appear in a `printf' template string.
 
2001
 
 
2002
   Characters in the template string that are not part of a conversion
 
2003
specification are printed as-is to the output stream.
 
2004
 
 
2005
   The conversion specifications in a `printf' template string have the
 
2006
general form:
 
2007
 
 
2008
     % FLAGS WIDTH [ . PRECISION ] TYPE CONVERSION
 
2009
 
 
2010
   For example, in the conversion specifier `%-10.8ld', the `-' is a
 
2011
flag, `10' specifies the field width, the precision is `8', the letter
 
2012
`l' is a type modifier, and `d' specifies the conversion style.  (This
 
2013
particular type specifier says to print a numeric argument in decimal
 
2014
notation, with a minimum of 8 digits left-justified in a field at least
 
2015
10 characters wide.)
 
2016
 
 
2017
   In more detail, output conversion specifications consist of an
 
2018
initial `%' character followed in sequence by:
 
2019
 
 
2020
   * Zero or more "flag characters" that modify the normal behavior of
 
2021
     the conversion specification.  
 
2022
 
 
2023
   * An optional decimal integer specifying the "minimum field width".
 
2024
     If the normal conversion produces fewer characters than this, the
 
2025
     field is padded with spaces to the specified width.  This is a
 
2026
     _minimum_ value; if the normal conversion produces more characters
 
2027
     than this, the field is _not_ truncated.  Normally, the output is
 
2028
     right-justified within the field.  
 
2029
 
 
2030
     You can also specify a field width of `*'.  This means that the
 
2031
     next argument in the argument list (before the actual value to be
 
2032
     printed) is used as the field width.  The value is rounded to the
 
2033
     nearest integer.  If the value is negative, this means to set the
 
2034
     `-' flag (see below) and to use the absolute value as the field
 
2035
     width.
 
2036
 
 
2037
   * An optional "precision" to specify the number of digits to be
 
2038
     written for the numeric conversions.  If the precision is
 
2039
     specified, it consists of a period (`.') followed optionally by a
 
2040
     decimal integer (which defaults to zero if omitted).  
 
2041
 
 
2042
     You can also specify a precision of `*'.  This means that the next
 
2043
     argument in the argument list (before the actual value to be
 
2044
     printed) is used as the precision.  The value must be an integer,
 
2045
     and is ignored if it is negative.
 
2046
 
 
2047
   * An optional "type modifier character".  This character is ignored
 
2048
     by Octave's `printf' function, but is recognized to provide
 
2049
     compatibility with the C language `printf'.
 
2050
 
 
2051
   * A character that specifies the conversion to be applied.
 
2052
 
 
2053
   The exact options that are permitted and how they are interpreted
 
2054
vary between the different conversion specifiers.  See the descriptions
 
2055
of the individual conversions for information about the particular
 
2056
options that they use.
 
2057
 
 
2058
 
 
2059
File: octave.info,  Node: Table of Output Conversions,  Next: Integer Conversions,  Prev: Output Conversion Syntax,  Up: C-Style I/O Functions
 
2060
 
 
2061
14.2.7 Table of Output Conversions
 
2062
----------------------------------
 
2063
 
 
2064
Here is a table summarizing what all the different conversions do:
 
2065
 
 
2066
`%d', `%i'
 
2067
     Print an integer as a signed decimal number.  *Note Integer
 
2068
     Conversions::, for details.  `%d' and `%i' are synonymous for
 
2069
     output, but are different when used with `scanf' for input (*note
 
2070
     Table of Input Conversions::).
 
2071
 
 
2072
`%o'
 
2073
     Print an integer as an unsigned octal number.  *Note Integer
 
2074
     Conversions::, for details.
 
2075
 
 
2076
`%u'
 
2077
     Print an integer as an unsigned decimal number.  *Note Integer
 
2078
     Conversions::, for details.
 
2079
 
 
2080
`%x', `%X'
 
2081
     Print an integer as an unsigned hexadecimal number.  `%x' uses
 
2082
     lower-case letters and `%X' uses upper-case.  *Note Integer
 
2083
     Conversions::, for details.
 
2084
 
 
2085
`%f'
 
2086
     Print a floating-point number in normal (fixed-point) notation.
 
2087
     *Note Floating-Point Conversions::, for details.
 
2088
 
 
2089
`%e', `%E'
 
2090
     Print a floating-point number in exponential notation.  `%e' uses
 
2091
     lower-case letters and `%E' uses upper-case.  *Note Floating-Point
 
2092
     Conversions::, for details.
 
2093
 
 
2094
`%g', `%G'
 
2095
     Print a floating-point number in either normal (fixed-point) or
 
2096
     exponential notation, whichever is more appropriate for its
 
2097
     magnitude.  `%g' uses lower-case letters and `%G' uses upper-case.
 
2098
     *Note Floating-Point Conversions::, for details.
 
2099
 
 
2100
`%c'
 
2101
     Print a single character.  *Note Other Output Conversions::.
 
2102
 
 
2103
`%s'
 
2104
     Print a string.  *Note Other Output Conversions::.
 
2105
 
 
2106
`%%'
 
2107
     Print a literal `%' character.  *Note Other Output Conversions::.
 
2108
 
 
2109
   If the syntax of a conversion specification is invalid, unpredictable
 
2110
things will happen, so don't do this.  If there aren't enough function
 
2111
arguments provided to supply values for all the conversion
 
2112
specifications in the template string, or if the arguments are not of
 
2113
the correct types, the results are unpredictable.  If you supply more
 
2114
arguments than conversion specifications, the extra argument values are
 
2115
simply ignored; this is sometimes useful.
 
2116
 
 
2117
 
 
2118
File: octave.info,  Node: Integer Conversions,  Next: Floating-Point Conversions,  Prev: Table of Output Conversions,  Up: C-Style I/O Functions
 
2119
 
 
2120
14.2.8 Integer Conversions
 
2121
--------------------------
 
2122
 
 
2123
This section describes the options for the `%d', `%i', `%o', `%u',
 
2124
`%x', and `%X' conversion specifications.  These conversions print
 
2125
integers in various formats.
 
2126
 
 
2127
   The `%d' and `%i' conversion specifications both print an numeric
 
2128
argument as a signed decimal number; while `%o', `%u', and `%x' print
 
2129
the argument as an unsigned octal, decimal, or hexadecimal number
 
2130
(respectively).  The `%X' conversion specification is just like `%x'
 
2131
except that it uses the characters `ABCDEF' as digits instead of
 
2132
`abcdef'.
 
2133
 
 
2134
   The following flags are meaningful:
 
2135
 
 
2136
`-'
 
2137
     Left-justify the result in the field (instead of the normal
 
2138
     right-justification).
 
2139
 
 
2140
`+'
 
2141
     For the signed `%d' and `%i' conversions, print a plus sign if the
 
2142
     value is positive.
 
2143
 
 
2144
` '
 
2145
     For the signed `%d' and `%i' conversions, if the result doesn't
 
2146
     start with a plus or minus sign, prefix it with a space character
 
2147
     instead.  Since the `+' flag ensures that the result includes a
 
2148
     sign, this flag is ignored if you supply both of them.
 
2149
 
 
2150
`#'
 
2151
     For the `%o' conversion, this forces the leading digit to be `0',
 
2152
     as if by increasing the precision.  For `%x' or `%X', this
 
2153
     prefixes a leading `0x' or `0X' (respectively) to the result.
 
2154
     This doesn't do anything useful for the `%d', `%i', or `%u'
 
2155
     conversions.
 
2156
 
 
2157
`0'
 
2158
     Pad the field with zeros instead of spaces.  The zeros are placed
 
2159
     after any indication of sign or base.  This flag is ignored if the
 
2160
     `-' flag is also specified, or if a precision is specified.
 
2161
 
 
2162
   If a precision is supplied, it specifies the minimum number of
 
2163
digits to appear; leading zeros are produced if necessary.  If you
 
2164
don't specify a precision, the number is printed with as many digits as
 
2165
it needs.  If you convert a value of zero with an explicit precision of
 
2166
zero, then no characters at all are produced.
 
2167
 
 
2168
 
 
2169
File: octave.info,  Node: Floating-Point Conversions,  Next: Other Output Conversions,  Prev: Integer Conversions,  Up: C-Style I/O Functions
 
2170
 
 
2171
14.2.9 Floating-Point Conversions
 
2172
---------------------------------
 
2173
 
 
2174
This section discusses the conversion specifications for floating-point
 
2175
numbers: the `%f', `%e', `%E', `%g', and `%G' conversions.
 
2176
 
 
2177
   The `%f' conversion prints its argument in fixed-point notation,
 
2178
producing output of the form [`-']DDD`.'DDD, where the number of digits
 
2179
following the decimal point is controlled by the precision you specify.
 
2180
 
 
2181
   The `%e' conversion prints its argument in exponential notation,
 
2182
producing output of the form [`-']D`.'DDD`e'[`+'|`-']DD.  Again, the
 
2183
number of digits following the decimal point is controlled by the
 
2184
precision.  The exponent always contains at least two digits.  The `%E'
 
2185
conversion is similar but the exponent is marked with the letter `E'
 
2186
instead of `e'.
 
2187
 
 
2188
   The `%g' and `%G' conversions print the argument in the style of
 
2189
`%e' or `%E' (respectively) if the exponent would be less than -4 or
 
2190
greater than or equal to the precision; otherwise they use the `%f'
 
2191
style.  Trailing zeros are removed from the fractional portion of the
 
2192
result and a decimal-point character appears only if it is followed by
 
2193
a digit.
 
2194
 
 
2195
   The following flags can be used to modify the behavior:
 
2196
 
 
2197
`-'
 
2198
     Left-justify the result in the field.  Normally the result is
 
2199
     right-justified.
 
2200
 
 
2201
`+'
 
2202
     Always include a plus or minus sign in the result.
 
2203
 
 
2204
` '
 
2205
     If the result doesn't start with a plus or minus sign, prefix it
 
2206
     with a space instead.  Since the `+' flag ensures that the result
 
2207
     includes a sign, this flag is ignored if you supply both of them.
 
2208
 
 
2209
`#'
 
2210
     Specifies that the result should always include a decimal point,
 
2211
     even if no digits follow it.  For the `%g' and `%G' conversions,
 
2212
     this also forces trailing zeros after the decimal point to be left
 
2213
     in place where they would otherwise be removed.
 
2214
 
 
2215
`0'
 
2216
     Pad the field with zeros instead of spaces; the zeros are placed
 
2217
     after any sign.  This flag is ignored if the `-' flag is also
 
2218
     specified.
 
2219
 
 
2220
   The precision specifies how many digits follow the decimal-point
 
2221
character for the `%f', `%e', and `%E' conversions.  For these
 
2222
conversions, the default precision is `6'.  If the precision is
 
2223
explicitly `0', this suppresses the decimal point character entirely.
 
2224
For the `%g' and `%G' conversions, the precision specifies how many
 
2225
significant digits to print.  Significant digits are the first digit
 
2226
before the decimal point, and all the digits after it.  If the
 
2227
precision is `0' or not specified for `%g' or `%G', it is treated like
 
2228
a value of `1'.  If the value being printed cannot be expressed
 
2229
precisely in the specified number of digits, the value is rounded to
 
2230
the nearest number that fits.
 
2231
 
 
2232
 
 
2233
File: octave.info,  Node: Other Output Conversions,  Next: Formatted Input,  Prev: Floating-Point Conversions,  Up: C-Style I/O Functions
 
2234
 
 
2235
14.2.10 Other Output Conversions
 
2236
--------------------------------
 
2237
 
 
2238
This section describes miscellaneous conversions for `printf'.
 
2239
 
 
2240
   The `%c' conversion prints a single character.  The `-' flag can be
 
2241
used to specify left-justification in the field, but no other flags are
 
2242
defined, and no precision or type modifier can be given.  For example:
 
2243
 
 
2244
     printf ("%c%c%c%c%c", "h", "e", "l", "l", "o");
 
2245
 
 
2246
prints `hello'.
 
2247
 
 
2248
   The `%s' conversion prints a string.  The corresponding argument
 
2249
must be a string.  A precision can be specified to indicate the maximum
 
2250
number of characters to write; otherwise characters in the string up to
 
2251
but not including the terminating null character are written to the
 
2252
output stream.  The `-' flag can be used to specify left-justification
 
2253
in the field, but no other flags or type modifiers are defined for this
 
2254
conversion.  For example:
 
2255
 
 
2256
     printf ("%3s%-6s", "no", "where");
 
2257
 
 
2258
prints ` nowhere ' (note the leading and trailing spaces).
 
2259
 
 
2260
 
 
2261
File: octave.info,  Node: Formatted Input,  Next: Input Conversion Syntax,  Prev: Other Output Conversions,  Up: C-Style I/O Functions
 
2262
 
 
2263
14.2.11 Formatted Input
 
2264
-----------------------
 
2265
 
 
2266
Octave provides the `scanf', `fscanf', and `sscanf' functions to read
 
2267
formatted input.  There are two forms of each of these functions.  One
 
2268
can be used to extract vectors of data from a file, and the other is
 
2269
more `C-like'.
 
2270
 
 
2271
 -- Built-in Function: [VAL, COUNT] = fscanf (FID, TEMPLATE, SIZE)
 
2272
 -- Built-in Function: [V1, V2, ..., COUNT] =  fscanf (FID, TEMPLATE,
 
2273
          "C")
 
2274
     In the first form, read from FID according to TEMPLATE, returning
 
2275
     the result in the matrix VAL.
 
2276
 
 
2277
     The optional argument SIZE specifies the amount of data to read
 
2278
     and may be one of
 
2279
 
 
2280
    `Inf'
 
2281
          Read as much as possible, returning a column vector.
 
2282
 
 
2283
    `NR'
 
2284
          Read up to NR elements, returning a column vector.
 
2285
 
 
2286
    `[NR, Inf]'
 
2287
          Read as much as possible, returning a matrix with NR rows.
 
2288
          If the number of elements read is not an exact multiple of
 
2289
          NR, the last column is padded with zeros.
 
2290
 
 
2291
    `[NR, NC]'
 
2292
          Read up to `NR * NC' elements, returning a matrix with NR
 
2293
          rows.  If the number of elements read is not an exact multiple
 
2294
          of NR, the last column is padded with zeros.
 
2295
 
 
2296
     If SIZE is omitted, a value of `Inf' is assumed.
 
2297
 
 
2298
     A string is returned if TEMPLATE specifies only character
 
2299
     conversions.
 
2300
 
 
2301
     The number of items successfully read is returned in COUNT.
 
2302
 
 
2303
     In the second form, read from FID according to TEMPLATE, with each
 
2304
     conversion specifier in TEMPLATE corresponding to a single scalar
 
2305
     return value.  This form is more `C-like', and also compatible
 
2306
     with previous versions of Octave.  The number of successful
 
2307
     conversions is returned in COUNT
 
2308
 
 
2309
     *See also:* scanf, sscanf, fread, fprintf.
 
2310
 
 
2311
 -- Built-in Function: [VAL, COUNT] = sscanf (STRING, TEMPLATE, SIZE)
 
2312
 -- Built-in Function: [V1, V2, ..., COUNT] =  sscanf (STRING,
 
2313
          TEMPLATE, "C")
 
2314
     This is like `fscanf', except that the characters are taken from
 
2315
     the string STRING instead of from a stream.  Reaching the end of
 
2316
     the string is treated as an end-of-file condition.
 
2317
 
 
2318
     *See also:* fscanf, scanf, sprintf.
 
2319
 
 
2320
   Calls to `scanf' are superficially similar to calls to `printf' in
 
2321
that arbitrary arguments are read under the control of a template
 
2322
string.  While the syntax of the conversion specifications in the
 
2323
template is very similar to that for `printf', the interpretation of
 
2324
the template is oriented more towards free-format input and simple
 
2325
pattern matching, rather than fixed-field formatting.  For example,
 
2326
most `scanf' conversions skip over any amount of "white space"
 
2327
(including spaces, tabs, and newlines) in the input file, and there is
 
2328
no concept of precision for the numeric input conversions as there is
 
2329
for the corresponding output conversions.  Ordinarily, non-whitespace
 
2330
characters in the template are expected to match characters in the
 
2331
input stream exactly.  
 
2332
 
 
2333
   When a "matching failure" occurs, `scanf' returns immediately,
 
2334
leaving the first non-matching character as the next character to be
 
2335
read from the stream, and `scanf' returns all the items that were
 
2336
successfully converted.  
 
2337
 
 
2338
   The formatted input functions are not used as frequently as the
 
2339
formatted output functions.  Partly, this is because it takes some care
 
2340
to use them properly.  Another reason is that it is difficult to recover
 
2341
from a matching error.
 
2342
 
 
2343
 
 
2344
File: octave.info,  Node: Input Conversion Syntax,  Next: Table of Input Conversions,  Prev: Formatted Input,  Up: C-Style I/O Functions
 
2345
 
 
2346
14.2.12 Input Conversion Syntax
 
2347
-------------------------------
 
2348
 
 
2349
A `scanf' template string is a string that contains ordinary multibyte
 
2350
characters interspersed with conversion specifications that start with
 
2351
`%'.
 
2352
 
 
2353
   Any whitespace character in the template causes any number of
 
2354
whitespace characters in the input stream to be read and discarded.
 
2355
The whitespace characters that are matched need not be exactly the same
 
2356
whitespace characters that appear in the template string.  For example,
 
2357
write ` , ' in the template to recognize a comma with optional
 
2358
whitespace before and after.
 
2359
 
 
2360
   Other characters in the template string that are not part of
 
2361
conversion specifications must match characters in the input stream
 
2362
exactly; if this is not the case, a matching failure occurs.
 
2363
 
 
2364
   The conversion specifications in a `scanf' template string have the
 
2365
general form:
 
2366
 
 
2367
     % FLAGS WIDTH TYPE CONVERSION
 
2368
 
 
2369
   In more detail, an input conversion specification consists of an
 
2370
initial `%' character followed in sequence by:
 
2371
 
 
2372
   * An optional "flag character" `*', which says to ignore the text
 
2373
     read for this specification.  When `scanf' finds a conversion
 
2374
     specification that uses this flag, it reads input as directed by
 
2375
     the rest of the conversion specification, but it discards this
 
2376
     input, does not return any value, and does not increment the count
 
2377
     of successful assignments.  
 
2378
 
 
2379
   * An optional decimal integer that specifies the "maximum field
 
2380
     width".  Reading of characters from the input stream stops either
 
2381
     when this maximum is reached or when a non-matching character is
 
2382
     found, whichever happens first.  Most conversions discard initial
 
2383
     whitespace characters, and these discarded characters don't count
 
2384
     towards the maximum field width.  Conversions that do not discard
 
2385
     initial whitespace are explicitly documented.  
 
2386
 
 
2387
   * An optional type modifier character.  This character is ignored by
 
2388
     Octave's `scanf' function, but is recognized to provide
 
2389
     compatibility with the C language `scanf'.
 
2390
 
 
2391
   * A character that specifies the conversion to be applied.
 
2392
 
 
2393
   The exact options that are permitted and how they are interpreted
 
2394
vary between the different conversion specifiers.  See the descriptions
 
2395
of the individual conversions for information about the particular
 
2396
options that they allow.
 
2397
 
 
2398
 
 
2399
File: octave.info,  Node: Table of Input Conversions,  Next: Numeric Input Conversions,  Prev: Input Conversion Syntax,  Up: C-Style I/O Functions
 
2400
 
 
2401
14.2.13 Table of Input Conversions
 
2402
----------------------------------
 
2403
 
 
2404
Here is a table that summarizes the various conversion specifications:
 
2405
 
 
2406
`%d'
 
2407
     Matches an optionally signed integer written in decimal.  *Note
 
2408
     Numeric Input Conversions::.
 
2409
 
 
2410
`%i'
 
2411
     Matches an optionally signed integer in any of the formats that
 
2412
     the C language defines for specifying an integer constant.  *Note
 
2413
     Numeric Input Conversions::.
 
2414
 
 
2415
`%o'
 
2416
     Matches an unsigned integer written in octal radix.  *Note Numeric
 
2417
     Input Conversions::.
 
2418
 
 
2419
`%u'
 
2420
     Matches an unsigned integer written in decimal radix.  *Note
 
2421
     Numeric Input Conversions::.
 
2422
 
 
2423
`%x', `%X'
 
2424
     Matches an unsigned integer written in hexadecimal radix.  *Note
 
2425
     Numeric Input Conversions::.
 
2426
 
 
2427
`%e', `%f', `%g', `%E', `%G'
 
2428
     Matches an optionally signed floating-point number.  *Note Numeric
 
2429
     Input Conversions::.
 
2430
 
 
2431
`%s'
 
2432
     Matches a string containing only non-whitespace characters.  *Note
 
2433
     String Input Conversions::.
 
2434
 
 
2435
`%c'
 
2436
     Matches a string of one or more characters; the number of
 
2437
     characters read is controlled by the maximum field width given for
 
2438
     the conversion.  *Note String Input Conversions::.
 
2439
 
 
2440
`%%'
 
2441
     This matches a literal `%' character in the input stream.  No
 
2442
     corresponding argument is used.
 
2443
 
 
2444
   If the syntax of a conversion specification is invalid, the behavior
 
2445
is undefined.  If there aren't enough function arguments provided to
 
2446
supply addresses for all the conversion specifications in the template
 
2447
strings that perform assignments, or if the arguments are not of the
 
2448
correct types, the behavior is also undefined.  On the other hand, extra
 
2449
arguments are simply ignored.
 
2450
 
 
2451
 
 
2452
File: octave.info,  Node: Numeric Input Conversions,  Next: String Input Conversions,  Prev: Table of Input Conversions,  Up: C-Style I/O Functions
 
2453
 
 
2454
14.2.14 Numeric Input Conversions
 
2455
---------------------------------
 
2456
 
 
2457
This section describes the `scanf' conversions for reading numeric
 
2458
values.
 
2459
 
 
2460
   The `%d' conversion matches an optionally signed integer in decimal
 
2461
radix.
 
2462
 
 
2463
   The `%i' conversion matches an optionally signed integer in any of
 
2464
the formats that the C language defines for specifying an integer
 
2465
constant.
 
2466
 
 
2467
   For example, any of the strings `10', `0xa', or `012' could be read
 
2468
in as integers under the `%i' conversion.  Each of these specifies a
 
2469
number with decimal value `10'.
 
2470
 
 
2471
   The `%o', `%u', and `%x' conversions match unsigned integers in
 
2472
octal, decimal, and hexadecimal radices, respectively.
 
2473
 
 
2474
   The `%X' conversion is identical to the `%x' conversion.  They both
 
2475
permit either uppercase or lowercase letters to be used as digits.
 
2476
 
 
2477
   Unlike the C language `scanf', Octave ignores the `h', `l', and `L'
 
2478
modifiers.
 
2479
 
 
2480
 
 
2481
File: octave.info,  Node: String Input Conversions,  Next: Binary I/O,  Prev: Numeric Input Conversions,  Up: C-Style I/O Functions
 
2482
 
 
2483
14.2.15 String Input Conversions
 
2484
--------------------------------
 
2485
 
 
2486
This section describes the `scanf' input conversions for reading string
 
2487
and character values: `%s' and `%c'.
 
2488
 
 
2489
   The `%c' conversion is the simplest: it matches a fixed number of
 
2490
characters, always.  The maximum field with says how many characters to
 
2491
read; if you don't specify the maximum, the default is 1.  This
 
2492
conversion does not skip over initial whitespace characters.  It reads
 
2493
precisely the next N characters, and fails if it cannot get that many.
 
2494
 
 
2495
   The `%s' conversion matches a string of non-whitespace characters.
 
2496
It skips and discards initial whitespace, but stops when it encounters
 
2497
more whitespace after having read something.
 
2498
 
 
2499
   For example, reading the input:
 
2500
 
 
2501
      hello, world
 
2502
 
 
2503
with the conversion `%10c' produces `" hello, wo"', but reading the
 
2504
same input with the conversion `%10s' produces `"hello,"'.
 
2505
 
 
2506
 
 
2507
File: octave.info,  Node: Binary I/O,  Next: Temporary Files,  Prev: String Input Conversions,  Up: C-Style I/O Functions
 
2508
 
 
2509
14.2.16 Binary I/O
 
2510
------------------
 
2511
 
 
2512
Octave can read and write binary data using the functions `fread' and
 
2513
`fwrite', which are patterned after the standard C functions with the
 
2514
same names.  They are able to automatically swap the byte order of
 
2515
integer data and convert among the supported floating point formats as
 
2516
the data are read.
 
2517
 
 
2518
 -- Built-in Function: [VAL, COUNT] = fread (FID, SIZE, PRECISION,
 
2519
          SKIP, ARCH)
 
2520
     Read binary data of type PRECISION from the specified file ID FID.
 
2521
 
 
2522
     The optional argument SIZE specifies the amount of data to read
 
2523
     and may be one of
 
2524
 
 
2525
    `Inf'
 
2526
          Read as much as possible, returning a column vector.
 
2527
 
 
2528
    `NR'
 
2529
          Read up to NR elements, returning a column vector.
 
2530
 
 
2531
    `[NR, Inf]'
 
2532
          Read as much as possible, returning a matrix with NR rows.
 
2533
          If the number of elements read is not an exact multiple of
 
2534
          NR, the last column is padded with zeros.
 
2535
 
 
2536
    `[NR, NC]'
 
2537
          Read up to `NR * NC' elements, returning a matrix with NR
 
2538
          rows.  If the number of elements read is not an exact multiple
 
2539
          of NR, the last column is padded with zeros.
 
2540
 
 
2541
     If SIZE is omitted, a value of `Inf' is assumed.
 
2542
 
 
2543
     The optional argument PRECISION is a string specifying the type of
 
2544
     data to read and may be one of
 
2545
 
 
2546
    `"schar"'
 
2547
    `"signed char"'
 
2548
          Signed character.
 
2549
 
 
2550
    `"uchar"'
 
2551
    `"unsigned char"'
 
2552
          Unsigned character.
 
2553
 
 
2554
    `"int8"'
 
2555
    `"integer*1"'
 
2556
          8-bit signed integer.
 
2557
 
 
2558
    `"int16"'
 
2559
    `"integer*2"'
 
2560
          16-bit signed integer.
 
2561
 
 
2562
    `"int32"'
 
2563
    `"integer*4"'
 
2564
          32-bit signed integer.
 
2565
 
 
2566
    `"int64"'
 
2567
    `"integer*8"'
 
2568
          64-bit signed integer.
 
2569
 
 
2570
    `"uint8"'
 
2571
          8-bit unsigned integer.
 
2572
 
 
2573
    `"uint16"'
 
2574
          16-bit unsigned integer.
 
2575
 
 
2576
    `"uint32"'
 
2577
          32-bit unsigned integer.
 
2578
 
 
2579
    `"uint64"'
 
2580
          64-bit unsigned integer.
 
2581
 
 
2582
    `"single"'
 
2583
    `"float32"'
 
2584
    `"real*4"'
 
2585
          32-bit floating point number.
 
2586
 
 
2587
    `"double"'
 
2588
    `"float64"'
 
2589
    `"real*8"'
 
2590
          64-bit floating point number.
 
2591
 
 
2592
    `"char"'
 
2593
    `"char*1"'
 
2594
          Single character.
 
2595
 
 
2596
    `"short"'
 
2597
          Short integer (size is platform dependent).
 
2598
 
 
2599
    `"int"'
 
2600
          Integer (size is platform dependent).
 
2601
 
 
2602
    `"long"'
 
2603
          Long integer (size is platform dependent).
 
2604
 
 
2605
    `"ushort"'
 
2606
    `"unsigned short"'
 
2607
          Unsigned short integer (size is platform dependent).
 
2608
 
 
2609
    `"uint"'
 
2610
    `"unsigned int"'
 
2611
          Unsigned integer (size is platform dependent).
 
2612
 
 
2613
    `"ulong"'
 
2614
    `"unsigned long"'
 
2615
          Unsigned long integer (size is platform dependent).
 
2616
 
 
2617
    `"float"'
 
2618
          Single precision floating point number (size is platform
 
2619
          dependent).
 
2620
 
 
2621
     The default precision is `"uchar"'.
 
2622
 
 
2623
     The PRECISION argument may also specify an optional repeat count.
 
2624
     For example, `32*single' causes `fread' to read a block of 32
 
2625
     single precision floating point numbers.  Reading in blocks is
 
2626
     useful in combination with the SKIP argument.
 
2627
 
 
2628
     The PRECISION argument may also specify a type conversion.  For
 
2629
     example, `int16=>int32' causes `fread' to read 16-bit integer
 
2630
     values and return an array of 32-bit integer values.  By default,
 
2631
     `fread' returns a double precision array.  The special form
 
2632
     `*TYPE' is shorthand for `TYPE=>TYPE'.
 
2633
 
 
2634
     The conversion and repeat counts may be combined.  For example, the
 
2635
     specification `32*single=>single' causes `fread' to read blocks of
 
2636
     single precision floating point values and return an array of
 
2637
     single precision values instead of the default array of double
 
2638
     precision values.
 
2639
 
 
2640
     The optional argument SKIP specifies the number of bytes to skip
 
2641
     after each element (or block of elements) is read.  If it is not
 
2642
     specified, a value of 0 is assumed.  If the final block read is not
 
2643
     complete, the final skip is omitted.  For example,
 
2644
 
 
2645
          fread (f, 10, "3*single=>single", 8)
 
2646
 
 
2647
     will omit the final 8-byte skip because the last read will not be
 
2648
     a complete block of 3 values.
 
2649
 
 
2650
     The optional argument ARCH is a string specifying the data format
 
2651
     for the file.  Valid values are
 
2652
 
 
2653
    `"native"'
 
2654
          The format of the current machine.
 
2655
 
 
2656
    `"ieee-be"'
 
2657
          IEEE big endian.
 
2658
 
 
2659
    `"ieee-le"'
 
2660
          IEEE little endian.
 
2661
 
 
2662
    `"vaxd"'
 
2663
          VAX D floating format.
 
2664
 
 
2665
    `"vaxg"'
 
2666
          VAX G floating format.
 
2667
 
 
2668
    `"cray"'
 
2669
          Cray floating format.
 
2670
 
 
2671
     Conversions are currently only supported for `"ieee-be"' and
 
2672
     `"ieee-le"' formats.
 
2673
 
 
2674
     The data read from the file is returned in VAL, and the number of
 
2675
     values read is returned in `count'
 
2676
 
 
2677
     *See also:* fwrite, fopen, fclose.
 
2678
 
 
2679
 -- Built-in Function: COUNT = fwrite (FID, DATA, PRECISION, SKIP, ARCH)
 
2680
     Write data in binary form of type PRECISION to the specified file
 
2681
     ID FID, returning the number of values successfully written to the
 
2682
     file.
 
2683
 
 
2684
     The argument DATA is a matrix of values that are to be written to
 
2685
     the file.  The values are extracted in column-major order.
 
2686
 
 
2687
     The remaining arguments PRECISION, SKIP, and ARCH are optional,
 
2688
     and are interpreted as described for `fread'.
 
2689
 
 
2690
     The behavior of `fwrite' is undefined if the values in DATA are
 
2691
     too large to fit in the specified precision.
 
2692
 
 
2693
     *See also:* fread, fopen, fclose.
 
2694
 
 
2695
 
 
2696
File: octave.info,  Node: Temporary Files,  Next: EOF and Errors,  Prev: Binary I/O,  Up: C-Style I/O Functions
 
2697
 
 
2698
14.2.17 Temporary Files
 
2699
-----------------------
 
2700
 
 
2701
Sometimes one needs to write data to a file that is only temporary.
 
2702
This is most commonly used when an external program launched from
 
2703
within Octave needs to access data.  When Octave exits all temporary
 
2704
files will be deleted, so this step need not be executed manually.
 
2705
 
 
2706
 -- Built-in Function: [FID, NAME, MSG] = mkstemp (TEMPLATE, DELETE)
 
2707
     Return the file ID corresponding to a new temporary file with a
 
2708
     unique name created from TEMPLATE.  The last six characters of
 
2709
     TEMPLATE must be `XXXXXX' and these are replaced with a string
 
2710
     that makes the filename unique.  The file is then created with
 
2711
     mode read/write and permissions that are system dependent (on
 
2712
     GNU/Linux systems, the permissions will be 0600 for versions of
 
2713
     glibc 2.0.7 and later).  The file is opened with the `O_EXCL' flag.
 
2714
 
 
2715
     If the optional argument DELETE is supplied and is true, the file
 
2716
     will be deleted automatically when Octave exits, or when the
 
2717
     function `purge_tmp_files' is called.
 
2718
 
 
2719
     If successful, FID is a valid file ID, NAME is the name of the
 
2720
     file, and MSG is an empty string.  Otherwise, FID is -1, NAME is
 
2721
     empty, and MSG contains a system-dependent error message.
 
2722
 
 
2723
     *See also:* tmpfile, tmpnam, P_tmpdir.
 
2724
 
 
2725
 -- Built-in Function: [FID, MSG] = tmpfile ()
 
2726
     Return the file ID corresponding to a new temporary file with a
 
2727
     unique name.  The file is opened in binary read/write (`"w+b"')
 
2728
     mode.  The file will be deleted automatically when it is closed or
 
2729
     when Octave exits.
 
2730
 
 
2731
     If successful, FID is a valid file ID and MSG is an empty string.
 
2732
     Otherwise, FID is -1 and MSG contains a system-dependent error
 
2733
     message.
 
2734
 
 
2735
     *See also:* tmpnam, mkstemp, P_tmpdir.
 
2736
 
 
2737
 -- Built-in Function:  tmpnam (DIR, PREFIX)
 
2738
     Return a unique temporary file name as a string.
 
2739
 
 
2740
     If PREFIX is omitted, a value of `"oct-"' is used.  If DIR is also
 
2741
     omitted, the default directory for temporary files is used.  If
 
2742
     DIR is provided, it must exist, otherwise the default directory
 
2743
     for temporary files is used.  Since the named file is not opened,
 
2744
     by `tmpnam', it is possible (though relatively unlikely) that it
 
2745
     will not be available by the time your program attempts to open it.
 
2746
 
 
2747
     *See also:* tmpfile, mkstemp, P_tmpdir.
 
2748
 
 
2749
 
 
2750
File: octave.info,  Node: EOF and Errors,  Next: File Positioning,  Prev: Temporary Files,  Up: C-Style I/O Functions
 
2751
 
 
2752
14.2.18 End of File and Errors
 
2753
------------------------------
 
2754
 
 
2755
Once a file has been opened its status can be acquired.  As an example
 
2756
the `feof' functions determines if the end of the file has been
 
2757
reached.  This can be very useful when reading small parts of a file at
 
2758
a time.  The following example shows how to read one line at a time
 
2759
from a file until the end has been reached.
 
2760
 
 
2761
     filename = "myfile.txt";
 
2762
     fid = fopen (filename, "r");
 
2763
     while (! feof (fid) )
 
2764
       text_line = fgetl (fid);
 
2765
     endwhile
 
2766
     fclose (fid);
 
2767
 
 
2768
Note that in some situations it is more efficient to read the entire
 
2769
contents of a file and then process it, than it is to read it line by
 
2770
line.  This has the potential advantage of removing the loop in the
 
2771
above code.
 
2772
 
 
2773
 -- Built-in Function:  feof (FID)
 
2774
     Return 1 if an end-of-file condition has been encountered for a
 
2775
     given file and 0 otherwise.  Note that it will only return 1 if
 
2776
     the end of the file has already been encountered, not if the next
 
2777
     read operation will result in an end-of-file condition.
 
2778
 
 
2779
     *See also:* fread, fopen, fclose.
 
2780
 
 
2781
 -- Built-in Function:  ferror (FID)
 
2782
     Return 1 if an error condition has been encountered for a given
 
2783
     file and 0 otherwise.  Note that it will only return 1 if an error
 
2784
     has already been encountered, not if the next operation will
 
2785
     result in an error condition.
 
2786
 
 
2787
 -- Built-in Function:  freport ()
 
2788
     Print a list of which files have been opened, and whether they are
 
2789
     open for reading, writing, or both.  For example,
 
2790
 
 
2791
          freport ()
 
2792
 
 
2793
               -|  number  mode  name
 
2794
               -|
 
2795
               -|       0     r  stdin
 
2796
               -|       1     w  stdout
 
2797
               -|       2     w  stderr
 
2798
               -|       3     r  myfile
 
2799
 
 
2800
 
 
2801
File: octave.info,  Node: File Positioning,  Prev: EOF and Errors,  Up: C-Style I/O Functions
 
2802
 
 
2803
14.2.19 File Positioning
 
2804
------------------------
 
2805
 
 
2806
Three functions are available for setting and determining the position
 
2807
of the file pointer for a given file.
 
2808
 
 
2809
 -- Built-in Function:  ftell (FID)
 
2810
     Return the position of the file pointer as the number of characters
 
2811
     from the beginning of the file FID.
 
2812
 
 
2813
     *See also:* fseek, fopen, fclose.
 
2814
 
 
2815
 -- Built-in Function:  fseek (FID, OFFSET, ORIGIN)
 
2816
     Set the file pointer to any location within the file FID.
 
2817
 
 
2818
     The pointer is positioned OFFSET characters from the ORIGIN, which
 
2819
     may be one of the predefined variables `SEEK_CUR' (current
 
2820
     position), `SEEK_SET' (beginning), or `SEEK_END' (end of file) or
 
2821
     strings "cof", "bof" or "eof". If ORIGIN is omitted, `SEEK_SET' is
 
2822
     assumed.  The offset must be zero, or a value returned by `ftell'
 
2823
     (in which case ORIGIN must be `SEEK_SET').
 
2824
 
 
2825
     Return 0 on success and -1 on error.
 
2826
 
 
2827
     *See also:* ftell, fopen, fclose.
 
2828
 
 
2829
 -- Built-in Function:  SEEK_SET ()
 
2830
 -- Built-in Function:  SEEK_CUR ()
 
2831
 -- Built-in Function:  SEEK_END ()
 
2832
     Return the value required to request that `fseek' perform one of
 
2833
     the following actions:
 
2834
    `SEEK_SET'
 
2835
          Position file relative to the beginning.
 
2836
 
 
2837
    `SEEK_CUR'
 
2838
          Position file relative to the current position.
 
2839
 
 
2840
    `SEEK_END'
 
2841
          Position file relative to the end.
 
2842
 
 
2843
 -- Built-in Function:  frewind (FID)
 
2844
     Move the file pointer to the beginning of the file FID, returning
 
2845
     0 for success, and -1 if an error was encountered.  It is
 
2846
     equivalent to `fseek (FID, 0, SEEK_SET)'.
 
2847
 
 
2848
   The following example stores the current file position in the
 
2849
variable `marker', moves the pointer to the beginning of the file, reads
 
2850
four characters, and then returns to the original position.
 
2851
 
 
2852
     marker = ftell (myfile);
 
2853
     frewind (myfile);
 
2854
     fourch = fgets (myfile, 4);
 
2855
     fseek (myfile, marker, SEEK_SET);
 
2856
 
 
2857
 
 
2858
File: octave.info,  Node: Plotting,  Next: Matrix Manipulation,  Prev: Input and Output,  Up: Top
 
2859
 
 
2860
15 Plotting
 
2861
***********
 
2862
 
 
2863
* Menu:
 
2864
 
 
2865
* Plotting Basics::
 
2866
* Advanced Plotting::
 
2867
 
 
2868
 
 
2869
File: octave.info,  Node: Plotting Basics,  Next: Advanced Plotting,  Up: Plotting
 
2870
 
 
2871
15.1 Plotting Basics
 
2872
====================
 
2873
 
 
2874
Octave makes it easy to create many different types of two- and
 
2875
three-dimensional plots using a few high-level functions.
 
2876
 
 
2877
   If you need finer control over graphics, see *note Advanced
 
2878
Plotting::.
 
2879
 
 
2880
* Menu:
 
2881
 
 
2882
* Two-Dimensional Plots::
 
2883
* Three-Dimensional Plotting::
 
2884
* Plot Annotations::
 
2885
* Multiple Plots on One Page::
 
2886
* Multiple Plot Windows::
 
2887
* Printing Plots::
 
2888
* Test Plotting Functions::
 
2889
 
 
2890
 
 
2891
File: octave.info,  Node: Two-Dimensional Plots,  Next: Three-Dimensional Plotting,  Up: Plotting Basics
 
2892
 
 
2893
15.1.1 Two-Dimensional Plots
 
2894
----------------------------
 
2895
 
 
2896
The `plot' function allows you to create simple x-y plots with linear
 
2897
axes.  For example,
 
2898
 
 
2899
     x = -10:0.1:10;
 
2900
     plot (x, sin (x));
 
2901
 
 
2902
displays a sine wave shown in *note fig:plot::.  On most systems, this
 
2903
command will open a separate plot window to display the graph.
 
2904
 
 
2905
[image src="plot.png" text="
 
2906
+---------------------------------+
 
2907
| Image unavailable in text mode. |
 
2908
+---------------------------------+
 
2909
"]
 
2910
 
 
2911
Figure 15.1: Simple Two-Dimensional Plot.
 
2912
 
 
2913
   The function `fplot' also generates two-dimensional plots with
 
2914
linear axes using a function name and limits for the range of the
 
2915
x-coordinate instead of the x and y data.  For example,
 
2916
 
 
2917
     fplot (@sin, [-10, 10], 201);
 
2918
 
 
2919
produces a plot that is equivalent to the one above, but also includes a
 
2920
legend displaying the name of the plotted function.
 
2921
 
 
2922
 -- Function File:  plot (Y)
 
2923
 -- Function File:  plot (X, Y)
 
2924
 -- Function File:  plot (X, Y, PROPERTY, VALUE, ...)
 
2925
 -- Function File:  plot (X, Y, FMT)
 
2926
 -- Function File:  plot (H, ...)
 
2927
     Produces two-dimensional plots.  Many different combinations of
 
2928
     arguments are possible.  The simplest form is
 
2929
 
 
2930
          plot (Y)
 
2931
 
 
2932
     where the argument is taken as the set of Y coordinates and the X
 
2933
     coordinates are taken to be the indices of the elements, starting
 
2934
     with 1.
 
2935
 
 
2936
     To save a plot, in one of several image formats such as PostScript
 
2937
     or PNG, use the `print' command.
 
2938
 
 
2939
     If more than one argument is given, they are interpreted as
 
2940
 
 
2941
          plot (Y, PROPERTY, VALUE, ...)
 
2942
 
 
2943
     or
 
2944
 
 
2945
          plot (X, Y, PROPERTY, VALUE, ...)
 
2946
 
 
2947
     or
 
2948
 
 
2949
          plot (X, Y, FMT, ...)
 
2950
 
 
2951
     and so on.  Any number of argument sets may appear.  The X and Y
 
2952
     values are interpreted as follows:
 
2953
 
 
2954
        * If a single data argument is supplied, it is taken as the set
 
2955
          of Y coordinates and the X coordinates are taken to be the
 
2956
          indices of the elements, starting with 1.
 
2957
 
 
2958
        * If the X is a vector and Y is a matrix, then the columns (or
 
2959
          rows) of Y are plotted versus X.  (using whichever
 
2960
          combination matches, with columns tried first.)
 
2961
 
 
2962
        * If the X is a matrix and Y is a vector, Y is plotted versus
 
2963
          the columns (or rows) of X.  (using whichever combination
 
2964
          matches, with columns tried first.)
 
2965
 
 
2966
        * If both arguments are vectors, the elements of Y are plotted
 
2967
          versus the elements of X.
 
2968
 
 
2969
        * If both arguments are matrices, the columns of Y are plotted
 
2970
          versus the columns of X.  In this case, both matrices must
 
2971
          have the same number of rows and columns and no attempt is
 
2972
          made to transpose the arguments to make the number of rows
 
2973
          match.
 
2974
 
 
2975
          If both arguments are scalars, a single point is plotted.
 
2976
 
 
2977
     Multiple property-value pairs may be specified, but they must
 
2978
     appear in pairs.  These arguments are applied to the lines drawn by
 
2979
     `plot'.
 
2980
 
 
2981
     If the FMT argument is supplied, it is interpreted as follows.  If
 
2982
     FMT is missing, the default gnuplot line style is assumed.
 
2983
 
 
2984
    `-'
 
2985
          Set lines plot style (default).
 
2986
 
 
2987
    `.'
 
2988
          Set dots plot style.
 
2989
 
 
2990
    `^'
 
2991
          Set impulses plot style.
 
2992
 
 
2993
    `L'
 
2994
          Set steps plot style.
 
2995
 
 
2996
    `N'
 
2997
          Interpreted as the plot color if N is an integer in the range
 
2998
          1 to 6.
 
2999
 
 
3000
    `NM'
 
3001
          If NM is a two digit integer and M is an integer in the range
 
3002
          1 to 6, M is interpreted as the point style.  This is only
 
3003
          valid in combination with the `@' or `-@' specifiers.
 
3004
 
 
3005
    `C'
 
3006
          If C is one of `"k"' (black), `"r"' (red), `"g"' (green),
 
3007
          `"b"' (blue), `"m"' (magenta), `"c"' (cyan), or `"w"'
 
3008
          (white), it is interpreted as the line plot color.
 
3009
 
 
3010
    `";title;"'
 
3011
          Here `"title"' is the label for the key.
 
3012
 
 
3013
    `+'
 
3014
    `*'
 
3015
    `o'
 
3016
    `x'
 
3017
          Used in combination with the points or linespoints styles,
 
3018
          set the point style.
 
3019
 
 
3020
     The FMT argument may also be used to assign key titles.  To do so,
 
3021
     include the desired title between semi-colons after the formatting
 
3022
     sequence described above, e.g. "+3;Key Title;" Note that the last
 
3023
     semi-colon is required and will generate an error if it is left
 
3024
     out.
 
3025
 
 
3026
     Here are some plot examples:
 
3027
 
 
3028
          plot (x, y, "@12", x, y2, x, y3, "4", x, y4, "+")
 
3029
 
 
3030
     This command will plot `y' with points of type 2 (displayed as
 
3031
     `+') and color 1 (red), `y2' with lines, `y3' with lines of color
 
3032
     4 (magenta) and `y4' with points displayed as `+'.
 
3033
 
 
3034
          plot (b, "*", "markersize", 3)
 
3035
 
 
3036
     This command will plot the data in the variable `b', with points
 
3037
     displayed as `*' with a marker size of 3.
 
3038
 
 
3039
          t = 0:0.1:6.3;
 
3040
          plot (t, cos(t), "-;cos(t);", t, sin(t), "+3;sin(t);");
 
3041
 
 
3042
     This will plot the cosine and sine functions and label them
 
3043
     accordingly in the key.
 
3044
 
 
3045
     If the first argument is an axis handle, then plot into these axes,
 
3046
     rather than the current axis handle returned by `gca'.
 
3047
 
 
3048
     *See also:* semilogx, semilogy, loglog, polar, mesh, contour, bar,
 
3049
     stairs, errorbar, xlabel, ylabel, title, print.
 
3050
 
 
3051
 -- Function File:  fplot (FN, LIMITS)
 
3052
 -- Function File:  fplot (FN, LIMITS, TOL)
 
3053
 -- Function File:  fplot (FN, LIMITS, N)
 
3054
 -- Function File:  fplot (..., FMT)
 
3055
     Plot a function FN, within the defined limits.  FN an be either a
 
3056
     string, a function handle or an inline function.  The limits of
 
3057
     the plot are given by LIMITS of the form `[XLO, XHI]' or `[XLO,
 
3058
     XHI, YLO, YHI]'. TOL is the default tolerance to use for the plot,
 
3059
     and if TOL is an integer it is assumed that it defines the number
 
3060
     points to use in the plot.  The FMT argument is passed to the plot
 
3061
     command.
 
3062
 
 
3063
             fplot ("cos", [0, 2*pi])
 
3064
             fplot ("[cos(x), sin(x)]", [0, 2*pi])
 
3065
 
 
3066
 
 
3067
     *See also:* plot.
 
3068
 
 
3069
   The functions `semilogx', `semilogy', and `loglog' are similar to
 
3070
the `plot' function, but produce plots in which one or both of the axes
 
3071
use log scales.
 
3072
 
 
3073
 -- Function File:  semilogx (ARGS)
 
3074
     Produce a two-dimensional plot using a log scale for the X axis.
 
3075
     See the description of `plot' for a description of the arguments
 
3076
     that `semilogx' will accept.
 
3077
 
 
3078
     *See also:* plot, semilogy, loglog.
 
3079
 
 
3080
 -- Function File:  semilogy (ARGS)
 
3081
     Produce a two-dimensional plot using a log scale for the Y axis.
 
3082
     See the description of `plot' for a description of the arguments
 
3083
     that `semilogy' will accept.
 
3084
 
 
3085
     *See also:* plot, semilogx, loglog.
 
3086
 
 
3087
 -- Function File:  loglog (ARGS)
 
3088
     Produce a two-dimensional plot using log scales for both axes.  See
 
3089
     the description of `plot' for a description of the arguments that
 
3090
     `loglog' will accept.
 
3091
 
 
3092
     *See also:* plot, semilogx, semilogy.
 
3093
 
 
3094
   The functions `bar', `barh', `stairs', and `stem' are useful for
 
3095
displaying discrete data.  For example,
 
3096
 
 
3097
     hist (randn (10000, 1), 30);
 
3098
 
 
3099
produces the histogram of 10,000 normally distributed random numbers
 
3100
shown in *note fig:hist::.
 
3101
 
 
3102
[image src="hist.png" text="
 
3103
+---------------------------------+
 
3104
| Image unavailable in text mode. |
 
3105
+---------------------------------+
 
3106
"]
 
3107
 
 
3108
Figure 15.2: Histogram.
 
3109
 
 
3110
 -- Function File:  bar (X, Y)
 
3111
 -- Function File:  bar (Y)
 
3112
 -- Function File:  bar (X, Y, W)
 
3113
 -- Function File:  bar (X, Y, W, STYLE)
 
3114
 -- Function File: H = bar (..., PROP, VAL)
 
3115
 -- Function File:  bar (H, ...)
 
3116
     Produce a bar graph from two vectors of x-y data.
 
3117
 
 
3118
     If only one argument is given, it is taken as a vector of y-values
 
3119
     and the x coordinates are taken to be the indices of the elements.
 
3120
 
 
3121
     The default width of 0.8 for the bars can be changed using W.
 
3122
 
 
3123
     If Y is a matrix, then each column of Y is taken to be a separate
 
3124
     bar graph plotted on the same graph. By default the columns are
 
3125
     plotted side-by-side. This behavior can be changed by the STYLE
 
3126
     argument, which can take the values `"grouped"' (the default), or
 
3127
     `"stacked"'.
 
3128
 
 
3129
     The optional return value H provides a handle to the patch object.
 
3130
     Whereas the option input handle H allows an axis handle to be
 
3131
     passed.  Properties of the patch graphics object can be changed
 
3132
     using PROP, VAL pairs.
 
3133
 
 
3134
 
 
3135
     *See also:* barh, plot.
 
3136
 
 
3137
 -- Function File:  barh (X, Y)
 
3138
 -- Function File:  barh (Y)
 
3139
 -- Function File:  barh (X, Y, W)
 
3140
 -- Function File:  barh (X, Y, W, STYLE)
 
3141
 -- Function File: H = barh (..., PROP, VAL)
 
3142
 -- Function File:  barh (H, ...)
 
3143
     Produce a horizontal bar graph from two vectors of x-y data.
 
3144
 
 
3145
     If only one argument is given, it is taken as a vector of y-values
 
3146
     and the x coordinates are taken to be the indices of the elements.
 
3147
 
 
3148
     The default width of 0.8 for the bars can be changed using W.
 
3149
 
 
3150
     If Y is a matrix, then each column of Y is taken to be a separate
 
3151
     bar graph plotted on the same graph. By default the columns are
 
3152
     plotted side-by-side. This behavior can be changed by the STYLE
 
3153
     argument, which can take the values `"grouped"' (the default), or
 
3154
     `"stacked"'.
 
3155
 
 
3156
     The optional return value H provides a handle to the patch object.
 
3157
     Whereas the option input handle H allows an axis handle to be
 
3158
     passed.  Properties of the patch graphics object can be changed
 
3159
     using PROP, VAL pairs.
 
3160
 
 
3161
 
 
3162
     *See also:* bar, plot.
 
3163
 
 
3164
 -- Function File:  hist (Y, X, NORM)
 
3165
     Produce histogram counts or plots.
 
3166
 
 
3167
     With one vector input argument, plot a histogram of the values with
 
3168
     10 bins.  The range of the histogram bins is determined by the
 
3169
     range of the data.
 
3170
 
 
3171
     Given a second scalar argument, use that as the number of bins.
 
3172
 
 
3173
     Given a second vector argument, use that as the centers of the
 
3174
     bins, with the width of the bins determined from the adjacent
 
3175
     values in the vector.
 
3176
 
 
3177
     If third argument is provided, the histogram is normalised such
 
3178
     that the sum of the bars is equal to NORM.
 
3179
 
 
3180
     Extreme values are lumped in the first and last bins.
 
3181
 
 
3182
     With two output arguments, produce the values NN and XX such that
 
3183
     `bar (XX, NN)' will plot the histogram.
 
3184
 
 
3185
     *See also:* bar.
 
3186
 
 
3187
 -- Function File:  stairs (X, Y)
 
3188
     Produce a stairstep plot.  The arguments may be vectors or
 
3189
     matrices.
 
3190
 
 
3191
     If only one argument is given, it is taken as a vector of y-values
 
3192
     and the x coordinates are taken to be the indices of the elements.
 
3193
 
 
3194
     If two output arguments are specified, the data are generated but
 
3195
     not plotted.  For example,
 
3196
 
 
3197
          stairs (x, y);
 
3198
 
 
3199
     and
 
3200
 
 
3201
          [xs, ys] = stairs (x, y);
 
3202
          plot (xs, ys);
 
3203
 
 
3204
     are equivalent.
 
3205
 
 
3206
     *See also:* plot, semilogx, semilogy, loglog, polar, mesh, contour,
 
3207
     bar, xlabel, ylabel, title.
 
3208
 
 
3209
 -- Function File: H = stem (X, Y, LINESPEC)
 
3210
     Plot a stem graph and return the handles of the line and marker
 
3211
     objects used to draw the stems.  The default color is `"r"' (red).
 
3212
     The default line style is `"-"' and the default marker is `"o"'.
 
3213
 
 
3214
     For example,
 
3215
          x = 1:10;
 
3216
          stem (x);
 
3217
     plots 10 stems with heights from 1 to 10;
 
3218
 
 
3219
          x = 1:10;
 
3220
          y = ones (1, length (x))*2.*x;
 
3221
          stem (x, y);
 
3222
     plots 10 stems with heights from 2 to 20;
 
3223
 
 
3224
          x = 1:10;
 
3225
          y = ones (size (x))*2.*x;
 
3226
          h = stem (x, y, "b");
 
3227
     plots 10 bars with heights from 2 to 20 (the color is blue, and H
 
3228
     is a 2-by-10 array of handles in which the first row holds the
 
3229
     line handles and the second row holds the marker handles);
 
3230
 
 
3231
          x = 1:10;
 
3232
          y = ones (size (x))*2.*x;
 
3233
          h = stem (x, y, "-.k");
 
3234
     plots 10 stems with heights from 2 to 20 (the color is black, line
 
3235
     style is `"-."', and H is a 2-by-10 array of handles in which the
 
3236
     first row holds the line handles and the second row holds the
 
3237
     marker handles);
 
3238
 
 
3239
          x = 1:10;
 
3240
          y = ones (size (x))*2.*x;
 
3241
          h = stem (x, y, "-.k.");
 
3242
     plots 10 stems with heights from 2 to 20 (the color is black, line
 
3243
     style is `"-."' and the marker style is `"."', and H is a 2-by-10
 
3244
     array of handles in which the first row holds the line handles and
 
3245
     the second row holds the marker handles);
 
3246
 
 
3247
          x = 1:10;
 
3248
          y = ones (size (x))*2.*x;
 
3249
          h = stem (x, y, "fill");
 
3250
     plots 10 stems with heights from 2 to 20 (the color is rgb-triple
 
3251
     defined, the line style is `"-"', the marker style is `"o"', and H
 
3252
     is a 2-by-10 array of handles in which the first row holds the
 
3253
     line handles and the second row holds the marker handles).
 
3254
 
 
3255
     Color definitions with rgb-triples are not valid!
 
3256
 
 
3257
     *See also:* bar, barh, plot.
 
3258
 
 
3259
   The `contour' and `contourc' functions produce two-dimensional
 
3260
contour plots from three dimensional data.
 
3261
 
 
3262
 -- Function File:  contour (Z)
 
3263
 -- Function File:  contour (Z, VN)
 
3264
 -- Function File:  contour (X, Y, Z)
 
3265
 -- Function File:  contour (X, Y, Z, VN)
 
3266
 -- Function File:  contour (..., STYLE)
 
3267
 -- Function File:  contour (H, ...)
 
3268
 -- Function File: [C, H] = contour (...)
 
3269
     Plot level curves (contour lines) of the matrix Z, using the
 
3270
     contour matrix C computed by `contourc' from the same arguments;
 
3271
     see the latter for their interpretation.  The set of contour
 
3272
     levels, C, is only returned if requested.  For example:
 
3273
 
 
3274
          x = 0:2;
 
3275
          y = x;
 
3276
          z = x' * y;
 
3277
          contour (x, y, z, 2:3)
 
3278
 
 
3279
     The style to use for the plot can be defined with a line style
 
3280
     STYLE in a similar manner to the line styles used with the `plot'
 
3281
     command.  Any markers defined by STYLE are ignored.
 
3282
 
 
3283
     The optional input and output argument H allows an axis handle to
 
3284
     be passed to `contour' and the handles to the contour objects to be
 
3285
     returned.
 
3286
 
 
3287
     *See also:* contourc, patch, plot.
 
3288
 
 
3289
 -- Function File: [C, LEV] = contourc (X, Y, Z, VN)
 
3290
     Compute isolines (countour lines) of the matrix Z.  Parameters X,
 
3291
     Y and VN are optional.
 
3292
 
 
3293
     The return value LEV is a vector of the contour levels.  The
 
3294
     return value C is a 2 by N matrix containing the contour lines in
 
3295
     the following format
 
3296
 
 
3297
          C = [lev1, x1, x2, ..., levn, x1, x2, ...
 
3298
               len1, y1, y2, ..., lenn, y1, y2, ...]
 
3299
 
 
3300
     in which contour line N has a level (height) of LEVN and length of
 
3301
     LENN.
 
3302
 
 
3303
     If X and Y are omitted they are taken as the row/column index of
 
3304
     Z.  VN is either a scalar denoting the number of lines to compute
 
3305
     or a vector containing the values of the lines. If only one value
 
3306
     is wanted, set `VN = [val, val]'; If VN is omitted it defaults to
 
3307
     10.
 
3308
 
 
3309
     For example,
 
3310
          x = 0:2;
 
3311
          y = x;
 
3312
          z = x' * y;
 
3313
          contourc (x, y, z, 2:3)
 
3314
          =>   2.0000   2.0000   1.0000   3.0000   1.5000   2.0000
 
3315
               2.0000   1.0000   2.0000   2.0000   2.0000   1.5000
 
3316
 
 
3317
 
 
3318
     *See also:* contour.
 
3319
 
 
3320
   The `errorbar', `semilogxerr', `semilogyerr', and `loglogerr'
 
3321
functions produces plots with error bar markers.  For example,
 
3322
 
 
3323
     x = 0:0.1:10;
 
3324
     y = sin (x);
 
3325
     yp =  0.1 .* randn (size (x));
 
3326
     ym = -0.1 .* randn (size (x));
 
3327
     errorbar (x, sin (x), ym, yp);
 
3328
 
 
3329
produces the figure shown in *note fig:errorbar::.
 
3330
 
 
3331
[image src="errorbar.png" text="
 
3332
+---------------------------------+
 
3333
| Image unavailable in text mode. |
 
3334
+---------------------------------+
 
3335
"]
 
3336
 
 
3337
Figure 15.3: Errorbar plot.
 
3338
 
 
3339
 -- Function File:  errorbar (ARGS)
 
3340
     This function produces two-dimensional plots with errorbars. Many
 
3341
     different combinations of arguments are possible.  The simplest
 
3342
     form is
 
3343
 
 
3344
          errorbar (Y, EY)
 
3345
 
 
3346
     where the first argument is taken as the set of Y coordinates and
 
3347
     the second argument EY is taken as the errors of the Y values. X
 
3348
     coordinates are taken to be the indices of the elements, starting
 
3349
     with 1.
 
3350
 
 
3351
     If more than two arguments are given, they are interpreted as
 
3352
 
 
3353
          errorbar (X, Y, ..., FMT, ...)
 
3354
 
 
3355
     where after X and Y there can be up to four error parameters such
 
3356
     as EY, EX, LY, UY etc., depending on the plot type. Any number of
 
3357
     argument sets may appear, as long as they are separated with a
 
3358
     format string FMT.
 
3359
 
 
3360
     If Y is a matrix, X and error parameters must also be matrices
 
3361
     having same dimensions. The columns of Y are plotted versus the
 
3362
     corresponding columns of X and errorbars are drawn from the
 
3363
     corresponding columns of error parameters.
 
3364
 
 
3365
     If FMT is missing, yerrorbars ("~") plot style is assumed.
 
3366
 
 
3367
     If the FMT argument is supplied, it is interpreted as in normal
 
3368
     plots. In addition the following plot styles are supported by
 
3369
     errorbar:
 
3370
 
 
3371
    `~'
 
3372
          Set yerrorbars plot style (default).
 
3373
 
 
3374
    `>'
 
3375
          Set xerrorbars plot style.
 
3376
 
 
3377
    `~>'
 
3378
          Set xyerrorbars plot style.
 
3379
 
 
3380
    `#'
 
3381
          Set boxes plot style.
 
3382
 
 
3383
    `#~'
 
3384
          Set boxerrorbars plot style.
 
3385
 
 
3386
    `#~>'
 
3387
          Set boxxyerrorbars plot style.
 
3388
 
 
3389
     Examples:
 
3390
 
 
3391
          errorbar (X, Y, EX, ">")
 
3392
 
 
3393
     produces an xerrorbar plot of Y versus X with X errorbars drawn
 
3394
     from X-EX to X+EX.
 
3395
 
 
3396
          errorbar (X, Y1, EY, "~",
 
3397
          X, Y2, LY, UY)
 
3398
 
 
3399
     produces yerrorbar plots with Y1 and Y2 versus X.  Errorbars for
 
3400
     Y1 are drawn from Y1-EY to Y1+EY, errorbars for Y2 from Y2-LY to
 
3401
     Y2+UY.
 
3402
 
 
3403
          errorbar (X, Y, LX, UX,
 
3404
          LY, UY, "~>")
 
3405
 
 
3406
     produces an xyerrorbar plot of Y versus X in which X errorbars are
 
3407
     drawn from X-LX to X+UX and Y errorbars from Y-LY to Y+UY.
 
3408
 
 
3409
     *See also:* semilogxerr, semilogyerr, loglogerr.
 
3410
 
 
3411
 -- Function File:  semilogxerr (ARGS)
 
3412
     Produce two-dimensional plots on a semilogarithm axis with
 
3413
     errorbars.  Many different combinations of arguments are possible.
 
3414
     The most used form is
 
3415
 
 
3416
          semilogxerr (X, Y, EY, FMT)
 
3417
 
 
3418
     which produces a semi-logarithm plot of Y versus X with errors in
 
3419
     the Y-scale defined by EY and the plot format defined by FMT. See
 
3420
     errorbar for available formats and additional information.
 
3421
 
 
3422
     *See also:* errorbar, loglogerr semilogyerr.
 
3423
 
 
3424
 -- Function File:  semilogyerr (ARGS)
 
3425
     Produce two-dimensional plots on a semilogarithm axis with
 
3426
     errorbars.  Many different combinations of arguments are possible.
 
3427
     The most used form is
 
3428
 
 
3429
          semilogyerr (X, Y, EY, FMT)
 
3430
 
 
3431
     which produces a semi-logarithm plot of Y versus X with errors in
 
3432
     the Y-scale defined by EY and the plot format defined by FMT.  See
 
3433
     errorbar for available formats and additional information.
 
3434
 
 
3435
     *See also:* errorbar, loglogerr semilogxerr.
 
3436
 
 
3437
 -- Function File:  loglogerr (ARGS)
 
3438
     Produce two-dimensional plots on double logarithm axis with
 
3439
     errorbars.  Many different combinations of arguments are possible.
 
3440
     The most used form is
 
3441
 
 
3442
          loglogerr (X, Y, EY, FMT)
 
3443
 
 
3444
     which produces a double logarithm plot of Y versus X with errors
 
3445
     in the Y-scale defined by EY and the plot format defined by FMT.
 
3446
     See errorbar for available formats and additional information.
 
3447
 
 
3448
     *See also:* errorbar, semilogxerr, semilogyerr.
 
3449
 
 
3450
   Finally, the `polar' function allows you to easily plot data in
 
3451
polar coordinates.  However, the display coordinates remain rectangular
 
3452
and linear.  For example,
 
3453
 
 
3454
     polar (0:0.1:10*pi, 0:0.1:10*pi);
 
3455
 
 
3456
produces the spiral plot shown in *note fig:polar::.
 
3457
 
 
3458
[image src="polar.png" text="
 
3459
+---------------------------------+
 
3460
| Image unavailable in text mode. |
 
3461
+---------------------------------+
 
3462
"]
 
3463
 
 
3464
Figure 15.4: Polar plot.
 
3465
 
 
3466
 -- Function File:  polar (THETA, RHO, FMT)
 
3467
     Make a two-dimensional plot given the polar coordinates THETA and
 
3468
     RHO.
 
3469
 
 
3470
     The optional third argument specifies the line type.
 
3471
 
 
3472
     *See also:* plot.
 
3473
 
 
3474
 -- Function File:  pie (Y)
 
3475
 -- Function File:  pie (Y, EXPLODE)
 
3476
 -- Function File:  pie (..., LABELS)
 
3477
 -- Function File:  pie (H, ...);
 
3478
 -- Function File: H = pie (...);
 
3479
     Produce a pie chart.
 
3480
 
 
3481
     Called with a single vector arrgument, produces a pie chart of the
 
3482
     elements in X, with the size of the slice determined by percentage
 
3483
     size of the values of X.
 
3484
 
 
3485
     The variable EXPLODE is a vector of the same length as X that if
 
3486
     non zero 'explodes' the slice from the pie chart.
 
3487
 
 
3488
     If given LABELS is a cell array of strings of the same length as
 
3489
     X, giving the labels of each of the slices of the pie chart.
 
3490
 
 
3491
     The optional return value H provides a handle to the patch object.
 
3492
 
 
3493
 
 
3494
     *See also:* bar, stem.
 
3495
 
 
3496
 -- Function File:  quiver (U, V)
 
3497
 -- Function File:  quiver (X, Y, U, V)
 
3498
 -- Function File:  quiver (..., S)
 
3499
 -- Function File:  quiver (..., STYLE)
 
3500
 -- Function File:  quiver (..., 'filled')
 
3501
 -- Function File:  quiver (H, ...)
 
3502
 -- Function File: H = quiver (...)
 
3503
     Plot the `(U, V)' components of a vector field in an `(X, Y)'
 
3504
     meshgrid. If the grid is uniform, you can specify X and Y as
 
3505
     vectors.
 
3506
 
 
3507
     If X and Y are undefined they are assumed to be `(1:M, 1:N)' where
 
3508
     `[M, N] = size(U)'.
 
3509
 
 
3510
     The variable S is a scalar defining a scaling factor to use for
 
3511
     the arrows of the field relative to the mesh spacing. A value of 0
 
3512
     disables all scaling. The default value is 1.
 
3513
 
 
3514
     The style to use for the plot can be defined with a line style
 
3515
     STYLE in a similar manner to the line styles used with the `plot'
 
3516
     command.  If a marker is specified then markers at the grid points
 
3517
     of the vectors are printed rather than arrows. If the argument
 
3518
     'filled' is given then the markers as filled.
 
3519
 
 
3520
     The optional return value H provides a list of handles to the the
 
3521
     parts of the vector field (body, arrow and marker).
 
3522
 
 
3523
          [x, y] = meshgrid (1:2:20);
 
3524
          quiver (x, y, sin (2*pi*x/10), sin (2*pi*y/10));
 
3525
 
 
3526
 
 
3527
     *See also:* plot.
 
3528
 
 
3529
 -- Function File:  pcolor (X, Y, C)
 
3530
 -- Function File:  pcolor (C)
 
3531
     Density plot for given matrices X, and Y from `meshgrid' and a
 
3532
     matrix C corresponding to the X and Y coordinates of the mesh.  If
 
3533
     X and Y are vectors, then a typical vertex is (X(j), Y(i),
 
3534
     C(i,j)).  Thus, columns of C correspond to different X values and
 
3535
     rows of C correspond to different Y values.
 
3536
 
 
3537
     *See also:* meshgrid, contour.
 
3538
 
 
3539
 -- Function File:  area (X, Y)
 
3540
 -- Function File:  area (X, Y, LVL)
 
3541
 -- Function File:  area (..., PROP, VAL, ...)
 
3542
 -- Function File:  area (Y, ...)
 
3543
 -- Function File:  area (H, ...)
 
3544
 -- Function File: H = area (...)
 
3545
     Area plot of cummulative sum of the columns of Y. This shows the
 
3546
     contributions of a value to a sum, and is functionally similar to
 
3547
     `plot (X, cumsum (Y, 2))', except that the area under the curve is
 
3548
     shaded.
 
3549
 
 
3550
     If the X argument is ommitted it is assumed to be given by `1 :
 
3551
     rows (Y)'. A value LVL can be defined that determines where the
 
3552
     base level of the shading under the curve should be defined.
 
3553
 
 
3554
     Additional arguments to the `area' function are passed to the
 
3555
     `patch'. The optional return value H provides a handle to the list
 
3556
     of patch objects.
 
3557
 
 
3558
     *See also:* plot, patch.
 
3559
 
 
3560
   The axis function may be used to change the axis limits of an
 
3561
existing plot.
 
3562
 
 
3563
 -- Function File:  axis (LIMITS)
 
3564
     Set axis limits for plots.
 
3565
 
 
3566
     The argument LIMITS should be a 2, 4, or 6 element vector.  The
 
3567
     first and second elements specify the lower and upper limits for
 
3568
     the x axis.  The third and fourth specify the limits for the y
 
3569
     axis, and the fifth and sixth specify the limits for the z axis.
 
3570
 
 
3571
     Without any arguments, `axis' turns autoscaling on.
 
3572
 
 
3573
     With one output argument, `x=axis' returns the current axes
 
3574
 
 
3575
     The vector argument specifying limits is optional, and additional
 
3576
     string arguments may be used to specify various axis properties.
 
3577
     For example,
 
3578
 
 
3579
          axis ([1, 2, 3, 4], "square");
 
3580
 
 
3581
     forces a square aspect ratio, and
 
3582
 
 
3583
          axis ("labely", "tic");
 
3584
 
 
3585
     turns tic marks on for all axes and tic mark labels on for the
 
3586
     y-axis only.
 
3587
 
 
3588
     The following options control the aspect ratio of the axes.
 
3589
 
 
3590
    `"square"'
 
3591
          Force a square aspect ratio.
 
3592
 
 
3593
    `"equal"'
 
3594
          Force x distance to equal y-distance.
 
3595
 
 
3596
    `"normal"'
 
3597
          Restore the balance.
 
3598
 
 
3599
     The following options control the way axis limits are interpreted.
 
3600
 
 
3601
    `"auto"'
 
3602
          Set the specified axes to have nice limits around the data or
 
3603
          all if no axes are specified.
 
3604
 
 
3605
    `"manual"'
 
3606
          Fix the current axes limits.
 
3607
 
 
3608
    `"tight"'
 
3609
          Fix axes to the limits of the data (not implemented).
 
3610
 
 
3611
     The option `"image"' is equivalent to `"tight"' and `"equal"'.
 
3612
 
 
3613
     The following options affect the appearance of tic marks.
 
3614
 
 
3615
    `"on"'
 
3616
          Turn tic marks and labels on for all axes.
 
3617
 
 
3618
    `"off"'
 
3619
          Turn tic marks off for all axes.
 
3620
 
 
3621
    `"tic[xyz]"'
 
3622
          Turn tic marks on for all axes, or turn them on for the
 
3623
          specified axes and off for the remainder.
 
3624
 
 
3625
    `"label[xyz]"'
 
3626
          Turn tic labels on for all axes, or turn them on for the
 
3627
          specified axes and off for the remainder.
 
3628
 
 
3629
    `"nolabel"'
 
3630
          Turn tic labels off for all axes.
 
3631
     Note, if there are no tic marks for an axis, there can be no
 
3632
     labels.
 
3633
 
 
3634
     The following options affect the direction of increasing values on
 
3635
     the axes.
 
3636
 
 
3637
    `"ij"'
 
3638
          Reverse y-axis, so lower values are nearer the top.
 
3639
 
 
3640
    `"xy"'
 
3641
          Restore y-axis, so higher values are nearer the top.
 
3642
 
 
3643
     If an axes handle is passed as the first argument, then operate on
 
3644
     this axes rather than the current axes.
 
3645
 
 
3646
   Similarly the axis limits of the colormap can be changed with the
 
3647
caxis function.
 
3648
 
 
3649
 -- Function File:  caxis (LIMITS)
 
3650
 -- Function File:  caxis (H, ...)
 
3651
     Set color axis limits for plots.
 
3652
 
 
3653
     The argument LIMITS should be a 2 element vector specifying the
 
3654
     lower and upper limits to assign to the first and last value in the
 
3655
     colormap. Values outside this range are clamped to the first and
 
3656
     last colormap entries.
 
3657
 
 
3658
     If LIMITS is 'auto', then automatic colormap scaling is applied,
 
3659
     whereas if LIMITS is 'manual' the colormap scaling is set to
 
3660
     manual.
 
3661
 
 
3662
     Called without any arguments to current color axis limits are
 
3663
     returned.
 
3664
 
 
3665
     If an axes handle is passed as the first argument, then operate on
 
3666
     this axes rather than the current axes.
 
3667
 
 
3668
 
 
3669
File: octave.info,  Node: Three-Dimensional Plotting,  Next: Plot Annotations,  Prev: Two-Dimensional Plots,  Up: Plotting Basics
 
3670
 
 
3671
15.1.2 Three-Dimensional Plotting
 
3672
---------------------------------
 
3673
 
 
3674
The function `mesh' produces mesh surface plots.  For example,
 
3675
 
 
3676
     tx = ty = linspace (-8, 8, 41)';
 
3677
     [xx, yy] = meshgrid (tx, ty);
 
3678
     r = sqrt (xx .^ 2 + yy .^ 2) + eps;
 
3679
     tz = sin (r) ./ r;
 
3680
     mesh (tx, ty, tz);
 
3681
 
 
3682
produces the familiar "sombrero" plot shown in *note fig:mesh::.  Note
 
3683
the use of the function `meshgrid' to create matrices of X and Y
 
3684
coordinates to use for plotting the Z data.  The `ndgrid' function is
 
3685
similar to `meshgrid', but works for N-dimensional matrices.
 
3686
 
 
3687
[image src="mesh.png" text="
 
3688
+---------------------------------+
 
3689
| Image unavailable in text mode. |
 
3690
+---------------------------------+
 
3691
"]
 
3692
 
 
3693
Figure 15.5: Mesh plot.
 
3694
 
 
3695
   The `meshc' function is similar to `mesh', but also produces a plot
 
3696
of contours for the surface.
 
3697
 
 
3698
   The `plot3' function displays arbitrary three-dimensional data,
 
3699
without requiring it to form a surface.  For example
 
3700
 
 
3701
     t = 0:0.1:10*pi;
 
3702
     r = linspace (0, 1, numel (t));
 
3703
     z = linspace (0, 1, numel (t));
 
3704
     plot3 (r.*sin(t), r.*cos(t), z);
 
3705
 
 
3706
displays the spiral in three dimensions shown in *note fig:plot3::.
 
3707
 
 
3708
[image src="plot3.png" text="
 
3709
+---------------------------------+
 
3710
| Image unavailable in text mode. |
 
3711
+---------------------------------+
 
3712
"]
 
3713
 
 
3714
Figure 15.6: Three dimensional spiral.
 
3715
 
 
3716
   Finally, the `view' function changes the viewpoint for
 
3717
three-dimensional plots.
 
3718
 
 
3719
 -- Function File:  mesh (X, Y, Z)
 
3720
     Plot a mesh given matrices X, and Y from `meshgrid' and a matrix Z
 
3721
     corresponding to the X and Y coordinates of the mesh.  If X and Y
 
3722
     are vectors, then a typical vertex is (X(j), Y(i), Z(i,j)).  Thus,
 
3723
     columns of Z correspond to different X values and rows of Z
 
3724
     correspond to different Y values.
 
3725
 
 
3726
     *See also:* meshgrid, contour.
 
3727
 
 
3728
 -- Function File:  meshc (X, Y, Z)
 
3729
     Plot a mesh and contour given matrices X, and Y from `meshgrid'
 
3730
     and a matrix Z corresponding to the X and Y coordinates of the
 
3731
     mesh.  If X and Y are vectors, then a typical vertex is (X(j),
 
3732
     Y(i), Z(i,j)).  Thus, columns of Z correspond to different X
 
3733
     values and rows of Z correspond to different Y values.
 
3734
 
 
3735
     *See also:* meshgrid, mesh, contour.
 
3736
 
 
3737
 -- Function File:  hidden (MODE)
 
3738
 -- Function File:  hidden ()
 
3739
     Manipulation the mesh hidden line removal. Called with no argument
 
3740
     the hidden line removal is toggled. The argument MODE can be either
 
3741
     'on' or 'off' and the set of the hidden line removal is set
 
3742
     accordingly.
 
3743
 
 
3744
     *See also:* mesh, meshc, surf.
 
3745
 
 
3746
 -- Function File:  surf (X, Y, Z)
 
3747
     Plot a surface given matrices X, and Y from `meshgrid' and a
 
3748
     matrix Z corresponding to the X and Y coordinates of the mesh.  If
 
3749
     X and Y are vectors, then a typical vertex is (X(j), Y(i),
 
3750
     Z(i,j)).  Thus, columns of Z correspond to different X values and
 
3751
     rows of Z correspond to different Y values.
 
3752
 
 
3753
     *See also:* mesh, surface.
 
3754
 
 
3755
 -- Function File:  surfc (X, Y, Z)
 
3756
     Plot a surface and contour given matrices X, and Y from `meshgrid'
 
3757
     and a matrix Z corresponding to the X and Y coordinates of the
 
3758
     mesh.  If X and Y are vectors, then a typical vertex is (X(j),
 
3759
     Y(i), Z(i,j)).  Thus, columns of Z correspond to different X
 
3760
     values and rows of Z correspond to different Y values.
 
3761
 
 
3762
     *See also:* meshgrid, surf, contour.
 
3763
 
 
3764
 -- Function File: [XX, YY, ZZ] = meshgrid (X, Y, Z)
 
3765
 -- Function File: [XX, YY] = meshgrid (X, Y)
 
3766
 -- Function File: [XX, YY] = meshgrid (X)
 
3767
     Given vectors of X and Y and Z coordinates, and returning 3
 
3768
     arguments, return three dimensional arrays corresponding to the X,
 
3769
     Y, and Z coordinates of a mesh.  When returning only 2 arguments,
 
3770
     return matrices corresponding to the X and Y coordinates of a
 
3771
     mesh.  The rows of XX are copies of X, and the columns of YY are
 
3772
     copies of Y.  If Y is omitted, then it is assumed to be the same
 
3773
     as X, and Z is assumed the same as Y.
 
3774
 
 
3775
     *See also:* mesh, contour.
 
3776
 
 
3777
 -- Function File: [Y1, Y2, ...,  Yn] = ndgrid (X1, X2, ..., Xn)
 
3778
 -- Function File: [Y1, Y2, ...,  Yn] = ndgrid (X)
 
3779
     Given n vectors X1, ... Xn, `ndgrid' returns n arrays of dimension
 
3780
     n.  The elements of the ith output argument contains the elements
 
3781
     of the vector Xi repeated over all dimensions different from the
 
3782
     ith dimension.  Calling ndgrid with only one input argument X is
 
3783
     equivalent of calling ndgrid with all n input arguments equal to X:
 
3784
 
 
3785
     [Y1, Y2, ...,  Yn] = ndgrid (X, ..., X)
 
3786
 
 
3787
     *See also:* meshgrid.
 
3788
 
 
3789
 -- Function File:  plot3 (ARGS)
 
3790
     Produce three-dimensional plots.  Many different combinations of
 
3791
     arguments are possible.  The simplest form is
 
3792
 
 
3793
          plot3 (X, Y, Z)
 
3794
 
 
3795
     in which the arguments are taken to be the vertices of the points
 
3796
     to be plotted in three dimensions. If all arguments are vectors of
 
3797
     the same length, then a single continuous line is drawn. If all
 
3798
     arguments are matrices, then each column of the matrices is
 
3799
     treated as a separate line.  No attempt is made to transpose the
 
3800
     arguments to make the number of rows match.
 
3801
 
 
3802
     If only two arguments are given, as
 
3803
 
 
3804
          plot3 (X, C)
 
3805
 
 
3806
     the real and imaginary parts of the second argument are used as
 
3807
     the Y and Z coordinates, respectively.
 
3808
 
 
3809
     If only one argument is given, as
 
3810
 
 
3811
          plot3 (C)
 
3812
 
 
3813
     the real and imaginary parts of the argument are used as the Y and
 
3814
     Z values, and they are plotted versus their index.
 
3815
 
 
3816
     Arguments may also be given in groups of three as
 
3817
 
 
3818
          plot3 (X1, Y1, Z1, X2, Y2, Z2, ...)
 
3819
 
 
3820
     in which each set of three arguments is treated as a separate line
 
3821
     or set of lines in three dimensions.
 
3822
 
 
3823
     To plot multiple one- or two-argument groups, separate each group
 
3824
     with an empty format string, as
 
3825
 
 
3826
          plot3 (X1, C1, "", C2, "", ...)
 
3827
 
 
3828
     An example of the use of `plot3' is
 
3829
 
 
3830
             z = [0:0.05:5];
 
3831
             plot3 (cos(2*pi*z), sin(2*pi*z), z, ";helix;");
 
3832
             plot3 (z, exp(2i*pi*z), ";complex sinusoid;");
 
3833
 
 
3834
 
 
3835
     *See also:* plot.
 
3836
 
 
3837
 -- Function File:  view (AZIMUTH, ELEVATION)
 
3838
 -- Function File:  view (DIMS)
 
3839
 -- Function File: [AZIMUTH, ELEVATION] = view ()
 
3840
     Set or get the viewpoint for the current axes.
 
3841
 
 
3842
 -- Function File:  shading (TYPE)
 
3843
 -- Function File:  shading (AX, ...)
 
3844
     Set the shading of surface or patch graphic objects. Valid
 
3845
     arguments for TYPE are `"flat"', `"interp"', or `"faceted"'.  If
 
3846
     AX is given the shading is applied to axis AX instead of the
 
3847
     current axis.
 
3848
 
 
3849
 
 
3850
File: octave.info,  Node: Plot Annotations,  Next: Multiple Plots on One Page,  Prev: Three-Dimensional Plotting,  Up: Plotting Basics
 
3851
 
 
3852
15.1.3 Plot Annotations
 
3853
-----------------------
 
3854
 
 
3855
You can add titles, axis labels, legends, and arbitrary text to an
 
3856
existing plot.  For example,
 
3857
 
 
3858
     x = -10:0.1:10;
 
3859
     plot (x, sin (x));
 
3860
     title ("sin(x) for x = -10:0.1:10");
 
3861
     xlabel ("x");
 
3862
     ylabel ("sin (x)");
 
3863
     text (pi, 0.7, "arbitrary text");
 
3864
     legend ("sin (x)");
 
3865
 
 
3866
   The functions `grid' and `box' may also be used to add grid and
 
3867
border lines to the plot.  By default, the grid is off and the border
 
3868
lines are on.
 
3869
 
 
3870
 -- Function File:  title (TITLE)
 
3871
     Create a title object and return a handle to it.
 
3872
 
 
3873
 -- Function File:  legend (ST1, ST2, ...)
 
3874
 -- Function File:  legend (ST1, ST2, ..., "location", POS)
 
3875
 -- Function File:  legend (MATSTR)
 
3876
 -- Function File:  legend (MATSTR, "location", POS)
 
3877
 -- Function File:  legend (CELL)
 
3878
 -- Function File:  legend (CELL, "location", POS)
 
3879
 -- Function File:  legend ('FUNC')
 
3880
     Display a legend for the current axes using the specified strings
 
3881
     as labels.  Legend entries may be specified as individual character
 
3882
     string arguments, a character array, or a cell array of character
 
3883
     strings.  Legend works on line graphs, bar graphs, etc.  A plot
 
3884
     must exist before legend is called.
 
3885
 
 
3886
     The optional parameter POS specifies the location of the legend as
 
3887
     follows:
 
3888
 
 
3889
          north      center top
 
3890
          south      center bottom
 
3891
          east       right center
 
3892
          west       left center
 
3893
          northeast  right top (default)
 
3894
          northwest  left top
 
3895
          southeast  right bottom
 
3896
          southwest  left bottom
 
3897
 
 
3898
          outside    can be appended to any location string
 
3899
 
 
3900
     Some specific functions are directly available using FUNC:
 
3901
 
 
3902
    "show"
 
3903
          Show legends from the plot
 
3904
 
 
3905
    "hide"
 
3906
    "off"
 
3907
          Hide legends from the plot
 
3908
 
 
3909
    "boxon"
 
3910
          Draw a box around legends
 
3911
 
 
3912
    "boxoff"
 
3913
          Withdraw the box around legends
 
3914
 
 
3915
    "left"
 
3916
          Text is to the left of the keys
 
3917
 
 
3918
    "right"
 
3919
          Text is to the right of the keys
 
3920
 
 
3921
 -- Function File: H = text (X, Y, LABEL)
 
3922
 -- Function File: H = text (X, Y, Z, LABEL)
 
3923
 -- Function File: H = text (X, Y, LABEL, P1, V1, ...)
 
3924
 -- Function File: H = text (X, Y, Z, LABEL, P1, V1, ...)
 
3925
     Create a text object with text LABEL at position X, Y, Z on the
 
3926
     current axes.  Property-value pairs following LABEL may be used to
 
3927
     specify the appearance of the text.
 
3928
 
 
3929
 -- Function File:  xlabel (STRING)
 
3930
 -- Function File:  ylabel (STRING)
 
3931
 -- Function File:  zlabel (STRING)
 
3932
 -- Function File:  xlabel (H, STRING)
 
3933
     Specify x, y, and z axis labels for the current figure. If H is
 
3934
     specified then label the axis defined by H.
 
3935
 
 
3936
     *See also:* plot, semilogx, semilogy, loglog, polar, mesh, contour,
 
3937
     bar, stairs,  ylabel, title.
 
3938
 
 
3939
 -- Function File:  box (ARG)
 
3940
 -- Function File:  box (H, ...)
 
3941
     Control the display of a border around the plot.  The argument may
 
3942
     be either `"on"' or `"off"'.  If it is omitted, the current box
 
3943
     state is toggled.
 
3944
 
 
3945
     *See also:* grid.
 
3946
 
 
3947
 -- Function File:  grid (ARG)
 
3948
 -- Function File:  grid ("minor", ARG2)
 
3949
     Force the display of a grid on the plot.  The argument may be
 
3950
     either `"on"' or `"off"'.  If it is omitted, the current grid
 
3951
     state is toggled.
 
3952
 
 
3953
     If ARG is `"minor"' then the minor grid is toggled.  When using a
 
3954
     minor grid a second argument ARG2 is allowed, which can be either
 
3955
     `"on"' or `"off"' to explicitly set the state of the minor grid.
 
3956
 
 
3957
     *See also:* plot.
 
3958
 
 
3959
 
 
3960
File: octave.info,  Node: Multiple Plots on One Page,  Next: Multiple Plot Windows,  Prev: Plot Annotations,  Up: Plotting Basics
 
3961
 
 
3962
15.1.4 Multiple Plots on One Page
 
3963
---------------------------------
 
3964
 
 
3965
Octave can display more than one plot in a single figure.  The simplest
 
3966
way to do this is to use the `subplot' function to divide the plot area
 
3967
into a series of subplot windows that are indexed by an integer.  For
 
3968
example,
 
3969
 
 
3970
     subplot (2, 1, 1)
 
3971
     fplot (@sin, [-10, 10]);
 
3972
     subplot (2, 1, 2)
 
3973
     fplot (@cos, [-10, 10]);
 
3974
 
 
3975
creates a figure with two separate axes, one displaying a sine wave and
 
3976
the other a cosine wave.  The first call to subplot divides the figure
 
3977
into two plotting areas (two rows and one column) and makes the first
 
3978
plot area active.  The grid of plot areas created by `subplot' is
 
3979
numbered in column-major order (top to bottom, left to right).
 
3980
 
 
3981
 -- Function File:  subplot (ROWS, COLS, INDEX)
 
3982
 -- Function File:  subplot (RCN)
 
3983
     Set up a plot grid with COLS by ROWS subwindows and plot in
 
3984
     location given by INDEX.
 
3985
 
 
3986
     If only one argument is supplied, then it must be a three digit
 
3987
     value specifying the location in digits 1 (rows) and 2 (columns)
 
3988
     and the plot index in digit 3.
 
3989
 
 
3990
     The plot index runs row-wise.  First all the columns in a row are
 
3991
     filled and then the next row is filled.
 
3992
 
 
3993
     For example, a plot with 2 by 3 grid will have plot indices
 
3994
     running as follows:
 
3995
 
 
3996
               +-----+-----+-----+
 
3997
               |  1  |  2  |  3  |
 
3998
               +-----+-----+-----+
 
3999
               |  4  |  5  |  6  |
 
4000
               +-----+-----+-----+
 
4001
 
 
4002
 
 
4003
     *See also:* plot.
 
4004
 
 
4005
 
 
4006
File: octave.info,  Node: Multiple Plot Windows,  Next: Printing Plots,  Prev: Multiple Plots on One Page,  Up: Plotting Basics
 
4007
 
 
4008
15.1.5 Multiple Plot Windows
 
4009
----------------------------
 
4010
 
 
4011
You can open multiple plot windows using the `figure' function.  For
 
4012
example
 
4013
 
 
4014
     figure (1);
 
4015
     fplot (@sin, [-10, 10]);
 
4016
     figure (2);
 
4017
     fplot (@cos, [-10, 10]);
 
4018
 
 
4019
creates two figures, with the first displaying a sine wave and the
 
4020
second a cosine wave.  Figure numbers must be positive integers.
 
4021
 
 
4022
 -- Function File:  figure (N)
 
4023
 -- Function File:  figure (N, PROPERTY, VALUE, ...)
 
4024
     Set the current plot window to plot window N.  If no arguments are
 
4025
     specified, the next available window number is chosen.
 
4026
 
 
4027
     Multiple property-value pairs may be specified for the figure, but
 
4028
     they must appear in pairs.
 
4029
 
 
4030
 
 
4031
File: octave.info,  Node: Printing Plots,  Next: Test Plotting Functions,  Prev: Multiple Plot Windows,  Up: Plotting Basics
 
4032
 
 
4033
15.1.6 Printing Plots
 
4034
---------------------
 
4035
 
 
4036
The `print' command allows you to save plots in a variety of formats.
 
4037
For example,
 
4038
 
 
4039
     print -deps foo.eps
 
4040
 
 
4041
writes the current figure to an encapsulated PostScript file called
 
4042
`foo.eps'.
 
4043
 
 
4044
 -- Function File:  print (FILENAME, OPTIONS)
 
4045
     Print a graph, or save it to a file
 
4046
 
 
4047
     FILENAME defines the file name of the output file. If no filename
 
4048
     is specified, output is sent to the printer.
 
4049
 
 
4050
     OPTIONS:
 
4051
    `-PPRINTER'
 
4052
          Set the PRINTER name to which the graph is sent if no
 
4053
          FILENAME is specified.
 
4054
 
 
4055
    `-color'
 
4056
    `-mono'
 
4057
          Monochrome or colour lines.
 
4058
 
 
4059
    `-solid'
 
4060
    `-dashed'
 
4061
          Solid or dashed lines.
 
4062
 
 
4063
    `-portrait'
 
4064
    `-landscape'
 
4065
          Plot orientation, as returned by "orient".
 
4066
 
 
4067
    `-dDEVICE'
 
4068
          Output device, where DEVICE is one of:
 
4069
         `ps'
 
4070
         `ps2'
 
4071
         `psc'
 
4072
         `psc2'
 
4073
               Postscript (level 1 and 2, mono and color)
 
4074
 
 
4075
         `eps'
 
4076
         `eps2'
 
4077
         `epsc'
 
4078
         `epsc2'
 
4079
               Encapsulated postscript (level 1 and 2, mono and color)
 
4080
 
 
4081
         `tex'
 
4082
         `epslatex'
 
4083
         `epslatexstandalone'
 
4084
         `pstex'
 
4085
         `pslatex'
 
4086
               Generate a LaTeX (or TeX) file for labels, and eps/ps for
 
4087
                  graphics.  The file produced by `epslatexstandalone'
 
4088
               can be     processed directly by LaTeX.  The other
 
4089
               formats are intended to     be included in a LaTeX (or
 
4090
               TeX) document.  The `tex' device     is the same as the
 
4091
               `epslatex' device.
 
4092
 
 
4093
         `ill'
 
4094
         `aifm'
 
4095
               Adobe Illustrator
 
4096
 
 
4097
         `cdr'
 
4098
         `corel'
 
4099
               CorelDraw
 
4100
 
 
4101
         `dxf'
 
4102
               AutoCAD
 
4103
 
 
4104
         `emf'
 
4105
               Microsoft Enhanced Metafile
 
4106
 
 
4107
         `fig'
 
4108
               XFig.  If this format is selected the additional options
 
4109
               `-textspecial' or `-textnormal' can be used to control
 
4110
                whether the special flag should be set for the text in
 
4111
               the figure     (default is `-textnormal').
 
4112
 
 
4113
         `hpgl'
 
4114
               HP plotter language
 
4115
 
 
4116
         `mf'
 
4117
               Metafont
 
4118
 
 
4119
         `png'
 
4120
               Portable network graphics
 
4121
 
 
4122
         `pbm'
 
4123
               PBMplus
 
4124
 
 
4125
         `svg'
 
4126
               Scalable vector graphics
 
4127
 
 
4128
          Other devices are supported by "convert" from ImageMagick.
 
4129
          Type   system("convert") to see what formats are available.
 
4130
 
 
4131
          If the device is omitted, it is inferred from the file
 
4132
          extension,   or if there is no filename it is sent to the
 
4133
          printer as postscript.
 
4134
 
 
4135
    `-SXSIZE,YSIZE'
 
4136
          Plot size in pixels for PNG and SVG.  If using the command
 
4137
          form of   the print function, you must quote the XSIZE,YSIZE
 
4138
          option.  For example, by writing `"-S640,480"'.
 
4139
 
 
4140
    `-FFONTNAME'
 
4141
    `-FFONTNAME:SIZE'
 
4142
    `-F:SIZE'
 
4143
          FONTNAME set the postscript font (for use with postscript,
 
4144
          aifm, corel and fig). By default, 'Helvetica' is set for
 
4145
          PS/Aifm,   and 'SwitzerlandLight' for Corel. It can also be
 
4146
          'Times-Roman'.  SIZE is given in points. FONTNAME is ignored
 
4147
          for the   fig device.
 
4148
 
 
4149
     The filename and options can be given in any order.
 
4150
 
 
4151
 -- Function File:  orient (ORIENTATION)
 
4152
     Set the default print orientation.  Valid values for ORIENTATION
 
4153
     include `"landscape"' and `"portrait"'.  If called with no
 
4154
     arguments, return the default print orientation.
 
4155
 
 
4156
 
 
4157
File: octave.info,  Node: Test Plotting Functions,  Prev: Printing Plots,  Up: Plotting Basics
 
4158
 
 
4159
15.1.7 Test Plotting Functions
 
4160
------------------------------
 
4161
 
 
4162
The functions `sombrero' and `peaks' provide a way to check that
 
4163
plotting is working.  Typing either `sombrero' or `peaks' at the Octave
 
4164
prompt should display a three dimensional plot.
 
4165
 
 
4166
 -- Function File:  sombrero (N)
 
4167
     Produce the familiar three-dimensional sombrero plot using N grid
 
4168
     lines.  If N is omitted, a value of 41 is assumed.
 
4169
 
 
4170
     The function plotted is
 
4171
 
 
4172
          z = sin (sqrt (x^2 + y^2)) / (sqrt (x^2 + y^2))
 
4173
 
 
4174
 
 
4175
     *See also:* surf, meshgrid, mesh.
 
4176
 
 
4177
 -- Function File:  peaks ()
 
4178
 -- Function File:  peaks (N)
 
4179
 -- Function File:  peaks (X, Y)
 
4180
 -- Function File: Z = peaks (...)
 
4181
 -- Function File: [X, Y, Z] = peaks (...)
 
4182
     Generate a function with lots of local maxima and minima. The
 
4183
     function has the form
 
4184
 
 
4185
 
 
4186
     f(x,y) = 3*(1-x)^2*exp(-x^2 - (y+1)^2) ...
 
4187
              - 10*(x/5 - x^3 - y^5)*exp(-x^2-y^2) ...
 
4188
              - 1/3*exp(-(x+1)^2 - y^2)
 
4189
 
 
4190
     Called without a return argument, `peaks' plots the surface of the
 
4191
     above function using `mesh'. If N is a scalar, the `peaks' returns
 
4192
     the values of the above function on a N-by-N mesh over the range
 
4193
     `[-3,3]'. The default value for N is 49.
 
4194
 
 
4195
     If N is a vector, then it represents the X and Y values of the
 
4196
     grid on which to calculate the above function. The X and Y values
 
4197
     can be specified separately.
 
4198
 
 
4199
     *See also:* surf, mesh, meshgrid.
 
4200
 
 
4201
 
 
4202
File: octave.info,  Node: Advanced Plotting,  Prev: Plotting Basics,  Up: Plotting
 
4203
 
 
4204
15.2 Advanced Plotting
 
4205
======================
 
4206
 
 
4207
* Menu:
 
4208
 
 
4209
* Graphics Objects::
 
4210
* Graphics Object Properties::
 
4211
* Managing Default Properties::
 
4212
* Colors::
 
4213
* Line Styles::
 
4214
* Marker Styles::
 
4215
* Interaction with gnuplot::
 
4216
 
 
4217
 
 
4218
File: octave.info,  Node: Graphics Objects,  Next: Graphics Object Properties,  Up: Advanced Plotting
 
4219
 
 
4220
15.2.1 Graphics Objects
 
4221
-----------------------
 
4222
 
 
4223
Plots in Octave are constructed from the following "graphics objects".
 
4224
Each graphics object has a set of properties that define its appearance
 
4225
and may also contain links to other graphics objects.  Graphics objects
 
4226
are only referenced by a numeric index, or "handle".
 
4227
 
 
4228
root figure
 
4229
     The parent of all figure objects.  The index for the root figure is
 
4230
     defined to be 0.
 
4231
 
 
4232
figure
 
4233
     A figure window.
 
4234
 
 
4235
axes
 
4236
     An set of axes.  This object is a child of a figure object and may
 
4237
     be a parent of line, text, image, patch, or surface objects.
 
4238
 
 
4239
line
 
4240
     A line in two or three dimensions.
 
4241
 
 
4242
text
 
4243
     Text annotations.
 
4244
 
 
4245
image
 
4246
     A bitmap image.
 
4247
 
 
4248
patch
 
4249
     A filled polygon, currently limited to two dimensions.
 
4250
 
 
4251
surface
 
4252
     A three-dimensional surface.
 
4253
 
 
4254
   To determine whether an object is a graphics object index or a figure
 
4255
index, use the functions `ishandle' and `isfigure'.
 
4256
 
 
4257
 -- Built-in Function:  ishandle (H)
 
4258
     Return true if H is a graphics handle and false otherwise.
 
4259
 
 
4260
 -- Function File:  isfigure (H)
 
4261
     Return true if H is a graphics handle that contains a figure
 
4262
     object and false otherwise.
 
4263
 
 
4264
   The function `gcf' returns an index to the current figure object, or
 
4265
creates one if none exists.  Similarly, `gca' returns the current axes
 
4266
object, or creates one (and its parent figure object) if none exists.
 
4267
 
 
4268
 -- Function File:  gcf ()
 
4269
     Return the current figure handle.  If a figure does not exist,
 
4270
     create one and return its handle.  The handle may then be used to
 
4271
     examine or set properties of the figure.  For example,
 
4272
 
 
4273
          fplot (@sin, [-10, 10]);
 
4274
          fig = gcf ();
 
4275
          set (fig, "visible", "off");
 
4276
 
 
4277
     plots a sine wave, finds the handle of the current figure, and then
 
4278
     makes that figure invisible.  Setting the visible property of the
 
4279
     figure to `"on"' will cause it to be displayed again.
 
4280
 
 
4281
     *See also:* get, set.
 
4282
 
 
4283
 -- Function File:  gca ()
 
4284
     Return a handle to the current axis object.  If no axis object
 
4285
     exists, create one and return its handle.  The handle may then be
 
4286
     used to examine or set properties of the axes.  For example,
 
4287
 
 
4288
          ax = gca ();
 
4289
          set (ax, "position", [0.5, 0.5, 0.5, 0.5]);
 
4290
 
 
4291
     creates an empty axes object, then changes its location and size in
 
4292
     the figure window.
 
4293
 
 
4294
     *See also:* get, set.
 
4295
 
 
4296
   The `get' and `set' functions may be used to examine and set
 
4297
properties for graphics objects.  For example,
 
4298
 
 
4299
     get (0)
 
4300
         => ans =
 
4301
            {
 
4302
              type = root figure
 
4303
              currentfigure = [](0x0)
 
4304
              children = [](0x0)
 
4305
              visible = on
 
4306
            }
 
4307
 
 
4308
returns a structure containing all the properties of the root figure.
 
4309
As with all functions in Octave, the structure is returned by value, so
 
4310
modifying it will not modify the internal root figure plot object.  To
 
4311
do that, you must use the `set' function.  Also, note that in this
 
4312
case, the `currentfigure' property is empty, which indicates that there
 
4313
is no current figure window.
 
4314
 
 
4315
   The `get' function may also be used to find the value of a single
 
4316
property.  For example,
 
4317
 
 
4318
     get (gca (), "xlim")
 
4319
         => [ 0 1 ]
 
4320
 
 
4321
returns the range of the x-axis for the current axes object in the
 
4322
current figure.
 
4323
 
 
4324
   To set graphics object properties, use the set function.  For
 
4325
example,
 
4326
 
 
4327
     set (gca (), "xlim", [-10, 10]);
 
4328
 
 
4329
sets the range of the x-axis for the current axes object in the current
 
4330
figure to `[-10, 10]'.  Additionally, calling set with a graphics
 
4331
object index as the only argument returns a structure containing the
 
4332
default values for all the properties for the given object type.  For
 
4333
example,
 
4334
 
 
4335
     set (gca ())
 
4336
 
 
4337
returns a structure containing the default property values for axes
 
4338
objects.
 
4339
 
 
4340
 -- Built-in Function:  get (H, P)
 
4341
     Return the named property P from the graphics handle H.  If P is
 
4342
     omitted, return the complete property list for H.  If H is a
 
4343
     vector, return a cell array including the property values or lists
 
4344
     respectively.
 
4345
 
 
4346
 -- Built-in Function:  set (H, P, V, ...)
 
4347
     Set the named property value or vector P to the value V for the
 
4348
     graphics handle H.
 
4349
 
 
4350
 -- Function File: PARENT = ancestor (H, TYPE)
 
4351
 -- Function File: PARENT = ancestor (H, TYPE, 'toplevel')
 
4352
     Return the first ancestor of handle object H whose type matches
 
4353
     TYPE, where TYPE is a character string. If TYPE is a cell array of
 
4354
     strings, return the first parent whose type matches any of the
 
4355
     given type strings.
 
4356
 
 
4357
     If the handle object H is of type TYPE, return H.
 
4358
 
 
4359
     If `"toplevel"' is given as a 3rd argument, return the highest
 
4360
     parent in the object hierarchy that matches the condition, instead
 
4361
     of the first (nearest) one.
 
4362
 
 
4363
     *See also:* get, set.
 
4364
 
 
4365
   You can create axes, line, and patch objects directly using the
 
4366
`axes', `line', and `patch' functions.  These objects become children
 
4367
of the current axes object.
 
4368
 
 
4369
 -- Function File:  axes ()
 
4370
 -- Function File:  axes (PROPERTY, VALUE, ...)
 
4371
 -- Function File:  axes (H)
 
4372
     Create an axes object and return a handle to it.
 
4373
 
 
4374
 -- Function File:  line ()
 
4375
 -- Function File:  line (X, Y)
 
4376
 -- Function File:  line (X, Y, Z)
 
4377
 -- Function File:  line (X, Y, Z, PROPERTY, VALUE, ...)
 
4378
     Create line object from X and Y and insert in current axes object.
 
4379
     Return a handle (or vector of handles) to the line objects created.
 
4380
 
 
4381
     Multiple property-value pairs may be specified for the line, but
 
4382
     they must appear in pairs.
 
4383
 
 
4384
 -- Function File:  patch ()
 
4385
 -- Function File:  patch (X, Y, C)
 
4386
 -- Function File:  patch (X, Y, C, OPTS)
 
4387
 -- Function File:  patch ('Faces', F, 'Vertices', V, ...)
 
4388
 -- Function File:  patch (..., PROP, VAL)
 
4389
 -- Function File:  patch (H, ...)
 
4390
 -- Function File: H =  patch (...)
 
4391
     Create patch object from X and Y with color C and insert in the
 
4392
     current axes object.  Return handle to patch object.
 
4393
 
 
4394
     For a uniform colored patch, C can be given as an RGB vector,
 
4395
     scalar value referring to the current colormap, or string value
 
4396
     (for example, "r" or "red").
 
4397
 
 
4398
 -- Function File:  surface (X, Y, Z, C)
 
4399
 -- Function File:  surface (X, Y, Z)
 
4400
 -- Function File:  surface (Z, C)
 
4401
 -- Function File:  surface (Z)
 
4402
 -- Function File:  surface (..., PROP, VAL)
 
4403
 -- Function File:  surface (H, ...)
 
4404
 -- Function File: H =  surface (...)
 
4405
     Plot a surface graphic object given matrices X, and Y from
 
4406
     `meshgrid' and a matrix Z corresponding to the X and Y coordinates
 
4407
     of the surface.  If X and Y are vectors, then a typical vertex  is
 
4408
     (X(j), Y(i), Z(i,j)).  Thus, columns of Z correspond to different
 
4409
     X values and rows of Z correspond to different Y values. If X and Y
 
4410
     are missing, they are constructed from size of the matrix Z.
 
4411
 
 
4412
     Any additional properties passed are assigned the the surface..
 
4413
 
 
4414
     *See also:* surf, mesh, patch, line.
 
4415
 
 
4416
   By default, Octave refreshes the plot window when a prompt is
 
4417
printed, or when waiting for input.  To force an update at other times,
 
4418
call the `drawnow' function.
 
4419
 
 
4420
 -- Function File:  drawnow ()
 
4421
     Update and display the current graphics.
 
4422
 
 
4423
     Octave automatically calls drawnow just before printing a prompt,
 
4424
     when `sleep' or `pause' is called, or while waiting for
 
4425
     command-line input.
 
4426
 
 
4427
   Normally, high-level plot functions like `plot' or `mesh' call
 
4428
`newplot' to initialize the state of the current axes so that the next
 
4429
plot is drawn in a blank window with default property settings.  To
 
4430
have two plots superimposed over one another, call the `hold' function.
 
4431
For example,
 
4432
 
 
4433
     hold ("on");
 
4434
     x = -10:0.1:10;
 
4435
     plot (x, sin (x));
 
4436
     plot (x, cos (x));
 
4437
     hold ("off");
 
4438
 
 
4439
displays sine and cosine waves on the same axes.  If the hold state is
 
4440
off, consecutive plotting commands like this will only display the last
 
4441
plot.
 
4442
 
 
4443
 -- Function File:  newplot ()
 
4444
     Prepare graphics engine to produce a new plot.  This function
 
4445
     should be called at the beginning of all high-level plotting
 
4446
     functions.
 
4447
 
 
4448
 -- Function File:  hold ARGS
 
4449
     Tell Octave to `hold' the current data on the plot when executing
 
4450
     subsequent plotting commands.  This allows you to execute a series
 
4451
     of plot commands and have all the lines end up on the same figure.
 
4452
     The default is for each new plot command to clear the plot device
 
4453
     first.  For example, the command
 
4454
 
 
4455
          hold on
 
4456
 
 
4457
     turns the hold state on.  An argument of `"off"' turns the hold
 
4458
     state off, and `hold' with no arguments toggles the current hold
 
4459
     state.
 
4460
 
 
4461
 -- Function File:  ishold
 
4462
     Return true if the next line will be added to the current plot, or
 
4463
     false if the plot device will be cleared before drawing the next
 
4464
     line.
 
4465
 
 
4466
   To clear the current figure, call the `clf' function.  To bring it
 
4467
to the top of the window stack, call the `shg' function.  To delete a
 
4468
graphics object, call `delete' on its index.  To close the figure
 
4469
window, call the `close' function.
 
4470
 
 
4471
 -- Function File:  clf ()
 
4472
     Clear the current figure.
 
4473
 
 
4474
     *See also:* close, delete.
 
4475
 
 
4476
 -- Function File:  shg
 
4477
     Show the graph window.  Currently, this is the same as executing
 
4478
     `drawnow'.
 
4479
 
 
4480
     *See also:* drawnow, figure.
 
4481
 
 
4482
 -- Function File:  delete (FILE)
 
4483
 -- Function File:  delete (H)
 
4484
     Delete the named file or figure handle.
 
4485
 
 
4486
 -- Command:  close
 
4487
 -- Command:  close (N)
 
4488
 -- Command:  close all
 
4489
 -- Command:  close all hidden
 
4490
     Close figure window(s) by calling the function specified by the
 
4491
     `"closerequestfcn"' property for each figure.  By default, the
 
4492
     function `closereq' is used.
 
4493
 
 
4494
     *See also:* closereq.
 
4495
 
 
4496
 -- Function File:  closereq ()
 
4497
     Close the current figure and delete all graphics objects associated
 
4498
     with it.
 
4499
 
 
4500
     *See also:* close, delete.
 
4501
 
 
4502
 
 
4503
File: octave.info,  Node: Graphics Object Properties,  Next: Managing Default Properties,  Prev: Graphics Objects,  Up: Advanced Plotting
 
4504
 
 
4505
15.2.2 Graphics Object Properties
 
4506
---------------------------------
 
4507
 
 
4508
* Menu:
 
4509
 
 
4510
* Root Figure Properties::
 
4511
* Figure Properties::
 
4512
* Axes Properties::
 
4513
* Line Properties::
 
4514
* Text Properties::
 
4515
* Image Properties::
 
4516
* Patch Properties::
 
4517
* Surface Properties::
 
4518
 
 
4519
 
 
4520
File: octave.info,  Node: Root Figure Properties,  Next: Figure Properties,  Up: Graphics Object Properties
 
4521
 
 
4522
15.2.2.1 Root Figure Properties
 
4523
...............................
 
4524
 
 
4525
`currentfigure'
 
4526
     Index to graphics object for the current figure.
 
4527
 
 
4528
 
 
4529
 
 
4530
File: octave.info,  Node: Figure Properties,  Next: Axes Properties,  Prev: Root Figure Properties,  Up: Graphics Object Properties
 
4531
 
 
4532
15.2.2.2 Figure Properties
 
4533
..........................
 
4534
 
 
4535
`nextplot'
 
4536
     May be one of
 
4537
    `"new"'
 
4538
 
 
4539
    `"add"'
 
4540
 
 
4541
    `"replace"'
 
4542
 
 
4543
    `"replacechildren"'
 
4544
 
 
4545
`closerequestfcn'
 
4546
     Handle of function to call when a figure is closed.
 
4547
 
 
4548
`currentaxes'
 
4549
     Index to graphics object of current axes.
 
4550
 
 
4551
`colormap'
 
4552
     An N-by-3 matrix containing the color map for the current axes.
 
4553
 
 
4554
`visible'
 
4555
     Either `"on"' or `"off"' to toggle display of the figure.
 
4556
 
 
4557
`paperorientation'
 
4558
     Indicates the orientation for printing.  Either `"landscape"' or
 
4559
     `"portrait"'.
 
4560
 
 
4561
 
 
4562
File: octave.info,  Node: Axes Properties,  Next: Line Properties,  Prev: Figure Properties,  Up: Graphics Object Properties
 
4563
 
 
4564
15.2.2.3 Axes Properties
 
4565
........................
 
4566
 
 
4567
`position'
 
4568
     A four-element vector specifying the coordinates of the lower left
 
4569
     corner and width and height of the plot, in normalized units.  For
 
4570
     example, `[0.2, 0.3, 0.4, 0.5]' sets the lower left corner of the
 
4571
     axes at (0.2, 0.3) and the width and height to be 0.4 and 0.5
 
4572
     respectively.
 
4573
 
 
4574
`title'
 
4575
     Index of text object for the axes title.
 
4576
 
 
4577
`box'
 
4578
     Either `"on"' or `"off"' to toggle display of the box around the
 
4579
     axes.
 
4580
 
 
4581
`key'
 
4582
     Either `"on"' or `"off"' to toggle display of the legend.  Note
 
4583
     that this property is not compatible with MATLAB and may be
 
4584
     removed in a future version of Octave.
 
4585
 
 
4586
`keybox'
 
4587
     Either `"on"' or `"off"' to toggle display of a box around the
 
4588
     legend.  Note that this property is not compatible with MATLAB and
 
4589
     may be removed in a future version of Octave.
 
4590
 
 
4591
`keypos'
 
4592
     An integer from 1 to 4 specifying the position of the legend.  1
 
4593
     indicates upper right corner, 2 indicates upper left, 3 indicates
 
4594
     lower left, and 4 indicates lower right.  Note that this property
 
4595
     is not compatible with MATLAB and may be removed in a future
 
4596
     version of Octave.
 
4597
 
 
4598
`dataaspectratio'
 
4599
     A two-element vector specifying the relative height and width of
 
4600
     the data displayed in the axes.  Setting `dataaspectratio' to `1,
 
4601
     2]' causes the length of one unit as displayed on the y axis to be
 
4602
     the same as the length of 2 units on the x axis.  Setting
 
4603
     `dataaspectratio' also forces the `dataaspectratiomode' property
 
4604
     to be set to `"manual"'.
 
4605
 
 
4606
`dataaspectratiomode'
 
4607
     Either `"manual"' or `"auto"'.
 
4608
 
 
4609
`xlim'
 
4610
`ylim'
 
4611
`zlim'
 
4612
`clim'
 
4613
     Two-element vectors defining the limits for the x, y, and z axes
 
4614
     and the Setting one of these properties also forces the
 
4615
     corresponding mode property to be set to `"manual"'.
 
4616
 
 
4617
`xlimmode'
 
4618
`ylimmode'
 
4619
`zlimmode'
 
4620
`climmode'
 
4621
     Either `"manual"' or `"auto"'.
 
4622
 
 
4623
`xlabel'
 
4624
`ylabel'
 
4625
`zlabel'
 
4626
     Indices to text objects for the axes labels.
 
4627
 
 
4628
`xgrid'
 
4629
`ygrid'
 
4630
`zgrid'
 
4631
     Either `"on"' or `"off"' to toggle display of grid lines.
 
4632
 
 
4633
`xminorgrid'
 
4634
`yminorgrid'
 
4635
`zminorgrid'
 
4636
     Either `"on"' or `"off"' to toggle display of minor grid lines.
 
4637
 
 
4638
`xtick'
 
4639
`ytick'
 
4640
`ztick'
 
4641
     Setting one of these properties also forces the corresponding mode
 
4642
     property to be set to `"manual"'.
 
4643
 
 
4644
`xtickmode'
 
4645
`ytickmode'
 
4646
`ztickmode'
 
4647
     Either `"manual"' or `"auto"'.
 
4648
 
 
4649
`xticklabel'
 
4650
`yticklabel'
 
4651
`zticklabel'
 
4652
     Setting one of these properties also forces the corresponding mode
 
4653
     property to be set to `"manual"'.
 
4654
 
 
4655
`xticklabelmode'
 
4656
`yticklabelmode'
 
4657
`zticklabelmode'
 
4658
     Either `"manual"' or `"auto"'.
 
4659
 
 
4660
`xscale'
 
4661
`yscale'
 
4662
`zscale'
 
4663
     Either `"linear"' or `"log"'.
 
4664
 
 
4665
`xdir'
 
4666
`ydir'
 
4667
`zdir'
 
4668
     Either `"forward"' or `"reverse"'.
 
4669
 
 
4670
`xaxislocation'
 
4671
`yaxislocation'
 
4672
     Either `"top"' or `"bottom"' for the x axis and `"left"' or
 
4673
     `"right"' for the y axis.
 
4674
 
 
4675
`view'
 
4676
     A three element vector specifying the view point for
 
4677
     three-dimensional plots.
 
4678
 
 
4679
`visible'
 
4680
     Either `"on"' or `"off"' to toggle display of the axes.
 
4681
 
 
4682
`nextplot'
 
4683
     May be one of
 
4684
    `"new"'
 
4685
 
 
4686
    `"add"'
 
4687
 
 
4688
    `"replace"'
 
4689
 
 
4690
    `"replacechildren"'
 
4691
 
 
4692
`outerposition'
 
4693
     A four-element vector specifying the coordinates of the lower left
 
4694
     corner and width and height of the plot, in normalized units.  For
 
4695
     example, `[0.2, 0.3, 0.4, 0.5]' sets the lower left corner of the
 
4696
     axes at (0.2, 0.3) and the width and height to be 0.4 and 0.5
 
4697
     respectively.
 
4698
 
 
4699
 
 
4700
File: octave.info,  Node: Line Properties,  Next: Text Properties,  Prev: Axes Properties,  Up: Graphics Object Properties
 
4701
 
 
4702
15.2.2.4 Line Properties
 
4703
........................
 
4704
 
 
4705
`xdata'
 
4706
`ydata'
 
4707
`zdata'
 
4708
`ldata'
 
4709
`udata'
 
4710
`xldata'
 
4711
`xudata'
 
4712
     The data to be plotted.  The `ldata' and `udata' elements are for
 
4713
     errobars in the y direction, and the `xldata' and `xudata'
 
4714
     elements are for errorbars in the x direction.
 
4715
 
 
4716
`color'
 
4717
     The RGB color of the line, or a color name.  *Note Colors::.
 
4718
 
 
4719
`linestyle'
 
4720
`linewidth'
 
4721
     *Note Line Styles::.
 
4722
 
 
4723
`marker'
 
4724
 
 
4725
`markeredgecolor'
 
4726
 
 
4727
`markerfacecolor'
 
4728
 
 
4729
`markersize'
 
4730
     *Note Marker Styles::.
 
4731
 
 
4732
`keylabel'
 
4733
     The text of the legend entry corresponding to this line.  Note
 
4734
     that this property is not compatible with MATLAB and may be
 
4735
     removed in a future version of Octave.
 
4736
 
 
4737
 
 
4738
File: octave.info,  Node: Text Properties,  Next: Image Properties,  Prev: Line Properties,  Up: Graphics Object Properties
 
4739
 
 
4740
15.2.2.5 Text Properties
 
4741
........................
 
4742
 
 
4743
`string'
 
4744
     The character string contained by the text object.
 
4745
 
 
4746
`units'
 
4747
     May be `"normalized"' or `"graph"'.
 
4748
 
 
4749
`position'
 
4750
     The coordinates of the text object.
 
4751
 
 
4752
`rotation'
 
4753
     The angle of rotation for the displayed text, measured in degrees.
 
4754
 
 
4755
`horizontalalignment'
 
4756
     May be `"left"', `"center"', or `"right"'.
 
4757
 
 
4758
`color'
 
4759
     The color of the text.  *Note Colors::.
 
4760
 
 
4761
`fontname'
 
4762
     The font used for the text.
 
4763
 
 
4764
`fontsize'
 
4765
     The size of the font, in points to use.
 
4766
 
 
4767
`fontangle'
 
4768
     Flag whether the font is italic or normal. Valid values are
 
4769
     'normal', 'italic' and 'oblique'.
 
4770
 
 
4771
`fontweight'
 
4772
     Flag whether the font is bold, etc. Valid values are 'normal',
 
4773
     'bold', 'demi' or 'light'.
 
4774
 
 
4775
`interpreter'
 
4776
     Determines how the text is rendered. Valid values are 'none',
 
4777
     'tex' or 'latex'.
 
4778
 
 
4779
   All text objects, including titles, labels, legends, and text,
 
4780
include the property 'interpreter', this property determines the manner
 
4781
in which special control sequences in the text are rendered. If the
 
4782
interpreter is set to 'none', then no rendering occurs. At this point
 
4783
the 'latex' option is not implemented and so the 'latex' interpreter
 
4784
also does not interpret the text.
 
4785
 
 
4786
   The 'tex' option implements a subset of TEX functionality in the
 
4787
rendering of the text. This allows the insertion of special characters
 
4788
such as Greek or mathematical symbols within the text. The special
 
4789
characters are also inserted with a code starting with the back-slash
 
4790
(\) character, as in the table *note tab:extended::.
 
4791
 
 
4792
   In addition, the formating of the text can be changed within the
 
4793
string with the codes
 
4794
 
 
4795
               \bf            Bold font                                   
 
4796
               \it            Italic font                                 
 
4797
               \sl            Oblique Font                                
 
4798
               \rm            Normal font                                 
 
4799
 
 
4800
   These are be used in conjunction with the { and } characters to limit
 
4801
the change in the font to part of the string. For example
 
4802
 
 
4803
     xlabel ('{\bf H} = a {\bf V}')
 
4804
 
 
4805
   where the character 'a' will not appear in a bold font. Note that to
 
4806
avoid having Octave interpret the backslash characters in the strings,
 
4807
the strings should be in single quotes.
 
4808
 
 
4809
   It is also possible to change the fontname and size within the text
 
4810
 
 
4811
        \fontname{FONTNAME}           Specify the font to use                     
 
4812
        \fontsize{SIZE}               Specify the size of the font to use         
 
4813
 
 
4814
   Finally, the superscript and subscripting can be controlled with the
 
4815
'^' and '_' characters. If the '^' or '_' is followed by a { character,
 
4816
then all of the block surrounded by the { } pair is super- or
 
4817
sub-scripted. Without the { } pair, only the character immediately
 
4818
following the '^' or '_' is super- or sub-scripted.
 
4819
 
 
4820
          \forall            \exists            \ni                
 
4821
          \cong              \Delta             \Phi               
 
4822
          \Gamma             \vartheta          \Lambda            
 
4823
          \Pi                \Theta             \Sigma             
 
4824
          \varsigma          \Omega             \Xi                
 
4825
          \Psi               \perp              \alpha             
 
4826
          \beta              \chi               \delta             
 
4827
          \epsilon           \phi               \gamma             
 
4828
          \eta               \iota              \kappa             
 
4829
          \lambda            \mu                \nu                
 
4830
          \o                 \pi                \theta             
 
4831
          \rho               \sigma             \tau               
 
4832
          \upsilon           \varpi             \omega             
 
4833
          \xi                \psi               \zeta              
 
4834
          \sim               \Upsilon           \prime             
 
4835
          \leq               \infty             \clubsuit          
 
4836
          \diamondsuit       \heartsuit         \spadesuit         
 
4837
          \leftrightarrow    \leftarrow         \uparrow           
 
4838
          \rightarrow        \downarrow         \circ              
 
4839
          \pm                \geq               \times             
 
4840
          \propto            \partial           \bullet            
 
4841
          \div               \neq               \equiv             
 
4842
          \approx            \ldots             \mid               
 
4843
          \aleph             \Im                \Re                
 
4844
          \wp                \otimes            \oplus             
 
4845
          \oslash            \cap               \cup               
 
4846
          \supset            \supseteq          \subset            
 
4847
          \subseteq          \in                \langle            
 
4848
          \rangle            \nabla             \surd              
 
4849
          \cdot              \neg               \wedge             
 
4850
          \vee               \copyright         \rfloor            
 
4851
          \lceil             \lfloor            \rceil             
 
4852
          \int                                                     
 
4853
 
 
4854
Table 15.1: Available special characters in TEX mode
 
4855
 
 
4856
   A complete example showing the capabilities of the extended text is
 
4857
 
 
4858
     x = 0:0.01:3;
 
4859
     plot(x,erf(x));
 
4860
     hold on;
 
4861
     plot(x,x,"r");
 
4862
     axis([0, 3, 0, 1]);
 
4863
     text(0.65, 0.6175, strcat('\leftarrow x = {2/\surd\pi',
 
4864
     ' {\fontsize{16}\int_{\fontsize{8}0}^{\fontsize{8}x}}',
 
4865
     ' e^{-t^2} dt} = 0.6175'))
 
4866
 
 
4867
 
 
4868
File: octave.info,  Node: Image Properties,  Next: Patch Properties,  Prev: Text Properties,  Up: Graphics Object Properties
 
4869
 
 
4870
15.2.2.6 Image Properties
 
4871
.........................
 
4872
 
 
4873
`cdata'
 
4874
     The data for the image.  Each pixel of the image corresponds to an
 
4875
     element of `cdata'.  The value of an element of `cdata' specifies
 
4876
     the row-index into the colormap of the axes object containing the
 
4877
     image.  The color value found in the color map for the given index
 
4878
     determines the color of the pixel.
 
4879
 
 
4880
`xdata'
 
4881
`ydata'
 
4882
     Two-element vectors specifying the range of the x- and y-
 
4883
     coordinates for the image.
 
4884
 
 
4885
 
 
4886
File: octave.info,  Node: Patch Properties,  Next: Surface Properties,  Prev: Image Properties,  Up: Graphics Object Properties
 
4887
 
 
4888
15.2.2.7 Patch Properties
 
4889
.........................
 
4890
 
 
4891
`cdata'
 
4892
`xdata'
 
4893
`ydata'
 
4894
`zdata'
 
4895
     Data defining the patch object.
 
4896
 
 
4897
`facecolor'
 
4898
     The fill color of the patch.  *Note Colors::.
 
4899
 
 
4900
`facealpha'
 
4901
     A number in the range [0, 1] indicating the transparency of the
 
4902
     patch.
 
4903
 
 
4904
`edgecolor'
 
4905
     The color of the line defining the patch.  *Note Colors::.
 
4906
 
 
4907
`linestyle'
 
4908
`linewidth'
 
4909
     *Note Line Styles::.
 
4910
 
 
4911
`marker'
 
4912
`markeredgecolor'
 
4913
`markerfacecolor'
 
4914
`markersize'
 
4915
     *Note Marker Styles::.
 
4916
 
 
4917
 
 
4918
File: octave.info,  Node: Surface Properties,  Prev: Patch Properties,  Up: Graphics Object Properties
 
4919
 
 
4920
15.2.2.8 Surface Properties
 
4921
...........................
 
4922
 
 
4923
`xdata'
 
4924
`ydata'
 
4925
`zdata'
 
4926
     The data determining the surface.  The `xdata' and `ydata'
 
4927
     elements are vectors and `zdata' must be a matrix.
 
4928
 
 
4929
`keylabel'
 
4930
     The text of the legend entry corresponding to this surface.  Note
 
4931
     that this property is not compatible with MATLAB and may be
 
4932
     removed in a future version of Octave.
 
4933
 
 
4934
 
 
4935
File: octave.info,  Node: Managing Default Properties,  Next: Colors,  Prev: Graphics Object Properties,  Up: Advanced Plotting
 
4936
 
 
4937
15.2.3 Managing Default Properties
 
4938
----------------------------------
 
4939
 
 
4940
Object properties have two classes of default values, "factory
 
4941
defaults" (the initial values) and "user-defined defaults", which may
 
4942
override the factory defaults.
 
4943
 
 
4944
   Although default values may be set for any object, they are set in
 
4945
parent objects and apply to child objects.  For example,
 
4946
 
 
4947
     set (0, "defaultlinecolor", "green");
 
4948
 
 
4949
sets the default line color for all objects.  The rule for constructing
 
4950
the property name to set a default value is
 
4951
 
 
4952
     default + OBJECT-TYPE + PROPERTY-NAME
 
4953
 
 
4954
   This rule can lead to some strange looking names, for example
 
4955
`defaultlinelinewidth"' specifies the default `linewidth' property for
 
4956
`line' objects.
 
4957
 
 
4958
   The example above used the root figure object, 0, so the default
 
4959
property value will apply to all line objects.  However, default values
 
4960
are hierarchical, so defaults set in a figure objects override those
 
4961
set in the root figure object.  Likewise, defaults set in axes objects
 
4962
override those set in figure or root figure objects.  For example,
 
4963
 
 
4964
     subplot (2, 1, 1);
 
4965
     set (0, "defaultlinecolor", "red");
 
4966
     set (1, "defaultlinecolor", "green");
 
4967
     set (gca (), "defaultlinecolor", "blue");
 
4968
     line (1:10, rand (1, 10));
 
4969
     subplot (2, 1, 2);
 
4970
     line (1:10, rand (1, 10));
 
4971
     figure (2)
 
4972
     line (1:10, rand (1, 10));
 
4973
 
 
4974
produces two figures.  The line in first subplot window of the first
 
4975
figure is blue because it inherits its color from its parent axes
 
4976
object.  The line in the second subplot window of the first figure is
 
4977
green because it inherits its color from its parent figure object.  The
 
4978
line in the second figure window is red because it inherits its color
 
4979
from the global root figure parent object.
 
4980
 
 
4981
   To remove a user-defined default setting, set the default property to
 
4982
the value `"remove"'.  For example,
 
4983
 
 
4984
     set (gca (), "defaultlinecolor", "remove");
 
4985
 
 
4986
removes the user-defined default line color setting from the current
 
4987
axes object.
 
4988
 
 
4989
   Getting the `"default"' property of an object returns a list of
 
4990
user-defined defaults set for the object.  For example,
 
4991
 
 
4992
     get (gca (), "default");
 
4993
 
 
4994
returns a list of user-defined default values for the current axes
 
4995
object.
 
4996
 
 
4997
   Factory default values are stored in the root figure object.  The
 
4998
command
 
4999
 
 
5000
     get (0, "factory");
 
5001
 
 
5002
returns a list of factory defaults.
 
5003
 
 
5004
 
 
5005
File: octave.info,  Node: Colors,  Next: Line Styles,  Prev: Managing Default Properties,  Up: Advanced Plotting
 
5006
 
 
5007
15.2.4 Colors
 
5008
-------------
 
5009
 
 
5010
Colors may be specified as RGB triplets with values ranging from zero to
 
5011
one, or by name.  Recognized color names include `"blue"', `"black"',
 
5012
`"cyan"', `"green"', `"magenta"', `"red"', `"white"', and `"yellow"'.
 
5013
 
 
5014
 
 
5015
File: octave.info,  Node: Line Styles,  Next: Marker Styles,  Prev: Colors,  Up: Advanced Plotting
 
5016
 
 
5017
15.2.5 Line Styles
 
5018
------------------
 
5019
 
 
5020
Line styles are specified by the following properties:
 
5021
 
 
5022
`linestyle'
 
5023
     May be one of
 
5024
    `"-"'
 
5025
          Solid lines.
 
5026
 
 
5027
    `"--"'
 
5028
          Dashed lines.
 
5029
 
 
5030
    `":"'
 
5031
          Points.
 
5032
 
 
5033
    `"-."'
 
5034
          A dash-dot line.
 
5035
 
 
5036
`linewidth'
 
5037
     A number specifying the width of the line.  The default is 1.  A
 
5038
     value of 2 is twice as wide as the default, etc.
 
5039
 
 
5040
 
 
5041
File: octave.info,  Node: Marker Styles,  Next: Interaction with gnuplot,  Prev: Line Styles,  Up: Advanced Plotting
 
5042
 
 
5043
15.2.6 Marker Styles
 
5044
--------------------
 
5045
 
 
5046
Marker styles are specified by the following properties:
 
5047
`marker'
 
5048
     A character indicating a plot marker to be place at each data
 
5049
     point, or `"none"', meaning no markers should be displayed.
 
5050
 
 
5051
`markeredgecolor'
 
5052
     The color of the edge around the marker, or `"auto"', meaning that
 
5053
     the edge color is the same as the face color.  *Note Colors::.
 
5054
 
 
5055
`markerfacecolor'
 
5056
     The color of the marker, or `"none"' to indicate that the marker
 
5057
     should not be filled.  *Note Colors::.
 
5058
 
 
5059
`markersize'
 
5060
     A number specifying the size of the marker.  The default is 1.  A
 
5061
     value of 2 is twice as large as the default, etc.
 
5062
 
 
5063
 
 
5064
File: octave.info,  Node: Interaction with gnuplot,  Prev: Marker Styles,  Up: Advanced Plotting
 
5065
 
 
5066
15.2.7 Interaction with `gnuplot'
 
5067
---------------------------------
 
5068
 
 
5069
 -- Loadable Function: VAL = gnuplot_binary ()
 
5070
 -- Loadable Function: OLD_VAL = gnuplot_binary (NEW_VAL)
 
5071
     Query or set the name of the program invoked by the plot command.
 
5072
     The default value `"gnuplot"'.  *Note Installation::.
 
5073
 
 
5074
 -- Loadable Function: VAL = gnuplot_use_title_option ()
 
5075
 -- Loadable Function: OLD_VAL = gnuplot_use_title_option (NEW_VAL)
 
5076
     If enabled, append `-title "Figure NN"' to the gnuplot command.
 
5077
     By default, this feature is enabled if the `DISPLAY' environment
 
5078
     variable is set when Octave starts.
 
5079
 
 
5080
     *This function is obsolete and will be removed from a future
 
5081
     version of Octave.*
 
5082
 
 
5083
 
 
5084
File: octave.info,  Node: Matrix Manipulation,  Next: Arithmetic,  Prev: Plotting,  Up: Top
 
5085
 
 
5086
16 Matrix Manipulation
 
5087
**********************
 
5088
 
 
5089
There are a number of functions available for checking to see if the
 
5090
elements of a matrix meet some condition, and for rearranging the
 
5091
elements of a matrix.  For example, Octave can easily tell you if all
 
5092
the elements of a matrix are finite, or are less than some specified
 
5093
value.  Octave can also rotate the elements, extract the upper- or
 
5094
lower-triangular parts, or sort the columns of a matrix.
 
5095
 
 
5096
* Menu:
 
5097
 
 
5098
* Finding Elements and Checking Conditions::
 
5099
* Rearranging Matrices::
 
5100
* Applying a Function to an Array::
 
5101
* Special Utility Matrices::
 
5102
* Famous Matrices::
 
5103
 
 
5104
 
 
5105
File: octave.info,  Node: Finding Elements and Checking Conditions,  Next: Rearranging Matrices,  Up: Matrix Manipulation
 
5106
 
 
5107
16.1 Finding Elements and Checking Conditions
 
5108
=============================================
 
5109
 
 
5110
The functions `any' and `all' are useful for determining whether any or
 
5111
all of the elements of a matrix satisfy some condition.  The `find'
 
5112
function is also useful in determining which elements of a matrix meet
 
5113
a specified condition.
 
5114
 
 
5115
 -- Built-in Function:  any (X, DIM)
 
5116
     For a vector argument, return 1 if any element of the vector is
 
5117
     nonzero.
 
5118
 
 
5119
     For a matrix argument, return a row vector of ones and zeros with
 
5120
     each element indicating whether any of the elements of the
 
5121
     corresponding column of the matrix are nonzero.  For example,
 
5122
 
 
5123
          any (eye (2, 4))
 
5124
               => [ 1, 1, 0, 0 ]
 
5125
 
 
5126
     If the optional argument DIM is supplied, work along dimension
 
5127
     DIM.  For example,
 
5128
 
 
5129
          any (eye (2, 4), 2)
 
5130
               => [ 1; 1 ]
 
5131
 
 
5132
 -- Built-in Function:  all (X, DIM)
 
5133
     The function `all' behaves like the function `any', except that it
 
5134
     returns true only if all the elements of a vector, or all the
 
5135
     elements along dimension DIM of a matrix, are nonzero.
 
5136
 
 
5137
   Since the comparison operators (*note Comparison Ops::) return
 
5138
matrices of ones and zeros, it is easy to test a matrix for many
 
5139
things, not just whether the elements are nonzero.  For example,
 
5140
 
 
5141
     all (all (rand (5) < 0.9))
 
5142
          => 0
 
5143
 
 
5144
tests a random 5 by 5 matrix to see if all of its elements are less
 
5145
than 0.9.
 
5146
 
 
5147
   Note that in conditional contexts (like the test clause of `if' and
 
5148
`while' statements) Octave treats the test as if you had typed `all
 
5149
(all (condition))'.
 
5150
 
 
5151
 -- Mapping Function:  xor (X, Y)
 
5152
     Return the `exclusive or' of the entries of X and Y.  For boolean
 
5153
     expressions X and Y, `xor (X, Y)' is true if and only if X or Y is
 
5154
     true, but not if both X and Y are true.
 
5155
 
 
5156
 -- Function File:  is_duplicate_entry (X)
 
5157
     Return non-zero if any entries in X are duplicates of one another.
 
5158
 
 
5159
 -- Function File:  diff (X, K, DIM)
 
5160
     If X is a vector of length N, `diff (X)' is the vector of first
 
5161
     differences X(2) - X(1), ..., X(n) - X(n-1).
 
5162
 
 
5163
     If X is a matrix, `diff (X)' is the matrix of column differences
 
5164
     along the first non-singleton dimension.
 
5165
 
 
5166
     The second argument is optional.  If supplied, `diff (X, K)',
 
5167
     where K is a nonnegative integer, returns the K-th differences. It
 
5168
     is possible that K is larger than then first non-singleton
 
5169
     dimension of the matrix. In this case, `diff' continues to take
 
5170
     the differences along the next non-singleton dimension.
 
5171
 
 
5172
     The dimension along which to take the difference can be explicitly
 
5173
     stated with the optional variable DIM. In this case the K-th order
 
5174
     differences are calculated along this dimension.  In the case
 
5175
     where K exceeds `size (X, DIM)' then an empty matrix is returned.
 
5176
 
 
5177
 -- Mapping Function:  isinf (X)
 
5178
     Return 1 for elements of X that are infinite and zero otherwise.
 
5179
     For example,
 
5180
 
 
5181
          isinf ([13, Inf, NA, NaN])
 
5182
               => [ 0, 1, 0, 0 ]
 
5183
 
 
5184
 -- Mapping Function:  isnan (X)
 
5185
     Return 1 for elements of X that are NaN values and zero otherwise.
 
5186
     NA values are also considered NaN values.  For example,
 
5187
 
 
5188
          isnan ([13, Inf, NA, NaN])
 
5189
               => [ 0, 0, 1, 1 ]
 
5190
 
 
5191
 -- Mapping Function:  finite (X)
 
5192
     Return 1 for elements of X that are finite values and zero
 
5193
     otherwise. For example,
 
5194
 
 
5195
          finite ([13, Inf, NA, NaN])
 
5196
               => [ 1, 0, 0, 0 ]
 
5197
 
 
5198
 -- Loadable Function:  find (X)
 
5199
 -- Loadable Function:  find (X, N)
 
5200
 -- Loadable Function:  find (X, N, DIRECTION)
 
5201
     Return a vector of indices of nonzero elements of a matrix, as a
 
5202
     row if X is a row or as a column otherwise.  To obtain a single
 
5203
     index for each matrix element, Octave pretends that the columns of
 
5204
     a matrix form one long vector (like Fortran arrays are stored).
 
5205
     For example,
 
5206
 
 
5207
          find (eye (2))
 
5208
               => [ 1; 4 ]
 
5209
 
 
5210
     If two outputs are requested, `find' returns the row and column
 
5211
     indices of nonzero elements of a matrix.  For example,
 
5212
 
 
5213
          [i, j] = find (2 * eye (2))
 
5214
               => i = [ 1; 2 ]
 
5215
               => j = [ 1; 2 ]
 
5216
 
 
5217
     If three outputs are requested, `find' also returns a vector
 
5218
     containing the nonzero values.  For example,
 
5219
 
 
5220
          [i, j, v] = find (3 * eye (2))
 
5221
               => i = [ 1; 2 ]
 
5222
               => j = [ 1; 2 ]
 
5223
               => v = [ 3; 3 ]
 
5224
 
 
5225
     If two inputs are given, N indicates the number of elements to
 
5226
     find from the beginning of the matrix or vector.
 
5227
 
 
5228
     If three inputs are given, DIRECTION should be one of "first" or
 
5229
     "last" indicating that it should start counting found elements
 
5230
     from the first or last element.
 
5231
 
 
5232
 -- Function File: [ERR, Y1, ...] = common_size (X1, ...)
 
5233
     Determine if all input arguments are either scalar or of common
 
5234
     size.  If so, ERR is zero, and YI is a matrix of the common size
 
5235
     with all entries equal to XI if this is a scalar or XI otherwise.
 
5236
     If the inputs cannot be brought to a common size, errorcode is 1,
 
5237
     and YI is XI.  For example,
 
5238
 
 
5239
          [errorcode, a, b] = common_size ([1 2; 3 4], 5)
 
5240
          => errorcode = 0
 
5241
          => a = [ 1, 2; 3, 4 ]
 
5242
          => b = [ 5, 5; 5, 5 ]
 
5243
 
 
5244
     This is useful for implementing functions where arguments can
 
5245
     either be scalars or of common size.
 
5246
 
 
5247
 
 
5248
File: octave.info,  Node: Rearranging Matrices,  Next: Applying a Function to an Array,  Prev: Finding Elements and Checking Conditions,  Up: Matrix Manipulation
 
5249
 
 
5250
16.2 Rearranging Matrices
 
5251
=========================
 
5252
 
 
5253
 -- Function File:  fliplr (X)
 
5254
     Return a copy of X with the order of the columns reversed.  For
 
5255
     example,
 
5256
 
 
5257
          fliplr ([1, 2; 3, 4])
 
5258
          =>  2  1
 
5259
                   4  3
 
5260
 
 
5261
     Note that `fliplr' only work with 2-D arrays.  To flip N-d arrays
 
5262
     use `flipdim' instead.
 
5263
 
 
5264
     *See also:* flipud, flipdim, rot90, rotdim.
 
5265
 
 
5266
 -- Function File:  flipud (X)
 
5267
     Return a copy of X with the order of the rows reversed.  For
 
5268
     example,
 
5269
 
 
5270
          flipud ([1, 2; 3, 4])
 
5271
          =>  3  4
 
5272
                   1  2
 
5273
 
 
5274
     Due to the difficulty of defining which axis about which to flip
 
5275
     the matrix `flipud' only work with 2-d arrays.  To flip N-d arrays
 
5276
     use `flipdim' instead.
 
5277
 
 
5278
     *See also:* fliplr, flipdim, rot90, rotdim.
 
5279
 
 
5280
 -- Function File:  flipdim (X, DIM)
 
5281
     Return a copy of X flipped about the dimension DIM.  For example
 
5282
 
 
5283
          flipdim ([1, 2; 3, 4], 2)
 
5284
          =>  2  1
 
5285
                   4  3
 
5286
 
 
5287
 
 
5288
     *See also:* fliplr, flipud, rot90, rotdim.
 
5289
 
 
5290
 -- Function File:  rot90 (X, N)
 
5291
     Return a copy of X with the elements rotated counterclockwise in
 
5292
     90-degree increments.  The second argument is optional, and
 
5293
     specifies how many 90-degree rotations are to be applied (the
 
5294
     default value is 1).  Negative values of N rotate the matrix in a
 
5295
     clockwise direction.  For example,
 
5296
 
 
5297
          rot90 ([1, 2; 3, 4], -1)
 
5298
          =>  3  1
 
5299
                   4  2
 
5300
 
 
5301
     rotates the given matrix clockwise by 90 degrees.  The following
 
5302
     are all equivalent statements:
 
5303
 
 
5304
          rot90 ([1, 2; 3, 4], -1)
 
5305
          rot90 ([1, 2; 3, 4], 3)
 
5306
          rot90 ([1, 2; 3, 4], 7)
 
5307
 
 
5308
     Due to the difficulty of defining an axis about which to rotate the
 
5309
     matrix `rot90' only work with 2-D arrays.  To rotate N-d arrays
 
5310
     use `rotdim' instead.
 
5311
 
 
5312
     *See also:* rotdim, flipud, fliplr, flipdim.
 
5313
 
 
5314
 -- Function File:  rotdim (X, N, PLANE)
 
5315
     Return a copy of X with the elements rotated counterclockwise in
 
5316
     90-degree increments.  The second argument is optional, and
 
5317
     specifies how many 90-degree rotations are to be applied (the
 
5318
     default value is 1).  The third argument is also optional and
 
5319
     defines the plane of the rotation. As such PLANE is a two element
 
5320
     vector containing two different valid dimensions of the matrix. If
 
5321
     PLANE is not given Then the first two non-singleton dimensions are
 
5322
     used.
 
5323
 
 
5324
     Negative values of N rotate the matrix in a clockwise direction.
 
5325
     For example,
 
5326
 
 
5327
          rotdim ([1, 2; 3, 4], -1, [1, 2])
 
5328
          =>  3  1
 
5329
                   4  2
 
5330
 
 
5331
     rotates the given matrix clockwise by 90 degrees.  The following
 
5332
     are all equivalent statements:
 
5333
 
 
5334
          rotdim ([1, 2; 3, 4], -1, [1, 2])
 
5335
          rotdim ([1, 2; 3, 4], 3, [1, 2])
 
5336
          rotdim ([1, 2; 3, 4], 7, [1, 2])
 
5337
 
 
5338
 
 
5339
     *See also:* rot90, flipud, fliplr, flipdim.
 
5340
 
 
5341
 -- Built-in Function:  cat (DIM, ARRAY1, ARRAY2, ..., ARRAYN)
 
5342
     Return the concatenation of N-d array objects, ARRAY1, ARRAY2,
 
5343
     ..., ARRAYN along dimension DIM.
 
5344
 
 
5345
          A = ones (2, 2);
 
5346
          B = zeros (2, 2);
 
5347
          cat (2, A, B)
 
5348
          => ans =
 
5349
 
 
5350
               1 1 0 0
 
5351
               1 1 0 0
 
5352
 
 
5353
     Alternatively, we can concatenate A and B along the second
 
5354
     dimension the following way:
 
5355
 
 
5356
          [A, B].
 
5357
 
 
5358
     DIM can be larger than the dimensions of the N-d array objects and
 
5359
     the result will thus have DIM dimensions as the following example
 
5360
     shows:
 
5361
          cat (4, ones(2, 2), zeros (2, 2))
 
5362
          => ans =
 
5363
 
 
5364
             ans(:,:,1,1) =
 
5365
 
 
5366
               1 1
 
5367
               1 1
 
5368
 
 
5369
             ans(:,:,1,2) =
 
5370
               0 0
 
5371
               0 0
 
5372
 
 
5373
 
 
5374
     *See also:* horzcat, vertcat.
 
5375
 
 
5376
 -- Built-in Function:  horzcat (ARRAY1, ARRAY2, ..., ARRAYN)
 
5377
     Return the horizontal concatenation of N-d array objects, ARRAY1,
 
5378
     ARRAY2, ..., ARRAYN along dimension 2.
 
5379
 
 
5380
     *See also:* cat, vertcat.
 
5381
 
 
5382
 -- Built-in Function:  vertcat (ARRAY1, ARRAY2, ..., ARRAYN)
 
5383
     Return the vertical concatenation of N-d array objects, ARRAY1,
 
5384
     ARRAY2, ..., ARRAYN along dimension 1.
 
5385
 
 
5386
     *See also:* cat, horzcat.
 
5387
 
 
5388
 -- Built-in Function:  permute (A, PERM)
 
5389
     Return the generalized transpose for an N-d array object A.  The
 
5390
     permutation vector PERM must contain the elements `1:ndims(a)' (in
 
5391
     any order, but each element must appear just once).
 
5392
 
 
5393
     *See also:* ipermute.
 
5394
 
 
5395
 -- Built-in Function:  ipermute (A, IPERM)
 
5396
     The inverse of the `permute' function.  The expression
 
5397
 
 
5398
          ipermute (permute (a, perm), perm)
 
5399
     returns the original array A.
 
5400
 
 
5401
     *See also:* permute.
 
5402
 
 
5403
 -- Built-in Function:  reshape (A, M, N, ...)
 
5404
 -- Built-in Function:  reshape (A, SIZ)
 
5405
     Return a matrix with the given dimensions whose elements are taken
 
5406
     from the matrix A.  The elements of the matrix are accessed in
 
5407
     column-major order (like Fortran arrays are stored).
 
5408
 
 
5409
     For example,
 
5410
 
 
5411
          reshape ([1, 2, 3, 4], 2, 2)
 
5412
               =>  1  3
 
5413
                   2  4
 
5414
 
 
5415
     Note that the total number of elements in the original matrix must
 
5416
     match the total number of elements in the new matrix.
 
5417
 
 
5418
     A single dimension of the return matrix can be unknown and is
 
5419
     flagged by an empty argument.
 
5420
 
 
5421
 -- Function File: Y = circshift (X, N)
 
5422
     Circularly shifts the values of the array X. N must be a vector of
 
5423
     integers no longer than the number of dimensions in X. The values
 
5424
     of N can be either positive or negative, which determines the
 
5425
     direction in which the values or X are shifted. If an element of N
 
5426
     is zero, then the corresponding dimension of X will not be
 
5427
     shifted. For example
 
5428
 
 
5429
          x = [1, 2, 3; 4, 5, 6; 7, 8, 9];
 
5430
          circshift (x, 1)
 
5431
          =>  7, 8, 9
 
5432
              1, 2, 3
 
5433
              4, 5, 6
 
5434
          circshift (x, -2)
 
5435
          =>  7, 8, 9
 
5436
              1, 2, 3
 
5437
              4, 5, 6
 
5438
          circshift (x, [0,1])
 
5439
          =>  3, 1, 2
 
5440
              6, 4, 5
 
5441
              9, 7, 8
 
5442
 
 
5443
 
 
5444
     *See also:* permute, ipermute, shiftdim.
 
5445
 
 
5446
 -- Function File: Y = shiftdim (X, N)
 
5447
 -- Function File: [Y, NS] = shiftdim (X)
 
5448
     Shifts the dimension of X by N, where N must be an integer scalar.
 
5449
     When N is positive, the dimensions of X are shifted to the left,
 
5450
     with the leading dimensions circulated to the end. If N is
 
5451
     negative, then the dimensions of X are shifted to the right, with
 
5452
     N leading singleton dimensions added.
 
5453
 
 
5454
     Called with a single argument, `shiftdim', removes the leading
 
5455
     singleton dimensions, returning the number of dimensions removed
 
5456
     in the second output argument NS.
 
5457
 
 
5458
     For example
 
5459
 
 
5460
          x = ones (1, 2, 3);
 
5461
          size (shiftdim (x, -1))
 
5462
          => [1, 1, 2, 3]
 
5463
          size (shiftdim (x, 1))
 
5464
          => [2, 3]
 
5465
          [b, ns] = shiftdim (x);
 
5466
          => b =  [1, 1, 1; 1, 1, 1]
 
5467
          => ns = 1
 
5468
 
 
5469
 
 
5470
     *See also:* reshape, permute, ipermute, circshift, squeeze.
 
5471
 
 
5472
 -- Function File:  shift (X, B)
 
5473
 -- Function File:  shift (X, B, DIM)
 
5474
     If X is a vector, perform a circular shift of length B of the
 
5475
     elements of X.
 
5476
 
 
5477
     If X is a matrix, do the same for each column of X.  If the
 
5478
     optional DIM argument is given, operate along this dimension
 
5479
 
 
5480
 -- Loadable Function: [S, I] = sort (X)
 
5481
 -- Loadable Function: [S, I] = sort (X, DIM)
 
5482
 -- Loadable Function: [S, I] = sort (X, MODE)
 
5483
 -- Loadable Function: [S, I] = sort (X, DIM, MODE)
 
5484
     Return a copy of X with the elements arranged in increasing order.
 
5485
     For matrices, `sort' orders the elements in each column.
 
5486
 
 
5487
     For example,
 
5488
 
 
5489
          sort ([1, 2; 2, 3; 3, 1])
 
5490
               =>  1  1
 
5491
                   2  2
 
5492
                   3  3
 
5493
 
 
5494
     The `sort' function may also be used to produce a matrix
 
5495
     containing the original row indices of the elements in the sorted
 
5496
     matrix.  For example,
 
5497
 
 
5498
          [s, i] = sort ([1, 2; 2, 3; 3, 1])
 
5499
               => s = 1  1
 
5500
                      2  2
 
5501
                      3  3
 
5502
               => i = 1  3
 
5503
                      2  1
 
5504
                      3  2
 
5505
 
 
5506
     If the optional argument DIM is given, then the matrix is sorted
 
5507
     along the dimension defined by DIM. The optional argument `mode'
 
5508
     defines the order in which the values will be sorted. Valid values
 
5509
     of `mode' are `ascend' or `descend'.
 
5510
 
 
5511
     For equal elements, the indices are such that the equal elements
 
5512
     are listed in the order that appeared in the original list.
 
5513
 
 
5514
     The `sort' function may also be used to sort strings and cell
 
5515
     arrays of strings, in which case the dictionary order of the
 
5516
     strings is used.
 
5517
 
 
5518
     The algorithm used in `sort' is optimized for the sorting of
 
5519
     partially ordered lists.
 
5520
 
 
5521
 -- Function File:  sortrows (A, C)
 
5522
     Sort the rows of the matrix A according to the order of the
 
5523
     columns specified in C.  If C is omitted, a lexicographical sort
 
5524
     is used.
 
5525
 
 
5526
   Since the `sort' function does not allow sort keys to be specified,
 
5527
it can't be used to order the rows of a matrix according to the values
 
5528
of the elements in various columns(1) in a single call.  Using the
 
5529
second output, however, it is possible to sort all rows based on the
 
5530
values in a given column.  Here's an example that sorts the rows of a
 
5531
matrix based on the values in the second column.
 
5532
 
 
5533
     a = [1, 2; 2, 3; 3, 1];
 
5534
     [s, i] = sort (a (:, 2));
 
5535
     a (i, :)
 
5536
          =>  3  1
 
5537
              1  2
 
5538
              2  3
 
5539
 
 
5540
 -- Function File:  swap (INPUTS)
 
5541
     [a1,b1] = swap(a,b)
 
5542
     interchange a and b
 
5543
 
 
5544
 -- Function File:  swapcols (inputs)
 
5545
      function B = swapcols(A)
 
5546
      permute columns of A into reverse order
 
5547
 
 
5548
 -- Function File:  swaprows (inputs)
 
5549
      function B = swaprows(A)
 
5550
      permute rows of A into reverse order
 
5551
 
 
5552
 -- Function File:  tril (A, K)
 
5553
 -- Function File:  triu (A, K)
 
5554
     Return a new matrix formed by extracting the lower (`tril') or
 
5555
     upper (`triu') triangular part of the matrix A, and setting all
 
5556
     other elements to zero.  The second argument is optional, and
 
5557
     specifies how many diagonals above or below the main diagonal
 
5558
     should also be set to zero.
 
5559
 
 
5560
     The default value of K is zero, so that `triu' and `tril' normally
 
5561
     include the main diagonal as part of the result matrix.
 
5562
 
 
5563
     If the value of K is negative, additional elements above (for
 
5564
     `tril') or below (for `triu') the main diagonal are also selected.
 
5565
 
 
5566
     The absolute value of K must not be greater than the number of
 
5567
     sub- or super-diagonals.
 
5568
 
 
5569
     For example,
 
5570
 
 
5571
          tril (ones (3), -1)
 
5572
          =>  0  0  0
 
5573
                   1  0  0
 
5574
                   1  1  0
 
5575
 
 
5576
     and
 
5577
 
 
5578
          tril (ones (3), 1)
 
5579
          =>  1  1  0
 
5580
                   1  1  1
 
5581
                   1  1  1
 
5582
 
 
5583
 
 
5584
     *See also:* triu, diag.
 
5585
 
 
5586
 -- Function File:  vec (X)
 
5587
     Return the vector obtained by stacking the columns of the matrix X
 
5588
     one above the other.
 
5589
 
 
5590
 -- Function File:  vech (X)
 
5591
     Return the vector obtained by eliminating all supradiagonal
 
5592
     elements of the square matrix X and stacking the result one column
 
5593
     above the other.
 
5594
 
 
5595
 -- Function File:  prepad (X, L, C)
 
5596
 -- Function File:  postpad (X, L, C)
 
5597
 -- Function File:  postpad (X, L, C, DIM)
 
5598
     Prepends (appends) the scalar value C to the vector X until it is
 
5599
     of length L.  If the third argument is not supplied, a value of 0
 
5600
     is used.
 
5601
 
 
5602
     If `length (X) > L', elements from the beginning (end) of X are
 
5603
     removed until a vector of length L is obtained.
 
5604
 
 
5605
     If X is a matrix, elements are prepended or removed from each row.
 
5606
 
 
5607
     If the optional DIM argument is given, then operate along this
 
5608
     dimension.
 
5609
 
 
5610
 -- Function File:  blkdiag (A, B, C, ...)
 
5611
     Build a block diagonal matrix from A, B, C, ....  All the
 
5612
     arguments must be numeric and are two-dimensional matrices or
 
5613
     scalars.
 
5614
 
 
5615
     *See also:* diag, horzcat, vertcat.
 
5616
 
 
5617
   ---------- Footnotes ----------
 
5618
 
 
5619
   (1) For example, to first sort based on the values in column 1, and
 
5620
then, for any values that are repeated in column 1, sort based on the
 
5621
values found in column 2, etc.
 
5622
 
 
5623
 
 
5624
File: octave.info,  Node: Applying a Function to an Array,  Next: Special Utility Matrices,  Prev: Rearranging Matrices,  Up: Matrix Manipulation
 
5625
 
 
5626
16.3 Applying a Function to an Array
 
5627
====================================
 
5628
 
 
5629
 -- Function File: A = arrayfun (NAME, C)
 
5630
 -- Function File: A = arrayfun (FUNC, C)
 
5631
 -- Function File: A = arrayfun (FUNC, C, D)
 
5632
 -- Function File: A = arrayfun (FUNC, C, OPTIONS)
 
5633
 -- Function File: [A, B, ...] = arrayfun (FUNC, C, ...)
 
5634
     Execute a function on each element of an array.  This is useful for
 
5635
     functions that do not accept array arguments.  If the function does
 
5636
     accept array arguments it is better to call the function directly.
 
5637
 
 
5638
     See `cellfun' for complete usage instructions.
 
5639
 
 
5640
     *See also:* cellfun.
 
5641
 
 
5642
 -- Loadable Function:  bsxfun (F, A, B)
 
5643
     Applies a binary function F element-wise to two matrix arguments A
 
5644
     and B. The function F must be capable of accepting two column
 
5645
     vector arguments of equal length, or one column vector argument
 
5646
     and a scalar.
 
5647
 
 
5648
     The dimensions of A and B must be equal or singleton. The
 
5649
     singleton dimensions of the matrices will be expanded to the same
 
5650
     dimensionality as the other matrix.
 
5651
 
 
5652
 
 
5653
     *See also:* arrayfun, cellfun.
 
5654
 
 
5655
 
 
5656
File: octave.info,  Node: Special Utility Matrices,  Next: Famous Matrices,  Prev: Applying a Function to an Array,  Up: Matrix Manipulation
 
5657
 
 
5658
16.4 Special Utility Matrices
 
5659
=============================
 
5660
 
 
5661
 -- Built-in Function:  eye (X)
 
5662
 -- Built-in Function:  eye (N, M)
 
5663
 -- Built-in Function:  eye (..., CLASS)
 
5664
     Return an identity matrix.  If invoked with a single scalar
 
5665
     argument, `eye' returns a square matrix with the dimension
 
5666
     specified.  If you supply two scalar arguments, `eye' takes them
 
5667
     to be the number of rows and columns.  If given a vector with two
 
5668
     elements, `eye' uses the values of the elements as the number of
 
5669
     rows and columns, respectively.  For example,
 
5670
 
 
5671
          eye (3)
 
5672
               =>  1  0  0
 
5673
                   0  1  0
 
5674
                   0  0  1
 
5675
 
 
5676
     The following expressions all produce the same result:
 
5677
 
 
5678
          eye (2)
 
5679
          ==
 
5680
          eye (2, 2)
 
5681
          ==
 
5682
          eye (size ([1, 2; 3, 4])
 
5683
 
 
5684
     The optional argument CLASS, allows `eye' to return an array of
 
5685
     the specified type, like
 
5686
 
 
5687
          val = zeros (n,m, "uint8")
 
5688
 
 
5689
     Calling `eye' with no arguments is equivalent to calling it with
 
5690
     an argument of 1.  This odd definition is for compatibility with
 
5691
     MATLAB.
 
5692
 
 
5693
 -- Built-in Function:  ones (X)
 
5694
 -- Built-in Function:  ones (N, M)
 
5695
 -- Built-in Function:  ones (N, M, K, ...)
 
5696
 -- Built-in Function:  ones (..., CLASS)
 
5697
     Return a matrix or N-dimensional array whose elements are all 1.
 
5698
     The arguments are handled the same as the arguments for `eye'.
 
5699
 
 
5700
     If you need to create a matrix whose values are all the same, you
 
5701
     should use an expression like
 
5702
 
 
5703
          val_matrix = val * ones (n, m)
 
5704
 
 
5705
     The optional argument CLASS, allows `ones' to return an array of
 
5706
     the specified type, for example
 
5707
 
 
5708
          val = ones (n,m, "uint8")
 
5709
 
 
5710
 -- Built-in Function:  zeros (X)
 
5711
 -- Built-in Function:  zeros (N, M)
 
5712
 -- Built-in Function:  zeros (N, M, K, ...)
 
5713
 -- Built-in Function:  zeros (..., CLASS)
 
5714
     Return a matrix or N-dimensional array whose elements are all 0.
 
5715
     The arguments are handled the same as the arguments for `eye'.
 
5716
 
 
5717
     The optional argument CLASS, allows `zeros' to return an array of
 
5718
     the specified type, for example
 
5719
 
 
5720
          val = zeros (n,m, "uint8")
 
5721
 
 
5722
 -- Function File:  repmat (A, M, N)
 
5723
 -- Function File:  repmat (A, [M N])
 
5724
 -- Function File:  repmat (A, [M N P ...])
 
5725
     Form a block matrix of size M by N, with a copy of matrix A as
 
5726
     each element.  If N is not specified, form an M by M block matrix.
 
5727
 
 
5728
 -- Loadable Function:  rand (X)
 
5729
 -- Loadable Function:  rand (N, M)
 
5730
 -- Loadable Function:  rand ("state", X)
 
5731
 -- Loadable Function:  rand ("seed", X)
 
5732
     Return a matrix with random elements uniformly distributed on the
 
5733
     interval (0, 1).  The arguments are handled the same as the
 
5734
     arguments for `eye'.
 
5735
 
 
5736
     You can query the state of the random number generator using the
 
5737
     form
 
5738
 
 
5739
          v = rand ("state")
 
5740
 
 
5741
     This returns a column vector V of length 625. Later, you can
 
5742
     restore the random number generator to the state V using the form
 
5743
 
 
5744
          rand ("state", v)
 
5745
 
 
5746
     You may also initialize the state vector from an arbitrary vector
 
5747
     of length <= 625 for V.  This new state will be a hash based on the
 
5748
     value of V, not V itself.
 
5749
 
 
5750
     By default, the generator is initialized from `/dev/urandom' if it
 
5751
     is available, otherwise from cpu time, wall clock time and the
 
5752
     current fraction of a second.
 
5753
 
 
5754
     To compute the psuedo-random sequence, `rand' uses the Mersenne
 
5755
     Twister with a period of 2^19937-1 (See M. Matsumoto and T.
 
5756
     Nishimura, "Mersenne Twister: A 623-dimensionally equidistributed
 
5757
     uniform pseudorandom number generator", ACM Trans. on Modeling and
 
5758
     Computer Simulation Vol. 8, No. 1, January pp.3-30 1998,
 
5759
     `http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html').  Do
 
5760
     *not* use for cryptography without securely hashing several
 
5761
     returned values together, otherwise the generator state can be
 
5762
     learned after reading 624 consecutive values.
 
5763
 
 
5764
     Older versions of Octave used a different random number generator.
 
5765
     The new generator is used by default as it is significantly faster
 
5766
     than the old generator, and produces random numbers with a
 
5767
     significantly longer cycle time. However, in some circumstances it
 
5768
     might be desirable to obtain the same random sequences as used by
 
5769
     the old generators. To do this the keyword "seed" is used to
 
5770
     specify that the old generators should be use, as in
 
5771
 
 
5772
          rand ("seed", val)
 
5773
 
 
5774
     which sets the seed of the generator to VAL. The seed of the
 
5775
     generator can be queried with
 
5776
 
 
5777
          s = rand ("seed")
 
5778
 
 
5779
     However, it should be noted that querying the seed will not cause
 
5780
     `rand' to use the old generators, only setting the seed will.  To
 
5781
     cause `rand' to once again use the new generators, the keyword
 
5782
     "state" should be used to reset the state of the `rand'.
 
5783
 
 
5784
     *See also:* randn, rande, randg, randp.
 
5785
 
 
5786
 -- Loadable Function:  randn (X)
 
5787
 -- Loadable Function:  randn (N, M)
 
5788
 -- Loadable Function:  randn ("state", X)
 
5789
 -- Loadable Function:  randn ("seed", X)
 
5790
     Return a matrix with normally distributed random elements. The
 
5791
     arguments are handled the same as the arguments for `rand'.
 
5792
 
 
5793
     By default, `randn' uses a Marsaglia and Tsang Ziggurat technique
 
5794
     to transform from a uniform to a normal distribution. (G.
 
5795
     Marsaglia and W.W. Tsang, 'Ziggurat method for generating random
 
5796
     variables', J. Statistical Software, vol 5, 2000,
 
5797
     `http://www.jstatsoft.org/v05/i08/')
 
5798
 
 
5799
 
 
5800
     *See also:* rand, rande, randg, randp.
 
5801
 
 
5802
 -- Loadable Function:  rande (X)
 
5803
 -- Loadable Function:  rande (N, M)
 
5804
 -- Loadable Function:  rande ("state", X)
 
5805
 -- Loadable Function:  rande ("seed", X)
 
5806
     Return a matrix with exponentially distributed random elements. The
 
5807
     arguments are handled the same as the arguments for `rand'.
 
5808
 
 
5809
     By default, `randn' uses a Marsaglia and Tsang Ziggurat technique
 
5810
     to transform from a uniform to a exponential distribution. (G.
 
5811
     Marsaglia and W.W. Tsang, 'Ziggurat method for generating random
 
5812
     variables', J. Statistical Software, vol 5, 2000,
 
5813
     `http://www.jstatsoft.org/v05/i08/')
 
5814
 
 
5815
     *See also:* rand, randn, randg, randp.
 
5816
 
 
5817
 -- Loadable Function:  randp (L, X)
 
5818
 -- Loadable Function:  randp (L, N, M)
 
5819
 -- Loadable Function:  randp ("state", X)
 
5820
 -- Loadable Function:  randp ("seed", X)
 
5821
     Return a matrix with Poisson distributed random elements. The
 
5822
     arguments are handled the same as the arguments for `rand', except
 
5823
     for the argument L.
 
5824
 
 
5825
     Five different algorithms are used depending on the range of L and
 
5826
     whether or not L is a scalar or a matrix.
 
5827
 
 
5828
    For scalar L <= 12, use direct method.
 
5829
          Press, et al., 'Numerical Recipes in C', Cambridge University
 
5830
          Press, 1992.
 
5831
 
 
5832
    For scalar L > 12, use rejection method.[1]
 
5833
          Press, et al., 'Numerical Recipes in C', Cambridge University
 
5834
          Press, 1992.
 
5835
 
 
5836
    For matrix L <= 10, use inversion method.[2]
 
5837
          Stadlober E., et al., WinRand source code, available via FTP.
 
5838
 
 
5839
    For matrix L > 10, use patchwork rejection method.
 
5840
          Stadlober E., et al., WinRand source code, available via FTP,
 
5841
          or H. Zechner, 'Efficient sampling from continuous and
 
5842
          discrete unimodal distributions', Doctoral Dissertaion,
 
5843
          156pp., Technical University Graz, Austria, 1994.
 
5844
 
 
5845
    For L > 1e8, use normal approximation.
 
5846
          L. Montanet, et al., 'Review of Particle Properties',
 
5847
          Physical Review D 50 p1284, 1994
 
5848
 
 
5849
 
 
5850
     *See also:* rand, randn, rande, randg.
 
5851
 
 
5852
 -- Loadable Function:  randg (A, X)
 
5853
 -- Loadable Function:  randg (A, N, M)
 
5854
 -- Loadable Function:  randg ("state", X)
 
5855
 -- Loadable Function:  randg ("seed", X)
 
5856
     Return a matrix with `gamma(A,1)' distributed random elements.
 
5857
     The arguments are handled the same as the arguments for `rand',
 
5858
     except for the argument A.
 
5859
 
 
5860
     This can be used to generate many distributions:
 
5861
 
 
5862
    `gamma (a, b)' for `a > -1', `b > 0'
 
5863
               r = b * randg (a)
 
5864
 
 
5865
    `beta (a, b)' for `a > -1', `b > -1'
 
5866
               r1 = randg (a, 1)
 
5867
               r = r1 / (r1 + randg (b, 1))
 
5868
 
 
5869
    `Erlang (a, n)'
 
5870
               r = a * randg (n)
 
5871
 
 
5872
    `chisq (df)' for `df > 0'
 
5873
               r = 2 * randg (df / 2)
 
5874
 
 
5875
    `t(df)' for `0 < df < inf' (use randn if df is infinite)
 
5876
               r = randn () / sqrt (2 * randg (df / 2) / df)
 
5877
 
 
5878
    `F (n1, n2)' for `0 < n1', `0 < n2'
 
5879
               ## r1 equals 1 if n1 is infinite
 
5880
               r1 = 2 * randg (n1 / 2) / n1
 
5881
               ## r2 equals 1 if n2 is infinite
 
5882
               r2 = 2 * randg (n2 / 2) / n2
 
5883
               r = r1 / r2
 
5884
 
 
5885
    negative `binomial (n, p)' for `n > 0', `0 < p <= 1'
 
5886
               r = randp ((1 - p) / p * randg (n))
 
5887
 
 
5888
    non-central `chisq (df, L)', for `df >= 0' and `L > 0'
 
5889
          (use chisq if `L = 0')
 
5890
               r = randp (L / 2)
 
5891
               r(r > 0) = 2 * randg (r(r > 0))
 
5892
               r(df > 0) += 2 * randg (df(df > 0)/2)
 
5893
 
 
5894
    `Dirichlet (a1, ..., ak)'
 
5895
               r = (randg (a1), ..., randg (ak))
 
5896
               r = r / sum (r)
 
5897
 
 
5898
 
 
5899
     *See also:* rand, randn, rande, randp.
 
5900
 
 
5901
   The new random generators all use a common Mersenne Twister
 
5902
generator, and so the state of only one of the generators needs to be
 
5903
reset.  The old generator function use separate generators. This
 
5904
ensures that
 
5905
 
 
5906
     rand ("seed", 13);
 
5907
     randn ("seed", 13);
 
5908
     u = rand (100, 1);
 
5909
     n = randn (100, 1);
 
5910
 
 
5911
and
 
5912
 
 
5913
     rand ("seed", 13);
 
5914
     randn ("seed", 13);
 
5915
     u = zeros (100, 1);
 
5916
     n = zeros (100, 1);
 
5917
     for i = 1:100
 
5918
       u(i) = rand ();
 
5919
       n(i) = randn ();
 
5920
     end
 
5921
 
 
5922
produce equivalent results.
 
5923
 
 
5924
   Normally, `rand' and `randn' obtain their initial seeds from the
 
5925
system clock, so that the sequence of random numbers is not the same
 
5926
each time you run Octave.  If you really do need for to reproduce a
 
5927
sequence of numbers exactly, you can set the seed to a specific value.
 
5928
 
 
5929
   If it is invoked without arguments, `rand' and `randn' return a
 
5930
single element of a random sequence.
 
5931
 
 
5932
   The `rand' and `randn' functions use Fortran code from RANLIB, a
 
5933
library of fortran routines for random number generation, compiled by
 
5934
Barry W. Brown and James Lovato of the Department of Biomathematics at
 
5935
The University of Texas, M.D. Anderson Cancer Center, Houston, TX 77030.
 
5936
 
 
5937
 -- Function File:  randperm (N)
 
5938
     Return a row vector containing a random permutation of the
 
5939
     integers from 1 to N.
 
5940
 
 
5941
 -- Built-in Function:  diag (V, K)
 
5942
     Return a diagonal matrix with vector V on diagonal K.  The second
 
5943
     argument is optional.  If it is positive, the vector is placed on
 
5944
     the K-th super-diagonal.  If it is negative, it is placed on the
 
5945
     -K-th sub-diagonal.  The default value of K is 0, and the vector
 
5946
     is placed on the main diagonal.  For example,
 
5947
 
 
5948
          diag ([1, 2, 3], 1)
 
5949
               =>  0  1  0  0
 
5950
                   0  0  2  0
 
5951
                   0  0  0  3
 
5952
                   0  0  0  0
 
5953
 
 
5954
     Given a matrix argument, instead of a vector, `diag' extracts the
 
5955
     K-th diagonal of the matrix.
 
5956
 
 
5957
   The functions `linspace' and `logspace' make it very easy to create
 
5958
vectors with evenly or logarithmically spaced elements.  *Note Ranges::.
 
5959
 
 
5960
 -- Built-in Function:  linspace (BASE, LIMIT, N)
 
5961
     Return a row vector with N linearly spaced elements between BASE
 
5962
     and LIMIT.  If the number of elements is greater than one, then
 
5963
     the BASE and LIMIT are always included in the range.  If BASE is
 
5964
     greater than LIMIT, the elements are stored in decreasing order.
 
5965
     If the number of points is not specified, a value of 100 is used.
 
5966
 
 
5967
     The `linspace' function always returns a row vector.
 
5968
 
 
5969
     For compatibility with MATLAB, return the second argument if fewer
 
5970
     than two values are requested.
 
5971
 
 
5972
 -- Function File:  logspace (BASE, LIMIT, N)
 
5973
     Similar to `linspace' except that the values are logarithmically
 
5974
     spaced from 10^base to 10^limit.
 
5975
 
 
5976
     If LIMIT is equal to pi, the points are between 10^base and pi,
 
5977
     _not_ 10^base and 10^pi, in order to  be compatible with the
 
5978
     corresponding MATLAB function.
 
5979
 
 
5980
     Also for compatibility, return the second argument if fewer than
 
5981
     two values are requested.
 
5982
 
 
5983
     *See also:* linspace.
 
5984
 
 
5985
 
 
5986
File: octave.info,  Node: Famous Matrices,  Prev: Special Utility Matrices,  Up: Matrix Manipulation
 
5987
 
 
5988
16.5 Famous Matrices
 
5989
====================
 
5990
 
 
5991
The following functions return famous matrix forms.
 
5992
 
 
5993
 -- Function File:  hadamard (N)
 
5994
     Construct a Hadamard matrix HN of size N-by-N. The size N must be
 
5995
     of the form `2 ^ K * P' in which P is one of 1, 12, 20 or 28. The
 
5996
     returned matrix is normalized, meaning `Hn(:,1) == 1' and `H(1,:)
 
5997
     == 1'.
 
5998
 
 
5999
     Some of the properties of Hadamard matrices are:
 
6000
 
 
6001
        * `kron (HM, HN)' is a Hadamard matrix of size M-by-N.
 
6002
 
 
6003
        * `Hn * Hn' == N * eye (N)'.
 
6004
 
 
6005
        * The rows of HN are orthogonal.
 
6006
 
 
6007
        * `det (A) <= det (HN)' for all A with `abs (A (I, J)) <= 1'.
 
6008
 
 
6009
        * Multiply any row or column by -1 and still have a Hadamard
 
6010
          matrix.
 
6011
 
 
6012
 
 
6013
 -- Function File:  hankel (C, R)
 
6014
     Return the Hankel matrix constructed given the first column C, and
 
6015
     (optionally) the last row R.  If the last element of C is not the
 
6016
     same as the first element of R, the last element of C is used.  If
 
6017
     the second argument is omitted, it is assumed to be a vector of
 
6018
     zeros with the same size as C.
 
6019
 
 
6020
     A Hankel matrix formed from an m-vector C, and an n-vector R, has
 
6021
     the elements
 
6022
 
 
6023
          H(i,j) = c(i+j-1),  i+j-1 <= m;
 
6024
          H(i,j) = r(i+j-m),  otherwise
 
6025
 
 
6026
 
 
6027
     *See also:* vander, sylvester_matrix, hilb, invhilb, toeplitz.
 
6028
 
 
6029
 -- Function File:  hilb (N)
 
6030
     Return the Hilbert matrix of order N.  The i, j element of a
 
6031
     Hilbert matrix is defined as
 
6032
 
 
6033
          H (i, j) = 1 / (i + j - 1)
 
6034
 
 
6035
 
 
6036
     *See also:* hankel, vander, sylvester_matrix, invhilb, toeplitz.
 
6037
 
 
6038
 -- Function File:  invhilb (N)
 
6039
     Return the inverse of a Hilbert matrix of order N.  This can be
 
6040
     computed exactly using
 
6041
 
 
6042
                      (i+j)         /n+i-1\  /n+j-1\   /i+j-2\ 2
 
6043
           A(i,j) = -1      (i+j-1)(       )(       ) (       )
 
6044
                                    \ n-j /  \ n-i /   \ i-2 /
 
6045
 
 
6046
                  = p(i) p(j) / (i+j-1)
 
6047
     where
 
6048
                       k  /k+n-1\   /n\
 
6049
              p(k) = -1  (       ) (   )
 
6050
                          \ k-1 /   \k/
 
6051
 
 
6052
     The validity of this formula can easily be checked by expanding
 
6053
     the binomial coefficients in both formulas as factorials.  It can
 
6054
     be derived more directly via the theory of Cauchy matrices: see J.
 
6055
     W. Demmel, Applied Numerical Linear Algebra, page 92.
 
6056
 
 
6057
     Compare this with the numerical calculation of `inverse (hilb
 
6058
     (n))', which suffers from the ill-conditioning of the Hilbert
 
6059
     matrix, and the finite precision of your computer's floating point
 
6060
     arithmetic.
 
6061
 
 
6062
     *See also:* hankel, vander, sylvester_matrix, hilb, toeplitz.
 
6063
 
 
6064
 -- Function File:  magic (N)
 
6065
     Create an N-by-N magic square. Note that `magic (2)' is undefined
 
6066
     since there is no 2-by-2 magic square.
 
6067
 
 
6068
 
 
6069
 -- Function File:  pascal (N, T)
 
6070
     Return the Pascal matrix of order N if `T = 0'.  T defaults to 0.
 
6071
     Return lower triangular Cholesky factor of the Pascal matrix if `T
 
6072
     = 1'. This matrix is its own inverse, that is `pascal (N, 1) ^ 2
 
6073
     == eye (N)'.  If `T = 2', return a transposed and  permuted
 
6074
     version of `pascal (N, 1)', which is the cube-root of the identity
 
6075
     matrix. That is `pascal (N, 2) ^ 3 == eye (N)'.
 
6076
 
 
6077
 
 
6078
     *See also:* hankel, vander, sylvester_matrix, hilb, invhilb,
 
6079
     toeplitz           hadamard, wilkinson, compan, rosser.
 
6080
 
 
6081
 -- Function File:  rosser ()
 
6082
     Returns the Rosser matrix. This is a difficult test case used to
 
6083
     test eigenvalue algorithms.
 
6084
 
 
6085
 
 
6086
     *See also:* hankel, vander, sylvester_matrix, hilb, invhilb,
 
6087
     toeplitz           hadamard, wilkinson, compan, pascal.
 
6088
 
 
6089
 -- Function File:  sylvester_matrix (K)
 
6090
     Return the Sylvester matrix of order n = 2^k.
 
6091
 
 
6092
     *See also:* hankel, vander, hilb, invhilb, toeplitz.
 
6093
 
 
6094
 -- Function File:  toeplitz (C, R)
 
6095
     Return the Toeplitz matrix constructed given the first column C,
 
6096
     and (optionally) the first row R.  If the first element of C is
 
6097
     not the same as the first element of R, the first element of C is
 
6098
     used.  If the second argument is omitted, the first row is taken
 
6099
     to be the same as the first column.
 
6100
 
 
6101
     A square Toeplitz matrix has the form:
 
6102
 
 
6103
          c(0)  r(1)   r(2)  ...  r(n)
 
6104
          c(1)  c(0)   r(1)  ... r(n-1)
 
6105
          c(2)  c(1)   c(0)  ... r(n-2)
 
6106
           .     ,      ,   .      .
 
6107
           .     ,      ,     .    .
 
6108
           .     ,      ,       .  .
 
6109
          c(n) c(n-1) c(n-2) ...  c(0)
 
6110
 
 
6111
 
 
6112
     *See also:* hankel, vander, sylvester_matrix, hilb, invhilb.
 
6113
 
 
6114
 -- Function File:  vander (C)
 
6115
     Return the Vandermonde matrix whose next to last column is C.
 
6116
 
 
6117
     A Vandermonde matrix has the form:
 
6118
 
 
6119
          c(1)^(n-1) ... c(1)^2  c(1)  1
 
6120
          c(2)^(n-1) ... c(2)^2  c(2)  1
 
6121
              .     .      .      .    .
 
6122
              .       .    .      .    .
 
6123
              .         .  .      .    .
 
6124
          c(n)^(n-1) ... c(n)^2  c(n)  1
 
6125
 
 
6126
 
 
6127
     *See also:* hankel, sylvester_matrix, hilb, invhilb, toeplitz.
 
6128
 
 
6129
 -- Function File:  wilkinson (N)
 
6130
     Return the Wilkinson matrix of order N.
 
6131
 
 
6132
 
 
6133
     *See also:* hankel, vander, sylvester_matrix, hilb, invhilb,
 
6134
     toeplitz           hadamard, rosser, compan, pascal.
 
6135
 
 
6136
 
 
6137
File: octave.info,  Node: Arithmetic,  Next: Linear Algebra,  Prev: Matrix Manipulation,  Up: Top
 
6138
 
 
6139
17 Arithmetic
 
6140
*************
 
6141
 
 
6142
Unless otherwise noted, all of the functions described in this chapter
 
6143
will work for real and complex scalar or matrix arguments.
 
6144
 
 
6145
* Menu:
 
6146
 
 
6147
* Utility Functions::
 
6148
* Complex Arithmetic::
 
6149
* Trigonometry::
 
6150
* Sums and Products::
 
6151
* Special Functions::
 
6152
* Coordinate Transformations::
 
6153
* Mathematical Constants::
 
6154
 
 
6155
 
 
6156
File: octave.info,  Node: Utility Functions,  Next: Complex Arithmetic,  Up: Arithmetic
 
6157
 
 
6158
17.1 Utility Functions
 
6159
======================
 
6160
 
 
6161
The following functions are available for working with complex numbers.
 
6162
Each expects a single argument.  They are called "mapping functions"
 
6163
because when given a matrix argument, they apply the given function to
 
6164
each element of the matrix.
 
6165
 
 
6166
 -- Mapping Function:  ceil (X)
 
6167
     Return the smallest integer not less than X.  If X is complex,
 
6168
     return `ceil (real (X)) + ceil (imag (X)) * I'.
 
6169
 
 
6170
 -- Function File:  cplxpair (Z, TOL, DIM)
 
6171
     Sort the numbers Z into complex conjugate pairs ordered by
 
6172
     increasing real part.  With identical real parts, order by
 
6173
     increasing imaginary magnitude. Place the negative imaginary
 
6174
     complex number first within each pair. Place all the real numbers
 
6175
     after all the complex pairs (those with `abs (imag (Z) / Z) <
 
6176
     TOL)', where the default value of TOL is `100 * EPS'.
 
6177
 
 
6178
     By default the complex pairs are sorted along the first
 
6179
     non-singleton dimension of Z. If DIM is specified, then the complex
 
6180
     pairs are sorted along this dimension.
 
6181
 
 
6182
     Signal an error if some complex numbers could not be paired.
 
6183
     Requires all complex numbers to be exact conjugates within tol, or
 
6184
     signals an error. Note that there are no guarantees on the order
 
6185
     of the returned pairs with identical real parts but differing
 
6186
     imaginary parts.
 
6187
 
 
6188
          cplxpair (exp(2i*pi*[0:4]'/5)) == exp(2i*pi*[3; 2; 4; 1; 0]/5)
 
6189
 
 
6190
 -- Function File: D = del2 (M)
 
6191
 -- Function File: D = del2 (M, H)
 
6192
 -- Function File: D = del2 (M, DX, DY, ...)
 
6193
     Calculates the discrete Laplace operator. If M is a matrix this is
 
6194
     defined as
 
6195
 
 
6196
                1    / d^2            d^2         \
 
6197
          D  = --- * | ---  M(x,y) +  ---  M(x,y) |
 
6198
                4    \ dx^2           dy^2        /
 
6199
 
 
6200
     The above to continued to N-dimensional arrays calculating the
 
6201
     second derivative over the higher dimensions.
 
6202
 
 
6203
     The spacing between evaluation points may be defined by H, which
 
6204
     is a scalar defining the spacing in all dimensions. Or
 
6205
     alternative, the spacing in each dimension may be defined
 
6206
     separately by DX, DY, etc.  Scalar spacing values give equidistant
 
6207
     spacing, whereas vector spacing values can be used to specify
 
6208
     variable spacing. The length of the vectors must match the
 
6209
     respective dimension of M. The default spacing value is 1.
 
6210
 
 
6211
     You need at least 3 data points for each dimension. Boundary
 
6212
     points are calculated as the linear extrapolation of the interior
 
6213
     points.
 
6214
 
 
6215
 
 
6216
     *See also:* gradient, diff.
 
6217
 
 
6218
 -- Mapping Function:  exp (X)
 
6219
     Compute the exponential of X.  To compute the matrix exponential,
 
6220
     see *note Linear Algebra::.
 
6221
 
 
6222
 -- Function File: P = factor (Q)
 
6223
 -- Function File: [P, N] = factor (Q)
 
6224
     Return prime factorization of Q. That is `prod (P) == Q'. If `Q ==
 
6225
     1', returns 1.
 
6226
 
 
6227
     With two output arguments, returns the unique primes P and their
 
6228
     multiplicities. That is `prod (P .^ N) == Q'.
 
6229
 
 
6230
 
 
6231
 -- Function File:  factorial (N)
 
6232
     Return the factorial of N. If N is scalar, this is equivalent to
 
6233
     `prod (1:N)'.  If N is an array, the factorial of the elements of
 
6234
     the array are returned.
 
6235
 
 
6236
 -- Mapping Function:  fix (X)
 
6237
     Truncate X toward zero.  If X is complex, return `fix (real (X)) +
 
6238
     fix (imag (X)) * I'.
 
6239
 
 
6240
 -- Mapping Function:  floor (X)
 
6241
     Return the largest integer not greater than X.  If X is complex,
 
6242
     return `floor (real (X)) + floor (imag (X)) * I'.
 
6243
 
 
6244
 -- Mapping Function:  fmod (X, Y)
 
6245
     Compute the floating point remainder of dividing X by Y using the
 
6246
     C library function `fmod'.  The result has the same sign as X.  If
 
6247
     Y is zero, the result implementation-defined.
 
6248
 
 
6249
 -- Loadable Function: G = gcd (A1, ...)
 
6250
 -- Loadable Function: [G, V1, ...] = gcd (A1, ...)
 
6251
     If a single argument is given then compute the greatest common
 
6252
     divisor of the elements of this argument. Otherwise if more than
 
6253
     one argument is given all arguments must be the same size or
 
6254
     scalar. In this case the greatest common divisor is calculated for
 
6255
     element individually. All elements must be integers. For example,
 
6256
 
 
6257
          gcd ([15, 20])
 
6258
              =>  5
 
6259
 
 
6260
     and
 
6261
 
 
6262
          gcd ([15, 9], [20 18])
 
6263
              =>  5  9
 
6264
 
 
6265
     Optional return arguments V1, etc, contain integer vectors such
 
6266
     that,
 
6267
 
 
6268
          G = V1 .* A1 + V2 .* A2 + ...
 
6269
 
 
6270
     For backward compatibility with previous versions of this
 
6271
     function, when all arguments are scalar, a single return argument
 
6272
     V1 containing all of the values of V1, ... is acceptable.
 
6273
 
 
6274
     *See also:* lcm, min, max, ceil, floor.
 
6275
 
 
6276
 -- Function File: X =  gradient (M)
 
6277
 -- Function File: [X, Y, ...] =  gradient (M)
 
6278
 -- Function File: [...] =  gradient (M, S)
 
6279
 -- Function File: [...] =  gradient (M, DX, DY, ...)
 
6280
     Calculates the gradient. `X = gradient (M)' calculates the one
 
6281
     dimensional gradient if M is a vector. If M is a matrix the
 
6282
     gradient is calculated for each row.
 
6283
 
 
6284
     `[X, Y] = gradient (M)' calculates the one dimensional gradient
 
6285
     for each direction if M if M is a matrix. Additional return
 
6286
     arguments can be use for multi-dimensional matrices.
 
6287
 
 
6288
     Spacing values between two points can be provided by the DX, DY or
 
6289
     H parameters. If H is supplied it is assumed to be the spacing in
 
6290
     all directions. Otherwise, separate values of the spacing can be
 
6291
     supplied by the DX, etc variables.  A scalar value specifies an
 
6292
     equidistant spacing, while a vector value can be used to specify a
 
6293
     variable spacing. The length must match their respective dimension
 
6294
     of M.
 
6295
 
 
6296
     At boundary points a linear extrapolation is applied. Interior
 
6297
     points are calculated with the first approximation of the
 
6298
     numerical gradient
 
6299
 
 
6300
          y'(i) = 1/(x(i+1)-x(i-1)) *(y(i-1)-y(i+1)).
 
6301
 
 
6302
 
 
6303
 -- Mapping Function:  lcm (X, ...)
 
6304
     Compute the least common multiple of the elements of X, or the
 
6305
     list of all the arguments.  For example,
 
6306
 
 
6307
          lcm (a1, ..., ak)
 
6308
 
 
6309
     is the same as
 
6310
 
 
6311
          lcm ([a1, ..., ak]).
 
6312
 
 
6313
     All elements must be the same size or scalar.
 
6314
 
 
6315
     *See also:* gcd, min, max, ceil, floor.
 
6316
 
 
6317
 -- Mapping Function:  log (X)
 
6318
     Compute the natural logarithm for each element of X.  To compute
 
6319
     the matrix logarithm, see *note Linear Algebra::.
 
6320
 
 
6321
     *See also:* log2, log10, logspace, exp.
 
6322
 
 
6323
 -- Mapping Function:  log10 (X)
 
6324
     Compute the base-10 logarithm for each element of X.
 
6325
 
 
6326
     *See also:* log, log2, logspace, exp.
 
6327
 
 
6328
 -- Mapping Function:  log2 (X)
 
6329
 -- Mapping Function: [F, E] = log2 (X)
 
6330
     Compute the base-2 logarithm of X.  With two outputs, returns F
 
6331
     and E such that  1/2 <= abs(f) < 1 and x = f * 2^e.
 
6332
 
 
6333
     *See also:* log, log10, logspace, exp.
 
6334
 
 
6335
 -- Mapping Function:  max (X, Y, DIM)
 
6336
 -- Mapping Function: [W, IW] = max (X)
 
6337
     For a vector argument, return the maximum value.  For a matrix
 
6338
     argument, return the maximum value from each column, as a row
 
6339
     vector, or over the dimension DIM if defined. For two matrices (or
 
6340
     a matrix and scalar), return the pair-wise maximum.  Thus,
 
6341
 
 
6342
          max (max (X))
 
6343
 
 
6344
     returns the largest element of X, and
 
6345
 
 
6346
          max (2:5, pi)
 
6347
              =>  3.1416  3.1416  4.0000  5.0000
 
6348
     compares each element of the range `2:5' with `pi', and returns a
 
6349
     row vector of the maximum values.
 
6350
 
 
6351
     For complex arguments, the magnitude of the elements are used for
 
6352
     comparison.
 
6353
 
 
6354
     If called with one input and two output arguments, `max' also
 
6355
     returns the first index of the maximum value(s). Thus,
 
6356
 
 
6357
          [x, ix] = max ([1, 3, 5, 2, 5])
 
6358
              =>  x = 5
 
6359
                  ix = 3
 
6360
 
 
6361
 -- Mapping Function:  min (X, Y, DIM)
 
6362
 -- Mapping Function: [W, IW] = min (X)
 
6363
     For a vector argument, return the minimum value.  For a matrix
 
6364
     argument, return the minimum value from each column, as a row
 
6365
     vector, or over the dimension DIM if defined. For two matrices (or
 
6366
     a matrix and scalar), return the pair-wise minimum.  Thus,
 
6367
 
 
6368
          min (min (X))
 
6369
 
 
6370
     returns the smallest element of X, and
 
6371
 
 
6372
          min (2:5, pi)
 
6373
              =>  2.0000  3.0000  3.1416  3.1416
 
6374
     compares each element of the range `2:5' with `pi', and returns a
 
6375
     row vector of the minimum values.
 
6376
 
 
6377
     For complex arguments, the magnitude of the elements are used for
 
6378
     comparison.
 
6379
 
 
6380
     If called with one input and two output arguments, `min' also
 
6381
     returns the first index of the minimum value(s). Thus,
 
6382
 
 
6383
          [x, ix] = min ([1, 3, 0, 2, 5])
 
6384
              =>  x = 0
 
6385
                  ix = 3
 
6386
 
 
6387
 -- Mapping Function:  mod (X, Y)
 
6388
     Compute modulo function, using
 
6389
 
 
6390
          x - y .* floor (x ./ y)
 
6391
 
 
6392
     Note that this handles negative numbers correctly: `mod (-1, 3)'
 
6393
     is 2, not -1 as `rem (-1, 3)' returns.  Also, `mod (X, 0)' returns
 
6394
     X.
 
6395
 
 
6396
     An error message is printed if the dimensions of the arguments do
 
6397
     not agree, or if either of the arguments is complex.
 
6398
 
 
6399
     *See also:* rem, round.
 
6400
 
 
6401
 -- Function File:  nextpow2 (X)
 
6402
     If X is a scalar, returns the first integer N such that  2^n >=
 
6403
     abs (x).
 
6404
 
 
6405
     If X is a vector, return `nextpow2 (length (X))'.
 
6406
 
 
6407
     *See also:* pow2.
 
6408
 
 
6409
 -- Function File:  nthroot (X, N)
 
6410
     Compute the nth root of X, returning real results for real
 
6411
     components of X. For example
 
6412
 
 
6413
          nthroot (-1, 3)
 
6414
          => -1
 
6415
          (-1) ^ (1 / 3)
 
6416
          => 0.50000 - 0.86603i
 
6417
 
 
6418
 
 
6419
 -- Mapping Function:  pow2 (X)
 
6420
 -- Mapping Function:  pow2 (F, E)
 
6421
     With one argument, computes  2 .^ x for each element of X.  With
 
6422
     two arguments, returns  f .* (2 .^ e).
 
6423
 
 
6424
     *See also:* nextpow2.
 
6425
 
 
6426
 -- Function File:  primes (N)
 
6427
     Return all primes up to N.
 
6428
 
 
6429
     Note that if you need a specific number of primes, you can use the
 
6430
     fact the distance from one prime to the next is on average
 
6431
     proportional to the logarithm of the prime.  Integrating, you find
 
6432
     that there are about k primes less than k \log ( 5 k ).
 
6433
 
 
6434
     The algorithm used is called the Sieve of Erastothenes.
 
6435
 
 
6436
 -- Mapping Function:  rem (X, Y)
 
6437
     Return the remainder of `X / Y', computed using the expression
 
6438
 
 
6439
          x - y .* fix (x ./ y)
 
6440
 
 
6441
     An error message is printed if the dimensions of the arguments do
 
6442
     not agree, or if either of the arguments is complex.
 
6443
 
 
6444
     *See also:* mod, round.
 
6445
 
 
6446
 -- Mapping Function:  round (X)
 
6447
     Return the integer nearest to X.  If X is complex, return `round
 
6448
     (real (X)) + round (imag (X)) * I'.
 
6449
 
 
6450
     *See also:* rem.
 
6451
 
 
6452
 -- Mapping Function:  sign (X)
 
6453
     Compute the "signum" function, which is defined as
 
6454
 
 
6455
                     -1, x < 0;
 
6456
          sign (x) =  0, x = 0;
 
6457
                      1, x > 0.
 
6458
 
 
6459
     For complex arguments, `sign' returns `x ./ abs (X)'.
 
6460
 
 
6461
 -- Mapping Function:  sqrt (X)
 
6462
     Compute the square root of X.  If X is negative, a complex result
 
6463
     is returned.  To compute the matrix square root, see *note Linear
 
6464
     Algebra::.
 
6465
 
 
6466
 
 
6467
File: octave.info,  Node: Complex Arithmetic,  Next: Trigonometry,  Prev: Utility Functions,  Up: Arithmetic
 
6468
 
 
6469
17.2 Complex Arithmetic
 
6470
=======================
 
6471
 
 
6472
The following functions are available for working with complex numbers.
 
6473
Each expects a single argument.  Given a matrix they work on an element
 
6474
by element basis.  In the descriptions of the following functions, Z is
 
6475
the complex number X + IY, where I is defined as `sqrt (-1)'.
 
6476
 
 
6477
 -- Mapping Function:  abs (Z)
 
6478
     Compute the magnitude of Z, defined as |Z| = `sqrt (x^2 + y^2)'.
 
6479
 
 
6480
     For example,
 
6481
 
 
6482
          abs (3 + 4i)
 
6483
               => 5
 
6484
 
 
6485
 -- Mapping Function:  arg (Z)
 
6486
 -- Mapping Function:  angle (Z)
 
6487
     Compute the argument of Z, defined as THETA = `atan (Y/X)'.  in
 
6488
     radians.
 
6489
 
 
6490
     For example,
 
6491
 
 
6492
          arg (3 + 4i)
 
6493
               => 0.92730
 
6494
 
 
6495
 -- Mapping Function:  conj (Z)
 
6496
     Return the complex conjugate of Z, defined as `conj (Z)' = X - IY.
 
6497
 
 
6498
     *See also:* real, imag.
 
6499
 
 
6500
 -- Mapping Function:  imag (Z)
 
6501
     Return the imaginary part of Z as a real number.
 
6502
 
 
6503
     *See also:* real, conj.
 
6504
 
 
6505
 -- Mapping Function:  real (Z)
 
6506
     Return the real part of Z.
 
6507
 
 
6508
     *See also:* imag, conj.
 
6509
 
 
6510
 
 
6511
File: octave.info,  Node: Trigonometry,  Next: Sums and Products,  Prev: Complex Arithmetic,  Up: Arithmetic
 
6512
 
 
6513
17.3 Trigonometry
 
6514
=================
 
6515
 
 
6516
Octave provides the following trigonometric functions.  Angles are
 
6517
specified in radians.  To convert from degrees to radians multiply by
 
6518
`pi/180'  (e.g. `sin (30 * pi/180)' returns the sine of 30 degrees).
 
6519
 
 
6520
 -- Mapping Function:  sin (X)
 
6521
     Compute the sine of each element of X.
 
6522
 
 
6523
 -- Mapping Function:  cos (X)
 
6524
     Compute the cosine of each element of X.
 
6525
 
 
6526
 -- Mapping Function:  tan (Z)
 
6527
     Compute tangent of each element of X.
 
6528
 
 
6529
 -- Mapping Function:  sec (X)
 
6530
     Compute the secant of each element of X.
 
6531
 
 
6532
 -- Mapping Function:  csc (X)
 
6533
     Compute the cosecant of each element of X.
 
6534
 
 
6535
 -- Mapping Function:  cot (X)
 
6536
     Compute the cotangent of each element of X.
 
6537
 
 
6538
 -- Mapping Function:  asin (X)
 
6539
     Compute the inverse sine of each element of X.
 
6540
 
 
6541
 -- Mapping Function:  acos (X)
 
6542
     Compute the inverse cosine of each element of X.
 
6543
 
 
6544
 -- Mapping Function:  atan (X)
 
6545
     Compute the inverse tangent of each element of X.
 
6546
 
 
6547
 -- Mapping Function:  asec (X)
 
6548
     Compute the inverse secant of each element of X.
 
6549
 
 
6550
 -- Mapping Function:  acsc (X)
 
6551
     Compute the inverse cosecant of each element of X.
 
6552
 
 
6553
 -- Mapping Function:  acot (X)
 
6554
     Compute the inverse cotangent of each element of X.
 
6555
 
 
6556
 -- Mapping Function:  sinh (X)
 
6557
     Compute the hyperbolic sine of each element of X.
 
6558
 
 
6559
 -- Mapping Function:  cosh (X)
 
6560
     Compute the hyperbolic cosine of each element of X.
 
6561
 
 
6562
 -- Mapping Function:  tanh (X)
 
6563
     Compute hyperbolic tangent of each element of X.
 
6564
 
 
6565
 -- Mapping Function:  sech (X)
 
6566
     Compute the hyperbolic secant of each element of X.
 
6567
 
 
6568
 -- Mapping Function:  csch (X)
 
6569
     Compute the hyperbolic cosecant of each element of X.
 
6570
 
 
6571
 -- Mapping Function:  coth (X)
 
6572
     Compute the hyperbolic cotangent of each element of X.
 
6573
 
 
6574
 -- Mapping Function:  asinh (X)
 
6575
     Compute the inverse hyperbolic sine of each element of X.
 
6576
 
 
6577
 -- Mapping Function:  acosh (X)
 
6578
     Compute the inverse hyperbolic cosine of each element of X.
 
6579
 
 
6580
 -- Mapping Function:  atanh (X)
 
6581
     Compute the inverse hyperbolic tangent of each element of X.
 
6582
 
 
6583
 -- Mapping Function:  asech (X)
 
6584
     Compute the inverse hyperbolic secant of each element of X.
 
6585
 
 
6586
 -- Mapping Function:  acsch (X)
 
6587
     Compute the inverse hyperbolic cosecant of each element of X.
 
6588
 
 
6589
 -- Mapping Function:  acoth (X)
 
6590
     Compute the inverse hyperbolic cotangent of each element of X.
 
6591
 
 
6592
   Each of these functions expects a single argument.  For matrix
 
6593
arguments, they work on an element by element basis.  For example,
 
6594
 
 
6595
     sin ([1, 2; 3, 4])
 
6596
          =>  0.84147   0.90930
 
6597
              0.14112  -0.75680
 
6598
 
 
6599
 -- Mapping Function:  atan2 (Y, X)
 
6600
     Compute atan (Y / X) for corresponding elements of Y and X.  The
 
6601
     result is in range -pi to pi.
 
6602
 
 
6603
   In addition to the trigonometric functions that work with radians,
 
6604
Octave also provides the following functions which work with degrees.
 
6605
 
 
6606
 -- Function File:  sind (X)
 
6607
     Compute the sine of each element of X.  Returns zero in elements
 
6608
     for which `X/180' is an integer.
 
6609
 
 
6610
     *See also:* sin, cosd, tand, acosd, asind, atand.
 
6611
 
 
6612
 -- Function File:  cosd (X)
 
6613
     Compute the cosine of an angle in degrees.  Returns zero in
 
6614
     elements for which `(X-90)/180' is an integer.
 
6615
 
 
6616
     *See also:* cos, sind, tand, acosd, asind, atand.
 
6617
 
 
6618
 -- Function File:  tand (X)
 
6619
     Compute the tangent of an angle in degrees.  Returns zero for
 
6620
     elements of for which `X/180' is an integer and `Inf' for elements
 
6621
     where `(X-90)/180' is an integer.
 
6622
 
 
6623
     *See also:* tan, cosd, sind, acosd, asind, atand.
 
6624
 
 
6625
 -- Function File:  secd (X)
 
6626
     Compute the secant of an angle in degrees.
 
6627
 
 
6628
     *See also:* sec, cscd, sind, cosd.
 
6629
 
 
6630
 -- Function File:  cscd (X)
 
6631
     Compute the cosecant of an angle in degrees.
 
6632
 
 
6633
     *See also:* csc, secd, sind, cosd.
 
6634
 
 
6635
 -- Function File:  cotd (X)
 
6636
     Compute the cotangent of an angle in degrees.
 
6637
 
 
6638
     *See also:* cot, tand.
 
6639
 
 
6640
 -- Function File:  asind (X)
 
6641
     Compute the inverse sine of an angle in degrees.
 
6642
 
 
6643
     *See also:* asin, sind, acosd.
 
6644
 
 
6645
 -- Function File:  acosd (X)
 
6646
     Compute the inverse cosine of an angle in degrees.
 
6647
 
 
6648
     *See also:* acos, cosd, asecd.
 
6649
 
 
6650
 -- Function File:  atand (X)
 
6651
     Compute the inverse tangent of an angle in degrees.
 
6652
 
 
6653
     *See also:* acot, tand.
 
6654
 
 
6655
 -- Function File:  asecd (X)
 
6656
     Compute inverse secant in degrees.
 
6657
 
 
6658
     *See also:* asec, secd, acscd.
 
6659
 
 
6660
 -- Function File:  acscd (X)
 
6661
     Compute the inverse cosecant of an angle in degrees.
 
6662
 
 
6663
     *See also:* acsc, cscd, asecd.
 
6664
 
 
6665
 -- Function File:  acotd (X)
 
6666
     Compute the inverse cotangent of an angle in degrees.
 
6667
 
 
6668
     *See also:* atan, tand.
 
6669
 
 
6670
 
 
6671
File: octave.info,  Node: Sums and Products,  Next: Special Functions,  Prev: Trigonometry,  Up: Arithmetic
 
6672
 
 
6673
17.4 Sums and Products
 
6674
======================
 
6675
 
 
6676
 -- Built-in Function:  sum (X, DIM)
 
6677
 -- Built-in Function:  sum (..., 'native')
 
6678
     Sum of elements along dimension DIM.  If DIM is omitted, it
 
6679
     defaults to 1 (column-wise sum).
 
6680
 
 
6681
     As a special case, if X is a vector and DIM is omitted, return the
 
6682
     sum of the elements.
 
6683
 
 
6684
     If the optional argument 'native' is given, then the sum is
 
6685
     performed in the same type as the original argument, rather than
 
6686
     in the default double type. For example
 
6687
 
 
6688
          sum ([true, true])
 
6689
            => 2
 
6690
          sum ([true, true], 'native')
 
6691
            => true
 
6692
 
 
6693
 -- Built-in Function:  prod (X, DIM)
 
6694
     Product of elements along dimension DIM.  If DIM is omitted, it
 
6695
     defaults to 1 (column-wise products).
 
6696
 
 
6697
     As a special case, if X is a vector and DIM is omitted, return the
 
6698
     product of the elements.
 
6699
 
 
6700
 -- Built-in Function:  cumsum (X, DIM)
 
6701
     Cumulative sum of elements along dimension DIM.  If DIM is
 
6702
     omitted, it defaults to 1 (column-wise cumulative sums).
 
6703
 
 
6704
     As a special case, if X is a vector and DIM is omitted, return the
 
6705
     cumulative sum of the elements as a vector with the same
 
6706
     orientation as X.
 
6707
 
 
6708
 -- Built-in Function:  cumprod (X, DIM)
 
6709
     Cumulative product of elements along dimension DIM.  If DIM is
 
6710
     omitted, it defaults to 1 (column-wise cumulative products).
 
6711
 
 
6712
     As a special case, if X is a vector and DIM is omitted, return the
 
6713
     cumulative product of the elements as a vector with the same
 
6714
     orientation as X.
 
6715
 
 
6716
 -- Built-in Function:  sumsq (X, DIM)
 
6717
     Sum of squares of elements along dimension DIM.  If DIM is
 
6718
     omitted, it defaults to 1 (column-wise sum of squares).
 
6719
 
 
6720
     As a special case, if X is a vector and DIM is omitted, return the
 
6721
     sum of squares of the elements.
 
6722
 
 
6723
     This function is conceptually equivalent to computing
 
6724
          sum (x .* conj (x), dim)
 
6725
     but it uses less memory and avoids calling conj if X is real.
 
6726
 
 
6727
 -- Function File:  accumarray (SUBS, VALS, SZ, FUN, FILLVAL, ISSPARSE)
 
6728
 -- Function File:  accumarray (CSUBS, VALS, ...)
 
6729
     Create an array by accumulating the elements of a vector into the
 
6730
     positions defined by their subscripts. The subscripts are defined
 
6731
     by the rows of the matrix SUBS and the values by VALS. Each row of
 
6732
     SUBS corresponds to one of the values in VALS.
 
6733
 
 
6734
     The size of the matrix will be determined by the subscripts
 
6735
     themselves.  However, if SZ is defined it determines the matrix
 
6736
     size. The length of SZ must correspond to the number of columns in
 
6737
     SUBS.
 
6738
 
 
6739
     The default action of `accumarray' is to sum the elements with the
 
6740
     same subscripts. This behavior can be modified by defining the FUN
 
6741
     function. This should be a function or function handle that
 
6742
     accepts a column vector and returns a scalar. The result of the
 
6743
     function should not depend on the order of the subscripts.
 
6744
 
 
6745
     The elements of the returned array that have no subscripts
 
6746
     assoicated with them are set to zero. Defining FILLVAL to some
 
6747
     other value allows these values to be defined.
 
6748
 
 
6749
     By default `accumarray' returns a full matrix. If ISSPARSE is
 
6750
     logically true, then a sparse matrix is returned instead.
 
6751
 
 
6752
     An example of the use of `accumarray' is:
 
6753
 
 
6754
          accumarray ([1,1,1;2,1,2;2,3,2;2,1,2;2,3,2], 101:105)
 
6755
          => ans(:,:,1) = [101, 0, 0; 0, 0, 0]
 
6756
             ans(:,:,2) = [0, 0, 0; 206, 0, 208]
 
6757
 
 
6758
 
 
6759
File: octave.info,  Node: Special Functions,  Next: Coordinate Transformations,  Prev: Sums and Products,  Up: Arithmetic
 
6760
 
 
6761
17.5 Special Functions
 
6762
======================
 
6763
 
 
6764
 -- Loadable Function: [J, IERR] = besselj (ALPHA, X, OPT)
 
6765
 -- Loadable Function: [Y, IERR] = bessely (ALPHA, X, OPT)
 
6766
 -- Loadable Function: [I, IERR] = besseli (ALPHA, X, OPT)
 
6767
 -- Loadable Function: [K, IERR] = besselk (ALPHA, X, OPT)
 
6768
 -- Loadable Function: [H, IERR] = besselh (ALPHA, K, X, OPT)
 
6769
     Compute Bessel or Hankel functions of various kinds:
 
6770
 
 
6771
    `besselj'
 
6772
          Bessel functions of the first kind.
 
6773
 
 
6774
    `bessely'
 
6775
          Bessel functions of the second kind.
 
6776
 
 
6777
    `besseli'
 
6778
          Modified Bessel functions of the first kind.
 
6779
 
 
6780
    `besselk'
 
6781
          Modified Bessel functions of the second kind.
 
6782
 
 
6783
    `besselh'
 
6784
          Compute Hankel functions of the first (K = 1) or second (K  =
 
6785
          2) kind.
 
6786
 
 
6787
     If the argument OPT is supplied, the result is scaled by the `exp
 
6788
     (-I*X)' for K = 1 or `exp (I*X)' for  K = 2.
 
6789
 
 
6790
     If ALPHA is a scalar, the result is the same size as X.  If X is a
 
6791
     scalar, the result is the same size as ALPHA.  If ALPHA is a row
 
6792
     vector and X is a column vector, the result is a matrix with
 
6793
     `length (X)' rows and `length (ALPHA)' columns.  Otherwise, ALPHA
 
6794
     and X must conform and the result will be the same size.
 
6795
 
 
6796
     The value of ALPHA must be real.  The value of X may be complex.
 
6797
 
 
6798
     If requested, IERR contains the following status information and
 
6799
     is the same size as the result.
 
6800
 
 
6801
       0. Normal return.
 
6802
 
 
6803
       1. Input error, return `NaN'.
 
6804
 
 
6805
       2. Overflow, return `Inf'.
 
6806
 
 
6807
       3. Loss of significance by argument reduction results in less
 
6808
          than half of machine accuracy.
 
6809
 
 
6810
       4. Complete loss of significance by argument reduction, return
 
6811
          `NaN'.
 
6812
 
 
6813
       5. Error--no computation, algorithm termination condition not
 
6814
          met, return `NaN'.
 
6815
 
 
6816
 -- Loadable Function: [A, IERR] = airy (K, Z, OPT)
 
6817
     Compute Airy functions of the first and second kind, and their
 
6818
     derivatives.
 
6819
 
 
6820
           K   Function   Scale factor (if 'opt' is supplied)
 
6821
          ---  --------   ---------------------------------------
 
6822
           0   Ai (Z)     exp ((2/3) * Z * sqrt (Z))
 
6823
           1   dAi(Z)/dZ  exp ((2/3) * Z * sqrt (Z))
 
6824
           2   Bi (Z)     exp (-abs (real ((2/3) * Z *sqrt (Z))))
 
6825
           3   dBi(Z)/dZ  exp (-abs (real ((2/3) * Z *sqrt (Z))))
 
6826
 
 
6827
     The function call `airy (Z)' is equivalent to `airy (0, Z)'.
 
6828
 
 
6829
     The result is the same size as Z.
 
6830
 
 
6831
     If requested, IERR contains the following status information and
 
6832
     is the same size as the result.
 
6833
 
 
6834
       0. Normal return.
 
6835
 
 
6836
       1. Input error, return `NaN'.
 
6837
 
 
6838
       2. Overflow, return `Inf'.
 
6839
 
 
6840
       3. Loss of significance by argument reduction results in less
 
6841
          than half  of machine accuracy.
 
6842
 
 
6843
       4. Complete loss of significance by argument reduction, return
 
6844
          `NaN'.
 
6845
 
 
6846
       5. Error--no computation, algorithm termination condition not
 
6847
          met, return `NaN'.
 
6848
 
 
6849
 -- Mapping Function:  beta (A, B)
 
6850
     Return the Beta function,
 
6851
 
 
6852
          beta (a, b) = gamma (a) * gamma (b) / gamma (a + b).
 
6853
 
 
6854
 -- Mapping Function:  betainc (X, A, B)
 
6855
     Return the incomplete Beta function,
 
6856
 
 
6857
                                                x
 
6858
                                               /
 
6859
          betainc (x, a, b) = beta (a, b)^(-1) | t^(a-1) (1-t)^(b-1) dt.
 
6860
                                               /
 
6861
                                            t=0
 
6862
 
 
6863
     If x has more than one component, both A and B must be scalars.
 
6864
     If X is a scalar, A and B must be of compatible dimensions.
 
6865
 
 
6866
 -- Mapping Function:  betaln (A, B)
 
6867
     Return the log of the Beta function,
 
6868
 
 
6869
          betaln (a, b) = gammaln (a) + gammaln (b) - gammaln (a + b)
 
6870
 
 
6871
 
 
6872
     *See also:* beta, betai, gammaln.
 
6873
 
 
6874
 -- Mapping Function:  bincoeff (N, K)
 
6875
     Return the binomial coefficient of N and K, defined as
 
6876
 
 
6877
           /   \
 
6878
           | n |    n (n-1) (n-2) ... (n-k+1)
 
6879
           |   |  = -------------------------
 
6880
           | k |               k!
 
6881
           \   /
 
6882
 
 
6883
     For example,
 
6884
 
 
6885
          bincoeff (5, 2)
 
6886
          => 10
 
6887
 
 
6888
 -- Mapping Function:  erf (Z)
 
6889
     Computes the error function,
 
6890
 
 
6891
                                   z
 
6892
                                  /
 
6893
          erf (z) = (2/sqrt (pi)) | e^(-t^2) dt
 
6894
                                  /
 
6895
                               t=0
 
6896
 
 
6897
 
 
6898
     *See also:* erfc, erfinv.
 
6899
 
 
6900
 -- Mapping Function:  erfc (Z)
 
6901
     Computes the complementary error function, `1 - erf (Z)'.
 
6902
 
 
6903
     *See also:* erf, erfinv.
 
6904
 
 
6905
 -- Mapping Function:  erfinv (Z)
 
6906
     Computes the inverse of the error function.
 
6907
 
 
6908
     *See also:* erf, erfc.
 
6909
 
 
6910
 -- Mapping Function:  gamma (Z)
 
6911
     Computes the Gamma function,
 
6912
 
 
6913
                      infinity
 
6914
                      /
 
6915
          gamma (z) = | t^(z-1) exp (-t) dt.
 
6916
                      /
 
6917
                   t=0
 
6918
 
 
6919
 
 
6920
     *See also:* gammai, lgamma.
 
6921
 
 
6922
 -- Mapping Function:  gammainc (X, A)
 
6923
     Compute the normalized incomplete gamma function,
 
6924
 
 
6925
                                          x
 
6926
                                1        /
 
6927
          gammainc (x, a) = ---------    | exp (-t) t^(a-1) dt
 
6928
                            gamma (a)    /
 
6929
                                      t=0
 
6930
 
 
6931
     with the limiting value of 1 as X approaches infinity.  The
 
6932
     standard notation is P(a,x), e.g. Abramowitz and Stegun (6.5.1).
 
6933
 
 
6934
     If A is scalar, then `gammainc (X, A)' is returned for each
 
6935
     element of X and vice versa.
 
6936
 
 
6937
     If neither X nor A is scalar, the sizes of X and A must agree, and
 
6938
     GAMMAINC is applied element-by-element.
 
6939
 
 
6940
     *See also:* gamma, lgamma.
 
6941
 
 
6942
 -- Function File: L = legendre (N, X)
 
6943
     Legendre Function of degree n and order m where all values for m =
 
6944
     0..N are returned.  N must be a scalar in the range [0..255].  The
 
6945
     return value has one dimension more than X.
 
6946
 
 
6947
          The Legendre Function of degree n and order m
 
6948
 
 
6949
           m        m       2  m/2   d^m
 
6950
          P(x) = (-1) * (1-x  )    * ----  P (x)
 
6951
           n                         dx^m   n
 
6952
 
 
6953
          with:
 
6954
          Legendre polynomial of degree n
 
6955
 
 
6956
                    1     d^n   2    n
 
6957
          P (x) = ------ [----(x - 1)  ]
 
6958
           n      2^n n!  dx^n
 
6959
 
 
6960
          legendre(3,[-1.0 -0.9 -0.8]) returns the matrix
 
6961
 
 
6962
           x  |   -1.0   |   -0.9   |  -0.8
 
6963
          ------------------------------------
 
6964
          m=0 | -1.00000 | -0.47250 | -0.08000
 
6965
          m=1 |  0.00000 | -1.99420 | -1.98000
 
6966
          m=2 |  0.00000 | -2.56500 | -4.32000
 
6967
          m=3 |  0.00000 | -1.24229 | -3.24000
 
6968
 
 
6969
 -- Mapping Function:  lgamma (X)
 
6970
 -- Mapping Function:  gammaln (X)
 
6971
     Return the natural logarithm of the absolute value of the gamma
 
6972
     function of X.
 
6973
 
 
6974
     *See also:* gamma, gammai.
 
6975
 
 
6976
 -- Function File:  cross (X, Y, DIM)
 
6977
     Computes the vector cross product of the two 3-dimensional vectors
 
6978
     X and Y.
 
6979
 
 
6980
          cross ([1,1,0], [0,1,1])
 
6981
          => [ 1; -1; 1 ]
 
6982
 
 
6983
     If X and Y are matrices, the cross product is applied along the
 
6984
     first dimension with 3 elements. The optional argument DIM is used
 
6985
     to force the cross product to be calculated along the dimension
 
6986
     defined by DIM.
 
6987
 
 
6988
 -- Function File:  commutation_matrix (M, N)
 
6989
     Return the commutation matrix  K(m,n)  which is the unique M*N by
 
6990
     M*N  matrix such that K(m,n) * vec(A) = vec(A')  for all m by n
 
6991
     matrices A.
 
6992
 
 
6993
     If only one argument M is given, K(m,m)  is returned.
 
6994
 
 
6995
     See Magnus and Neudecker (1988), Matrix differential calculus with
 
6996
     applications in statistics and econometrics.
 
6997
 
 
6998
 -- Function File:  duplication_matrix (N)
 
6999
     Return the duplication matrix Dn  which is the unique n^2 by
 
7000
     n*(n+1)/2  matrix such that Dn vech (A) = vec (A)  for all
 
7001
     symmetric n by n  matrices A.
 
7002
 
 
7003
     See Magnus and Neudecker (1988), Matrix differential calculus with
 
7004
     applications in statistics and econometrics.
 
7005
 
 
7006
 
 
7007
File: octave.info,  Node: Coordinate Transformations,  Next: Mathematical Constants,  Prev: Special Functions,  Up: Arithmetic
 
7008
 
 
7009
17.6 Coordinate Transformations
 
7010
===============================
 
7011
 
 
7012
 -- Function File: [THETA, R] = cart2pol (X, Y)
 
7013
 -- Function File: [THETA, R, Z] = cart2pol (X, Y, Z)
 
7014
     Transform cartesian to polar or cylindrical coordinates.  X, Y
 
7015
     (and Z) must be of same shape.  THETA describes the angle relative
 
7016
     to the x - axis.  R is the distance to the z - axis (0, 0, z).
 
7017
 
 
7018
     *See also:* pol2cart, cart2sph, sph2cart.
 
7019
 
 
7020
 -- Function File: [X, Y] = pol2cart (THETA, R)
 
7021
 -- Function File: [X, Y, Z] = pol2cart (THETA, R, Z)
 
7022
     Transform polar or cylindrical to cartesian coordinates.  THETA, R
 
7023
     (and Z) must be of same shape.  THETA describes the angle relative
 
7024
     to the x - axis.  R is the distance to the z - axis (0, 0, z).
 
7025
 
 
7026
     *See also:* cart2pol, cart2sph, sph2cart.
 
7027
 
 
7028
 -- Function File: [THETA, PHI, R] = cart2sph (X, Y, Z)
 
7029
     Transform cartesian to spherical coordinates.  X, Y and Z must be
 
7030
     of same shape.  THETA describes the angle relative to the x - axis.
 
7031
     PHI is the angle relative to the xy - plane.  R is the distance to
 
7032
     the origin (0, 0, 0).
 
7033
 
 
7034
     *See also:* pol2cart, cart2pol, sph2cart.
 
7035
 
 
7036
 -- Function File: [X, Y, Z] = sph2cart (THETA, PHI, R)
 
7037
     Transform spherical to cartesian coordinates.  X, Y and Z must be
 
7038
     of same shape.  THETA describes the angle relative to the x-axis.
 
7039
     PHI is the angle relative to the xy-plane.  R is the distance to
 
7040
     the origin (0, 0, 0).
 
7041
 
 
7042
     *See also:* pol2cart, cart2pol, cart2sph.
 
7043
 
 
7044
 
 
7045
File: octave.info,  Node: Mathematical Constants,  Prev: Coordinate Transformations,  Up: Arithmetic
 
7046
 
 
7047
17.7 Mathematical Constants
 
7048
===========================
 
7049
 
 
7050
 -- Built-in Function:  I (X)
 
7051
 -- Built-in Function:  I (N, M)
 
7052
 -- Built-in Function:  I (N, M, K, ...)
 
7053
 -- Built-in Function:  I (..., CLASS)
 
7054
     Return a matrix or N-dimensional array whose elements are all equal
 
7055
     to the pure imaginary unit, defined as   `sqrt (-1)'.  Since I
 
7056
     (also i, J, and j) is a function, you can use the name(s) for
 
7057
     other purposes.
 
7058
 
 
7059
 -- Built-in Function:  Inf (X)
 
7060
 -- Built-in Function:  Inf (N, M)
 
7061
 -- Built-in Function:  Inf (N, M, K, ...)
 
7062
 -- Built-in Function:  Inf (..., CLASS)
 
7063
     Return a matrix or N-dimensional array whose elements are all
 
7064
     Infinity.  The arguments are handled the same as the arguments for
 
7065
     `eye'.  The optional argument CLASS may be either `"single"' or
 
7066
     `"double"'.  The default is `"double"'.
 
7067
 
 
7068
 -- Built-in Function:  NaN (X)
 
7069
 -- Built-in Function:  NaN (N, M)
 
7070
 -- Built-in Function:  NaN (N, M, K, ...)
 
7071
 -- Built-in Function:  NaN (..., CLASS)
 
7072
     Return a matrix or N-dimensional array whose elements are all NaN
 
7073
     (Not a Number).  The value NaN is the result of an operation like
 
7074
     0/0, or `Inf - Inf', or any operation with a NaN.
 
7075
 
 
7076
     Note that NaN always compares not equal to NaN.  This behavior is
 
7077
     specified by the IEEE standard for floating point arithmetic.  To
 
7078
     find NaN values, you must use the `isnan' function.
 
7079
 
 
7080
     The arguments are handled the same as the arguments for `eye'.
 
7081
     The optional argument CLASS may be either `"single"' or
 
7082
     `"double"'.  The default is `"double"'.
 
7083
 
 
7084
 -- Built-in Function:  pi (X)
 
7085
 -- Built-in Function:  pi (N, M)
 
7086
 -- Built-in Function:  pi (N, M, K, ...)
 
7087
 -- Built-in Function:  pi (..., CLASS)
 
7088
     Return a matrix or N-dimensional array whose elements are all equal
 
7089
     to the ratio of the circumference of a circle to its diameter.
 
7090
     Internally, `pi' is computed as `4.0 * atan (1.0)'.
 
7091
 
 
7092
 -- Built-in Function:  e (X)
 
7093
 -- Built-in Function:  e (N, M)
 
7094
 -- Built-in Function:  e (N, M, K, ...)
 
7095
 -- Built-in Function:  e (..., CLASS)
 
7096
     Return a matrix or N-dimensional array whose elements are all equal
 
7097
     to the base of natural logarithms.  The constant  E  satisfies the
 
7098
     equation  `log' (E) = 1.
 
7099
 
 
7100
 -- Built-in Function:  eps (X)
 
7101
 -- Built-in Function:  eps (N, M)
 
7102
 -- Built-in Function:  eps (N, M, K, ...)
 
7103
 -- Built-in Function:  eps (..., CLASS)
 
7104
     Return a matrix or N-dimensional array whose elements are all eps,
 
7105
     the machine precision.  More precisely, `eps' is the largest
 
7106
     relative spacing between any two adjacent numbers in the machine's
 
7107
     floating point system.  This number is obviously system-dependent.
 
7108
     On machines that support 64 bit IEEE floating point arithmetic,
 
7109
     `eps' is approximately  2.2204e-16.
 
7110
 
 
7111
 -- Built-in Function:  realmax (X)
 
7112
 -- Built-in Function:  realmax (N, M)
 
7113
 -- Built-in Function:  realmax (N, M, K, ...)
 
7114
 -- Built-in Function:  realmax (..., CLASS)
 
7115
     Return a matrix or N-dimensional array whose elements are all equal
 
7116
     to the largest floating point number that is representable.  The
 
7117
     actual value is system-dependent.  On machines that support 64-bit
 
7118
     IEEE floating point arithmetic, `realmax' is approximately
 
7119
     1.7977e+308
 
7120
 
 
7121
     *See also:* realmin.
 
7122
 
 
7123
 -- Built-in Function:  realmin (X)
 
7124
 -- Built-in Function:  realmin (N, M)
 
7125
 -- Built-in Function:  realmin (N, M, K, ...)
 
7126
 -- Built-in Function:  realmin (..., CLASS)
 
7127
     Return a matrix or N-dimensional array whose elements are all equal
 
7128
     to the smallest normalized floating point number that is
 
7129
     representable.  The actual value is system-dependent.  On machines
 
7130
     that support 64-bit IEEE floating point arithmetic, `realmin' is
 
7131
     approximately  2.2251e-308
 
7132
 
 
7133
     *See also:* realmax.
 
7134
 
 
7135
 
 
7136
File: octave.info,  Node: Linear Algebra,  Next: Nonlinear Equations,  Prev: Arithmetic,  Up: Top
 
7137
 
 
7138
18 Linear Algebra
 
7139
*****************
 
7140
 
 
7141
This chapter documents the linear algebra functions of Octave.
 
7142
Reference material for many of these functions may be found in Golub
 
7143
and Van Loan, `Matrix Computations, 2nd Ed.', Johns Hopkins, 1989, and
 
7144
in `LAPACK Users' Guide', SIAM, 1992.
 
7145
 
 
7146
* Menu:
 
7147
 
 
7148
* Techniques used for Linear Algebra::
 
7149
* Basic Matrix Functions::
 
7150
* Matrix Factorizations::
 
7151
* Functions of a Matrix::
 
7152
 
 
7153
 
 
7154
File: octave.info,  Node: Techniques used for Linear Algebra,  Next: Basic Matrix Functions,  Up: Linear Algebra
 
7155
 
 
7156
18.1 Techniques used for Linear Algebra
 
7157
=======================================
 
7158
 
 
7159
Octave includes a poly-morphic solver, that selects an appropriate
 
7160
matrix factorization depending on the properties of the matrix itself.
 
7161
Generally, the cost of determining the matrix type is small relative to
 
7162
the cost of factorizing the matrix itself, but in any case the matrix
 
7163
type is cached once it is calculated, so that it is not re-determined
 
7164
each time it is used in a linear equation.
 
7165
 
 
7166
   The selection tree for how the linear equation is solve or a matrix
 
7167
inverse is form is given by
 
7168
 
 
7169
  1. If the matrix is upper or lower triangular sparse a forward or
 
7170
     backward substitution using the LAPACK xTRTRS function, and goto 4.
 
7171
 
 
7172
  2. If the matrix is square, hermitian with a real positive diagonal,
 
7173
     attempt Cholesky factorization using the LAPACK xPOTRF function.
 
7174
 
 
7175
  3. If the Cholesky factorization failed or the matrix is not
 
7176
     hermitian with a real positive diagonal, and the matrix is square,
 
7177
     factorize using the LAPACK xGETRF function.
 
7178
 
 
7179
  4. If the matrix is not square, or any of the previous solvers flags
 
7180
     a singular or near singular matrix, find a least squares solution
 
7181
     using the LAPACK xGELSD function.
 
7182
 
 
7183
   The user can force the type of the matrix with the `matrix_type'
 
7184
function. This overcomes the cost of discovering the type of the matrix.
 
7185
However, it should be noted incorrectly identifying the type of the
 
7186
matrix will lead to unpredictable results, and so `matrix_type' should
 
7187
be used with care.
 
7188
 
 
7189
   It should be noted that the test for whether a matrix is a candidate
 
7190
for Cholesky factorization, performed above and by the `matrix_type'
 
7191
function, does not give a certainty that the matrix is Hermitian.
 
7192
However, the attempt to factorize the matrix will quickly flag a
 
7193
non-Hermitian matrix.
 
7194
 
 
7195
 
 
7196
File: octave.info,  Node: Basic Matrix Functions,  Next: Matrix Factorizations,  Prev: Techniques used for Linear Algebra,  Up: Linear Algebra
 
7197
 
 
7198
18.2 Basic Matrix Functions
 
7199
===========================
 
7200
 
 
7201
 -- Loadable Function: AA = balance (A, OPT)
 
7202
 -- Loadable Function: [DD, AA] = balance (A, OPT)
 
7203
 -- Loadable Function: [CC, DD, AA, BB] = balance (A, B, OPT)
 
7204
     Compute `aa = dd \ a * dd' in which `aa' is a matrix whose row and
 
7205
     column norms are roughly equal in magnitude, and `dd' = `p * d',
 
7206
     in which `p' is a permutation matrix and `d' is a diagonal matrix
 
7207
     of powers of two.  This allows the equilibration to be computed
 
7208
     without roundoff.  Results of eigenvalue calculation are typically
 
7209
     improved by balancing first.
 
7210
 
 
7211
     If four output values are requested, compute `aa = cc*a*dd' and
 
7212
     `bb = cc*b*dd)', in which `aa' and `bb' have non-zero elements of
 
7213
     approximately the same magnitude and `cc' and `dd' are permuted
 
7214
     diagonal matrices as in `dd' for the algebraic eigenvalue problem.
 
7215
 
 
7216
     The eigenvalue balancing option `opt' may be one of:
 
7217
 
 
7218
    `"N"', `"n"'
 
7219
          No balancing; arguments copied, transformation(s) set to
 
7220
          identity.
 
7221
 
 
7222
    `"P"', `"p"'
 
7223
          Permute argument(s) to isolate eigenvalues where possible.
 
7224
 
 
7225
    `"S"', `"s"'
 
7226
          Scale to improve accuracy of computed eigenvalues.
 
7227
 
 
7228
    `"B"', `"b"'
 
7229
          Permute and scale, in that order. Rows/columns of a (and b)
 
7230
          that are isolated by permutation are not scaled.  This is the
 
7231
          default behavior.
 
7232
 
 
7233
     Algebraic eigenvalue balancing uses standard LAPACK routines.
 
7234
 
 
7235
     Generalized eigenvalue problem balancing uses Ward's algorithm
 
7236
     (SIAM Journal on Scientific and Statistical Computing, 1981).
 
7237
 
 
7238
 -- Function File:  cond (A)
 
7239
     Compute the (two-norm) condition number of a matrix. `cond (a)' is
 
7240
     defined as `norm (a) * norm (inv (a))', and is computed via a
 
7241
     singular value decomposition.
 
7242
 
 
7243
     *See also:* norm, svd, rank.
 
7244
 
 
7245
 -- Loadable Function: [D, RCOND] =  det (A)
 
7246
     Compute the determinant of A using LAPACK.  Return an estimate of
 
7247
     the reciprocal condition number if requested.
 
7248
 
 
7249
 -- Function File:  dmult (A, B)
 
7250
     If A is a vector of length `rows (B)', return `diag (A) * B' (but
 
7251
     computed much more efficiently).
 
7252
 
 
7253
 -- Function File:  dot (X, Y, DIM)
 
7254
     Computes the dot product of two vectors. If X and Y are matrices,
 
7255
     calculate the dot-product along the first non-singleton dimension.
 
7256
     If the optional argument DIM is given, calculate the dot-product
 
7257
     along this dimension.
 
7258
 
 
7259
 -- Loadable Function: LAMBDA = eig (A)
 
7260
 -- Loadable Function: [V, LAMBDA] = eig (A)
 
7261
     The eigenvalues (and eigenvectors) of a matrix are computed in a
 
7262
     several step process which begins with a Hessenberg decomposition,
 
7263
     followed by a Schur decomposition, from which the eigenvalues are
 
7264
     apparent.  The eigenvectors, when desired, are computed by further
 
7265
     manipulations of the Schur decomposition.
 
7266
 
 
7267
     The eigenvalues returned by `eig' are not ordered.
 
7268
 
 
7269
 -- Loadable Function: G = givens (X, Y)
 
7270
 -- Loadable Function: [C, S] = givens (X, Y)
 
7271
     Return a 2 by 2 orthogonal matrix `G = [C S; -S' C]' such that `G
 
7272
     [X; Y] = [*; 0]' with X and Y scalars.
 
7273
 
 
7274
     For example,
 
7275
 
 
7276
          givens (1, 1)
 
7277
               =>   0.70711   0.70711
 
7278
                   -0.70711   0.70711
 
7279
 
 
7280
 -- Loadable Function: [X, RCOND] =  inv (A)
 
7281
 -- Loadable Function: [X, RCOND] =  inverse (A)
 
7282
     Compute the inverse of the square matrix A.  Return an estimate of
 
7283
     the reciprocal condition number if requested, otherwise warn of an
 
7284
     ill-conditioned matrix if the reciprocal condition number is small.
 
7285
 
 
7286
 -- Loadable Function: TYPE = matrix_type (A)
 
7287
 -- Loadable Function: A = matrix_type (A, TYPE)
 
7288
 -- Loadable Function: A = matrix_type (A, 'upper', PERM)
 
7289
 -- Loadable Function: A = matrix_type (A, 'lower', PERM)
 
7290
 -- Loadable Function: A = matrix_type (A, 'banded', NL, NU)
 
7291
     Identify the matrix type or mark a matrix as a particular type.
 
7292
     This allows rapid for solutions of linear equations involving A to
 
7293
     be performed. Called with a single argument, `matrix_type' returns
 
7294
     the type of the matrix and caches it for future use. Called with
 
7295
     more than one argument, `matrix_type' allows the type of the
 
7296
     matrix to be defined.
 
7297
 
 
7298
     The possible matrix types depend on whether the matrix is full or
 
7299
     sparse, and can be one of the following
 
7300
 
 
7301
    'unknown'
 
7302
          Remove any previously cached matrix type, and mark type as
 
7303
          unknown
 
7304
 
 
7305
    'full'
 
7306
          Mark the matrix as full.
 
7307
 
 
7308
    'positive definite'
 
7309
          Full positive definite matrix.
 
7310
 
 
7311
    'diagonal'
 
7312
          Diagonal Matrix. (Sparse matrices only)
 
7313
 
 
7314
    'permuted diagonal'
 
7315
          Permuted Diagonal matrix. The permutation does not need to be
 
7316
          specifically indicated, as the structure of the matrix
 
7317
          explicitly gives this. (Sparse matrices only)
 
7318
 
 
7319
    'upper'
 
7320
          Upper triangular. If the optional third argument PERM is
 
7321
          given, the matrix is assumed to be a permuted upper
 
7322
          triangular with the permutations defined by the vector PERM.
 
7323
 
 
7324
    'lower'
 
7325
          Lower triangular. If the optional third argument PERM is
 
7326
          given, the matrix is assumed to be a permuted lower
 
7327
          triangular with the permutations defined by the vector PERM.
 
7328
 
 
7329
    'banded'
 
7330
    'banded positive definite'
 
7331
          Banded matrix with the band size of NL below the diagonal and
 
7332
          NU above it. If NL and NU are 1, then the matrix is
 
7333
          tridiagonal and treated with specialized code. In addition
 
7334
          the matrix can be marked as positive definite (Sparse
 
7335
          matrices only)
 
7336
 
 
7337
    'singular'
 
7338
          The matrix is assumed to be singular and will be treated with
 
7339
          a minimum norm solution
 
7340
 
 
7341
 
 
7342
     Note that the matrix type will be discovered automatically on the
 
7343
     first attempt to solve a linear equation involving A. Therefore
 
7344
     `matrix_type' is only useful to give Octave hints of the matrix
 
7345
     type. Incorrectly defining the matrix type will result in
 
7346
     incorrect results from solutions of linear equations, and so it is
 
7347
     entirely the responsibility of the user to correctly identify the
 
7348
     matrix type.
 
7349
 
 
7350
 -- Function File:  norm (A, P)
 
7351
     Compute the p-norm of the matrix A.  If the second argument is
 
7352
     missing, `p = 2' is assumed.
 
7353
 
 
7354
     If A is a matrix:
 
7355
 
 
7356
    P = `1'
 
7357
          1-norm, the largest column sum of the absolute values of A.
 
7358
 
 
7359
    P = `2'
 
7360
          Largest singular value of A.
 
7361
 
 
7362
    P = `Inf' or `"inf"'
 
7363
          Infinity norm, the largest row sum of the absolute values of
 
7364
          A.
 
7365
 
 
7366
    P = `"fro"'
 
7367
          Frobenius norm of A, `sqrt (sum (diag (A' * A)))'.
 
7368
 
 
7369
     If A is a vector or a scalar:
 
7370
 
 
7371
    P = `Inf' or `"inf"'
 
7372
          `max (abs (A))'.
 
7373
 
 
7374
    P = `-Inf'
 
7375
          `min (abs (A))'.
 
7376
 
 
7377
    P = `"fro"'
 
7378
          Frobenius norm of A, `sqrt (sumsq (abs (a)))'.
 
7379
 
 
7380
    other
 
7381
          p-norm of A, `(sum (abs (A) .^ P)) ^ (1/P)'.
 
7382
 
 
7383
 
 
7384
     *See also:* cond, svd.
 
7385
 
 
7386
 -- Function File:  null (A, TOL)
 
7387
     Return an orthonormal basis of the null space of A.
 
7388
 
 
7389
     The dimension of the null space is taken as the number of singular
 
7390
     values of A not greater than TOL.  If the argument TOL is missing,
 
7391
     it is computed as
 
7392
 
 
7393
          max (size (A)) * max (svd (A)) * eps
 
7394
 
 
7395
 -- Function File:  orth (A, TOL)
 
7396
     Return an orthonormal basis of the range space of A.
 
7397
 
 
7398
     The dimension of the range space is taken as the number of singular
 
7399
     values of A greater than TOL.  If the argument TOL is missing, it
 
7400
     is computed as
 
7401
 
 
7402
          max (size (A)) * max (svd (A)) * eps
 
7403
 
 
7404
 -- Loadable Function:  pinv (X, TOL)
 
7405
     Return the pseudoinverse of X.  Singular values less than TOL are
 
7406
     ignored.
 
7407
 
 
7408
     If the second argument is omitted, it is assumed that
 
7409
 
 
7410
          tol = max (size (X)) * sigma_max (X) * eps,
 
7411
 
 
7412
     where `sigma_max (X)' is the maximal singular value of X.
 
7413
 
 
7414
 -- Function File:  rank (A, TOL)
 
7415
     Compute the rank of A, using the singular value decomposition.
 
7416
     The rank is taken to be the number  of singular values of A that
 
7417
     are greater than the specified tolerance TOL.  If the second
 
7418
     argument is omitted, it is taken to be
 
7419
 
 
7420
          tol = max (size (A)) * sigma(1) * eps;
 
7421
 
 
7422
     where `eps' is machine precision and `sigma(1)' is the largest
 
7423
     singular value of A.
 
7424
 
 
7425
 -- Function File:  trace (A)
 
7426
     Compute the trace of A, `sum (diag (A))'.
 
7427
 
 
7428
 -- Function File: [R, K] = rref (A, TOL)
 
7429
     Returns the reduced row echelon form of A. TOL defaults to `eps *
 
7430
     max (size (A)) * norm (A, inf)'.
 
7431
 
 
7432
     Called with two return arguments, K returns the vector of "bound
 
7433
     variables", which are those columns on which elimination has been
 
7434
     performed.
 
7435
 
 
7436
 
 
7437
 
 
7438
File: octave.info,  Node: Matrix Factorizations,  Next: Functions of a Matrix,  Prev: Basic Matrix Functions,  Up: Linear Algebra
 
7439
 
 
7440
18.3 Matrix Factorizations
 
7441
==========================
 
7442
 
 
7443
 -- Loadable Function:  chol (A)
 
7444
     Compute the Cholesky factor, R, of the symmetric positive definite
 
7445
     matrix A, where
 
7446
 
 
7447
          r' * r = a.
 
7448
 
 
7449
 
 
7450
     *See also:* cholinv, chol2inv.
 
7451
 
 
7452
 -- Loadable Function:  cholinv (A)
 
7453
     Use the Cholesky factorization to compute the inverse of the
 
7454
     symmetric positive definite matrix A.
 
7455
 
 
7456
     *See also:* chol, chol2inv.
 
7457
 
 
7458
 -- Loadable Function:  chol2inv (U)
 
7459
     Invert a symmetric, positive definite square matrix from its
 
7460
     Cholesky decomposition, U.  Note that U should be an
 
7461
     upper-triangular matrix with positive diagonal elements.
 
7462
     `chol2inv (U)' provides `inv (U'*U)' but it is much faster than
 
7463
     using `inv'.
 
7464
 
 
7465
     *See also:* chol, cholinv.
 
7466
 
 
7467
 -- Loadable Function: H = hess (A)
 
7468
 -- Loadable Function: [P, H] = hess (A)
 
7469
     Compute the Hessenberg decomposition of the matrix A.
 
7470
 
 
7471
     The Hessenberg decomposition is usually used as the first step in
 
7472
     an eigenvalue computation, but has other applications as well (see
 
7473
     Golub, Nash, and Van Loan, IEEE Transactions on Automatic Control,
 
7474
     1979).  The Hessenberg decomposition is `p * h * p' = a' where `p'
 
7475
     is a square unitary matrix (`p' * p = I', using complex-conjugate
 
7476
     transposition) and `h' is upper Hessenberg (`i >= j+1 => h (i, j)
 
7477
     = 0').
 
7478
 
 
7479
 -- Loadable Function: [L, U, P] = lu (A)
 
7480
     Compute the LU decomposition of A, using subroutines from LAPACK.
 
7481
     The result is returned in a permuted form, according to the
 
7482
     optional return value P.  For example, given the matrix `a = [1,
 
7483
     2; 3, 4]',
 
7484
 
 
7485
          [l, u, p] = lu (a)
 
7486
 
 
7487
     returns
 
7488
 
 
7489
          l =
 
7490
 
 
7491
            1.00000  0.00000
 
7492
            0.33333  1.00000
 
7493
 
 
7494
          u =
 
7495
 
 
7496
            3.00000  4.00000
 
7497
            0.00000  0.66667
 
7498
 
 
7499
          p =
 
7500
 
 
7501
            0  1
 
7502
            1  0
 
7503
 
 
7504
     The matrix is not required to be square.
 
7505
 
 
7506
 -- Loadable Function: [Q, R, P] = qr (A)
 
7507
     Compute the QR factorization of A, using standard LAPACK
 
7508
     subroutines.  For example, given the matrix `a = [1, 2; 3, 4]',
 
7509
 
 
7510
          [q, r] = qr (a)
 
7511
 
 
7512
     returns
 
7513
 
 
7514
          q =
 
7515
 
 
7516
            -0.31623  -0.94868
 
7517
            -0.94868   0.31623
 
7518
 
 
7519
          r =
 
7520
 
 
7521
            -3.16228  -4.42719
 
7522
             0.00000  -0.63246
 
7523
 
 
7524
     The `qr' factorization has applications in the solution of least
 
7525
     squares problems
 
7526
 
 
7527
          `min norm(A x - b)'
 
7528
 
 
7529
     for overdetermined systems of equations (i.e., `a'  is a tall,
 
7530
     thin matrix).  The QR factorization is `q * r = a' where `q' is an
 
7531
     orthogonal matrix and `r' is upper triangular.
 
7532
 
 
7533
     The permuted QR factorization `[Q, R, P] = qr (A)' forms the QR
 
7534
     factorization such that the diagonal entries of `r' are decreasing
 
7535
     in magnitude order.  For example, given the matrix `a = [1, 2; 3,
 
7536
     4]',
 
7537
 
 
7538
          [q, r, p] = qr(a)
 
7539
 
 
7540
     returns
 
7541
 
 
7542
          q =
 
7543
 
 
7544
            -0.44721  -0.89443
 
7545
            -0.89443   0.44721
 
7546
 
 
7547
          r =
 
7548
 
 
7549
            -4.47214  -3.13050
 
7550
             0.00000   0.44721
 
7551
 
 
7552
          p =
 
7553
 
 
7554
             0  1
 
7555
             1  0
 
7556
 
 
7557
     The permuted `qr' factorization `[q, r, p] = qr (a)' factorization
 
7558
     allows the construction of an orthogonal basis of `span (a)'.
 
7559
 
 
7560
 -- Loadable Function: LAMBDA = qz (A, B)
 
7561
     Generalized eigenvalue problem A x = s B x, QZ decomposition.
 
7562
     There are three ways to call this function:
 
7563
       1. `lambda = qz(A,B)'
 
7564
 
 
7565
          Computes the generalized eigenvalues LAMBDA of (A - s B).
 
7566
 
 
7567
       2. `[AA, BB, Q, Z, V, W, lambda] = qz (A, B)'
 
7568
 
 
7569
          Computes qz decomposition, generalized eigenvectors, and
 
7570
          generalized eigenvalues of (A - sB)
 
7571
 
 
7572
                   A*V = B*V*diag(lambda)
 
7573
                   W'*A = diag(lambda)*W'*B
 
7574
                   AA = Q'*A*Z, BB = Q'*B*Z
 
7575
          with Q and Z orthogonal (unitary)= I
 
7576
 
 
7577
       3. `[AA,BB,Z{, lambda}] = qz(A,B,opt)'
 
7578
 
 
7579
          As in form [2], but allows ordering of generalized eigenpairs
 
7580
          for (e.g.) solution of discrete time algebraic Riccati
 
7581
          equations.  Form 3 is not available for complex matrices, and
 
7582
          does not compute the generalized eigenvectors V, W, nor the
 
7583
          orthogonal matrix Q.
 
7584
         OPT
 
7585
               for ordering eigenvalues of the GEP pencil.  The leading
 
7586
               block of the revised pencil contains all eigenvalues
 
7587
               that satisfy:
 
7588
              `"N"'
 
7589
                    = unordered (default)
 
7590
 
 
7591
              `"S"'
 
7592
                    = small: leading block has all |lambda| <=1
 
7593
 
 
7594
              `"B"'
 
7595
                    = big: leading block has all |lambda| >= 1
 
7596
 
 
7597
              `"-"'
 
7598
                    = negative real part: leading block has all
 
7599
                    eigenvalues in the open left half-plane
 
7600
 
 
7601
              `"+"'
 
7602
                    = nonnegative real part: leading block has all
 
7603
                    eigenvalues in the closed right half-plane
 
7604
 
 
7605
     Note: qz performs permutation balancing, but not scaling (see
 
7606
     balance).  Order of output arguments was selected for
 
7607
     compatibility with MATLAB
 
7608
 
 
7609
 
 
7610
     *See also:* balance, dare, eig, schur.
 
7611
 
 
7612
 -- Function File: [AA, BB, Q, Z] = qzhess (A, B)
 
7613
     Compute the Hessenberg-triangular decomposition of the matrix
 
7614
     pencil `(A, B)', returning `AA = Q * A * Z', `BB = Q * B * Z',
 
7615
     with Q and Z orthogonal.  For example,
 
7616
 
 
7617
          [aa, bb, q, z] = qzhess ([1, 2; 3, 4], [5, 6; 7, 8])
 
7618
          => aa = [ -3.02244, -4.41741;  0.92998,  0.69749 ]
 
7619
          => bb = [ -8.60233, -9.99730;  0.00000, -0.23250 ]
 
7620
          =>  q = [ -0.58124, -0.81373; -0.81373,  0.58124 ]
 
7621
          =>  z = [ 1, 0; 0, 1 ]
 
7622
 
 
7623
     The Hessenberg-triangular decomposition is the first step in Moler
 
7624
     and Stewart's QZ decomposition algorithm.
 
7625
 
 
7626
     Algorithm taken from Golub and Van Loan, `Matrix Computations, 2nd
 
7627
     edition'.
 
7628
 
 
7629
 -- Loadable Function: S = schur (A)
 
7630
 -- Loadable Function: [U, S] = schur (A, OPT)
 
7631
     The Schur decomposition is used to compute eigenvalues of a square
 
7632
     matrix, and has applications in the solution of algebraic Riccati
 
7633
     equations in control (see `are' and `dare').  `schur' always
 
7634
     returns `s = u' * a * u' where `u'  is a unitary matrix (`u'* u'
 
7635
     is identity) and `s' is upper triangular.  The eigenvalues of `a'
 
7636
     (and `s') are the diagonal elements of `s'.  If the matrix `a' is
 
7637
     real, then the real Schur decomposition is computed, in which the
 
7638
     matrix `u' is orthogonal and `s' is block upper triangular with
 
7639
     blocks of size at most `2 x 2' along the diagonal.  The diagonal
 
7640
     elements of `s' (or the eigenvalues of the `2 x 2' blocks, when
 
7641
     appropriate) are the eigenvalues of `a' and `s'.
 
7642
 
 
7643
     The eigenvalues are optionally ordered along the diagonal
 
7644
     according to the value of `opt'.  `opt = "a"' indicates that all
 
7645
     eigenvalues with negative real parts should be moved to the leading
 
7646
     block of `s' (used in `are'), `opt = "d"' indicates that all
 
7647
     eigenvalues with magnitude less than one should be moved to the
 
7648
     leading block of `s' (used in `dare'), and `opt = "u"', the
 
7649
     default, indicates that no ordering of eigenvalues should occur.
 
7650
     The leading `k' columns of `u' always span the `a'-invariant
 
7651
     subspace corresponding to the `k' leading eigenvalues of `s'.
 
7652
 
 
7653
 -- Loadable Function: S = svd (A)
 
7654
 -- Loadable Function: [U, S, V] = svd (A)
 
7655
     Compute the singular value decomposition of A
 
7656
 
 
7657
          A = U*S*V'
 
7658
 
 
7659
     The function `svd' normally returns the vector of singular values.
 
7660
     If asked for three return values, it computes U, S, and V.  For
 
7661
     example,
 
7662
 
 
7663
          svd (hilb (3))
 
7664
 
 
7665
     returns
 
7666
 
 
7667
          ans =
 
7668
 
 
7669
            1.4083189
 
7670
            0.1223271
 
7671
            0.0026873
 
7672
 
 
7673
     and
 
7674
 
 
7675
          [u, s, v] = svd (hilb (3))
 
7676
 
 
7677
     returns
 
7678
 
 
7679
          u =
 
7680
 
 
7681
            -0.82704   0.54745   0.12766
 
7682
            -0.45986  -0.52829  -0.71375
 
7683
            -0.32330  -0.64901   0.68867
 
7684
 
 
7685
          s =
 
7686
 
 
7687
            1.40832  0.00000  0.00000
 
7688
            0.00000  0.12233  0.00000
 
7689
            0.00000  0.00000  0.00269
 
7690
 
 
7691
          v =
 
7692
 
 
7693
            -0.82704   0.54745   0.12766
 
7694
            -0.45986  -0.52829  -0.71375
 
7695
            -0.32330  -0.64901   0.68867
 
7696
 
 
7697
     If given a second argument, `svd' returns an economy-sized
 
7698
     decomposition, eliminating the unnecessary rows or columns of U or
 
7699
     V.
 
7700
 
 
7701
 -- Function File: [HOUSV, BETA, ZER] = housh (X, J, Z)
 
7702
     Compute Householder reflection vector HOUSV to reflect X to be the
 
7703
     jth column of identity, i.e.,
 
7704
 
 
7705
          (I - beta*housv*housv')x =  norm(x)*e(j) if x(1) < 0,
 
7706
          (I - beta*housv*housv')x = -norm(x)*e(j) if x(1) >= 0
 
7707
 
 
7708
     Inputs
 
7709
 
 
7710
    X
 
7711
          vector
 
7712
 
 
7713
    J
 
7714
          index into vector
 
7715
 
 
7716
    Z
 
7717
          threshold for zero  (usually should be the number 0)
 
7718
 
 
7719
     Outputs (see Golub and Van Loan):
 
7720
 
 
7721
    BETA
 
7722
          If beta = 0, then no reflection need be applied (zer set to 0)
 
7723
 
 
7724
    HOUSV
 
7725
          householder vector
 
7726
 
 
7727
 -- Function File: [U, H, NU] = krylov (A, V, K, EPS1, PFLG)
 
7728
     Construct an orthogonal basis U of block Krylov subspace
 
7729
 
 
7730
          [v a*v a^2*v ... a^(k+1)*v]
 
7731
 
 
7732
     Using Householder reflections to guard against loss of
 
7733
     orthogonality.
 
7734
 
 
7735
     If V is a vector, then H contains the Hessenberg matrix such that
 
7736
     `a*u == u*h+rk*ek'', in which `rk = a*u(:,k)-u*h(:,k)', and `ek''
 
7737
     is the vector `[0, 0, ..., 1]' of length `k'.  Otherwise, H is
 
7738
     meaningless.
 
7739
 
 
7740
     If V is a vector and K is greater than `length(A)-1', then H
 
7741
     contains the Hessenberg matrix such that `a*u == u*h'.
 
7742
 
 
7743
     The value of NU is the dimension of the span of the krylov
 
7744
     subspace (based on EPS1).
 
7745
 
 
7746
     If B is a vector and K is greater than M-1, then H contains the
 
7747
     Hessenberg decomposition of A.
 
7748
 
 
7749
     The optional parameter EPS1 is the threshold for zero.  The
 
7750
     default value is 1e-12.
 
7751
 
 
7752
     If the optional parameter PFLG is nonzero, row pivoting is used to
 
7753
     improve numerical behavior.  The default value is 0.
 
7754
 
 
7755
     Reference: Hodel and Misra, "Partial Pivoting in the Computation of
 
7756
     Krylov Subspaces", to be submitted to Linear Algebra and its
 
7757
     Applications
 
7758
 
 
7759
 
 
7760
File: octave.info,  Node: Functions of a Matrix,  Prev: Matrix Factorizations,  Up: Linear Algebra
 
7761
 
 
7762
18.4 Functions of a Matrix
 
7763
==========================
 
7764
 
 
7765
 -- Loadable Function:  expm (A)
 
7766
     Return the exponential of a matrix, defined as the infinite Taylor
 
7767
     series
 
7768
 
 
7769
          expm(a) = I + a + a^2/2! + a^3/3! + ...
 
7770
 
 
7771
     The Taylor series is _not_ the way to compute the matrix
 
7772
     exponential; see Moler and Van Loan, `Nineteen Dubious Ways to
 
7773
     Compute the Exponential of a Matrix', SIAM Review, 1978.  This
 
7774
     routine uses Ward's diagonal Pade' approximation method with three
 
7775
     step preconditioning (SIAM Journal on Numerical Analysis, 1977).
 
7776
     Diagonal Pade'  approximations are rational polynomials of matrices
 
7777
 
 
7778
               -1
 
7779
          D (a)   N (a)
 
7780
 
 
7781
     whose Taylor series matches the first `2q+1' terms of the Taylor
 
7782
     series above; direct evaluation of the Taylor series (with the
 
7783
     same preconditioning steps) may be desirable in lieu of the Pade'
 
7784
     approximation when `Dq(a)' is ill-conditioned.
 
7785
 
 
7786
 -- Function File:  logm (A)
 
7787
     Compute the matrix logarithm of the square matrix A.  Note that
 
7788
     this is currently implemented in terms of an eigenvalue expansion
 
7789
     and needs to be improved to be more robust.
 
7790
 
 
7791
 -- Loadable Function: [RESULT, ERROR_ESTIMATE] = sqrtm (A)
 
7792
     Compute the matrix square root of the square matrix A.
 
7793
 
 
7794
     Ref: Nicholas J. Higham. A new sqrtm for MATLAB. Numerical Analysis
 
7795
     Report No. 336, Manchester Centre for Computational Mathematics,
 
7796
     Manchester, England, January 1999.
 
7797
 
 
7798
     *See also:* expm, logm, funm.
 
7799
 
 
7800
 -- Loadable Function:  kron (A, B)
 
7801
     Form the kronecker product of two matrices, defined block by block
 
7802
     as
 
7803
 
 
7804
          x = [a(i, j) b]
 
7805
 
 
7806
     For example,
 
7807
 
 
7808
          kron (1:4, ones (3, 1))
 
7809
                =>  1  2  3  4
 
7810
                    1  2  3  4
 
7811
                    1  2  3  4
 
7812
 
 
7813
 -- Loadable Function: X = syl (A, B, C)
 
7814
     Solve the Sylvester equation
 
7815
 
 
7816
          A X + X B + C = 0
 
7817
     using standard LAPACK subroutines.  For example,
 
7818
 
 
7819
          syl ([1, 2; 3, 4], [5, 6; 7, 8], [9, 10; 11, 12])
 
7820
               => [ -0.50000, -0.66667; -0.66667, -0.50000 ]
 
7821
 
 
7822
 
 
7823
File: octave.info,  Node: Nonlinear Equations,  Next: Sparse Matrices,  Prev: Linear Algebra,  Up: Top
 
7824
 
 
7825
19 Nonlinear Equations
 
7826
**********************
 
7827
 
 
7828
Octave can solve sets of nonlinear equations of the form
 
7829
 
 
7830
     F (x) = 0
 
7831
 
 
7832
using the function `fsolve', which is based on the MINPACK subroutine
 
7833
`hybrd'.  This is an iterative technique so a starting point will have
 
7834
to be provided.  This also has the consequence that convergence is not
 
7835
guarantied even if a solution exists.
 
7836
 
 
7837
 -- Loadable Function: [X, FVAL, INFO] = fsolve (FCN, X0)
 
7838
     Given FCN, the name of a function of the form `f (X)' and an
 
7839
     initial starting point X0, `fsolve' solves the set of equations
 
7840
     such that `f(X) == 0'.
 
7841
 
 
7842
     If FCN is a two-element string array, or a two element cell array
 
7843
     containing either the function name or inline or function handle.
 
7844
     The first element names the function f described above, and the
 
7845
     second element names a function of the form `j (X)' to compute the
 
7846
     Jacobian matrix with elements
 
7847
 
 
7848
                     df_i
 
7849
          jac(i,j) = ----
 
7850
                     dx_j
 
7851
 
 
7852
     You can use the function `fsolve_options' to set optional
 
7853
     parameters for `fsolve'.
 
7854
 
 
7855
 -- Loadable Function:  fsolve_options (OPT, VAL)
 
7856
     When called with two arguments, this function allows you set
 
7857
     options parameters for the function `fsolve'.  Given one argument,
 
7858
     `fsolve_options' returns the value of the corresponding option.  If
 
7859
     no arguments are supplied, the names of all the available options
 
7860
     and their current values are displayed.
 
7861
 
 
7862
     Options include
 
7863
 
 
7864
    `"tolerance"'
 
7865
          Nonnegative relative tolerance.
 
7866
 
 
7867
   Here is a complete example.  To solve the set of equations
 
7868
 
 
7869
     -2x^2 + 3xy   + 4 sin(y) = 6
 
7870
      3x^2 - 2xy^2 + 3 cos(x) = -4
 
7871
 
 
7872
you first need to write a function to compute the value of the given
 
7873
function.  For example:
 
7874
 
 
7875
     function y = f (x)
 
7876
       y(1) = -2*x(1)^2 + 3*x(1)*x(2)   + 4*sin(x(2)) - 6;
 
7877
       y(2) =  3*x(1)^2 - 2*x(1)*x(2)^2 + 3*cos(x(1)) + 4;
 
7878
     endfunction
 
7879
 
 
7880
   Then, call `fsolve' with a specified initial condition to find the
 
7881
roots of the system of equations.  For example, given the function `f'
 
7882
defined above,
 
7883
 
 
7884
     [x, info] = fsolve (@f, [1; 2])
 
7885
 
 
7886
results in the solution
 
7887
 
 
7888
     x =
 
7889
 
 
7890
       0.57983
 
7891
       2.54621
 
7892
 
 
7893
     info = 1
 
7894
 
 
7895
A value of `info = 1' indicates that the solution has converged.
 
7896
 
 
7897
   The function `perror' may be used to print English messages
 
7898
corresponding to the numeric error codes.  For example,
 
7899
 
 
7900
     perror ("fsolve", 1)
 
7901
          -| solution converged to requested tolerance
 
7902
 
 
7903
   When no Jacobian is supplied (as in the example above) it is
 
7904
approximated numerically.  This requires more function evaluations, and
 
7905
hence is less efficient.  In the example above we could compute the
 
7906
Jacobian analytically as
 
7907
 
 
7908
     function J = jacobian(x)
 
7909
       J(1,1) =  3*x(2) - 4*x(1);
 
7910
       J(1,2) =  4*cos(x(2)) + 3*x(1);
 
7911
       J(2,1) = -2*x(2)^2 - 3*sin(x(1)) + 6*x(1);
 
7912
       J(2,2) = -4*x(1)*x(2);
 
7913
     endfunction
 
7914
 
 
7915
Using this Jacobian is done with the following code
 
7916
 
 
7917
     [x, info] = fsolve ({@f, @jacobian}, [1; 2]);
 
7918
 
 
7919
which gives the same solution as before.
 
7920
 
 
7921
 
 
7922
File: octave.info,  Node: Sparse Matrices,  Next: Numerical Integration,  Prev: Nonlinear Equations,  Up: Top
 
7923
 
 
7924
20 Sparse Matrices
 
7925
******************
 
7926
 
 
7927
* Menu:
 
7928
 
 
7929
* Basics:: The Creation and Manipulation of Sparse Matrices
 
7930
* Sparse Linear Algebra:: Linear Algebra on Sparse Matrices
 
7931
* Iterative Techniques:: Iterative Techniques applied to Sparse Matrices
 
7932
* Real Life Example:: Real Life Example of the use of Sparse Matrices
 
7933
 
 
7934
 
 
7935
File: octave.info,  Node: Basics,  Next: Sparse Linear Algebra,  Prev: Sparse Matrices,  Up: Sparse Matrices
 
7936
 
 
7937
20.1 The Creation and Manipulation of Sparse Matrices
 
7938
=====================================================
 
7939
 
 
7940
The size of mathematical problems that can be treated at any particular
 
7941
time is generally limited by the available computing resources. Both,
 
7942
the speed of the computer and its available memory place limitation on
 
7943
the problem size.
 
7944
 
 
7945
   There are many classes of mathematical problems which give rise to
 
7946
matrices, where a large number of the elements are zero. In this case
 
7947
it makes sense to have a special matrix type to handle this class of
 
7948
problems where only the non-zero elements of the matrix are stored. Not
 
7949
only does this reduce the amount of memory to store the matrix, but it
 
7950
also means that operations on this type of matrix can take advantage of
 
7951
the a-priori knowledge of the positions of the non-zero elements to
 
7952
accelerate their calculations.
 
7953
 
 
7954
   A matrix type that stores only the non-zero elements is generally
 
7955
called sparse. It is the purpose of this document to discuss the basics
 
7956
of the storage and creation of sparse matrices and the fundamental
 
7957
operations on them.
 
7958
 
 
7959
* Menu:
 
7960
 
 
7961
* Storage:: Storage of Sparse Matrices
 
7962
* Creation:: Creating Sparse Matrices
 
7963
* Information:: Finding out Information about Sparse Matrices
 
7964
* Operators and Functions:: Basic Operators and Functions on Sparse Matrices
 
7965
 
 
7966
 
 
7967
File: octave.info,  Node: Storage,  Next: Creation,  Prev: Basics,  Up: Basics
 
7968
 
 
7969
20.1.1 Storage of Sparse Matrices
 
7970
---------------------------------
 
7971
 
 
7972
It is not strictly speaking necessary for the user to understand how
 
7973
sparse matrices are stored. However, such an understanding will help to
 
7974
get an understanding of the size of sparse matrices. Understanding the
 
7975
storage technique is also necessary for those users wishing to create
 
7976
their own oct-files.
 
7977
 
 
7978
   There are many different means of storing sparse matrix data. What
 
7979
all of the methods have in common is that they attempt to reduce the
 
7980
complexity and storage given a-priori knowledge of the particular class
 
7981
of problems that will be solved. A good summary of the available
 
7982
techniques for storing sparse matrix is given by Saad (1).  With full
 
7983
matrices, knowledge of the point of an element of the matrix within the
 
7984
matrix is implied by its position in the computers memory.  However,
 
7985
this is not the case for sparse matrices, and so the positions of the
 
7986
non-zero elements of the matrix must equally be stored.
 
7987
 
 
7988
   An obvious way to do this is by storing the elements of the matrix as
 
7989
triplets, with two elements being their position in the array (rows and
 
7990
column) and the third being the data itself. This is conceptually easy
 
7991
to grasp, but requires more storage than is strictly needed.
 
7992
 
 
7993
   The storage technique used within Octave is the compressed column
 
7994
format.  In this format the position of each element in a row and the
 
7995
data are stored as previously. However, if we assume that all elements
 
7996
in the same column are stored adjacent in the computers memory, then we
 
7997
only need to store information on the number of non-zero elements in
 
7998
each column, rather than their positions. Thus assuming that the matrix
 
7999
has more non-zero elements than there are columns in the matrix, we win
 
8000
in terms of the amount of memory used.
 
8001
 
 
8002
   In fact, the column index contains one more element than the number
 
8003
of columns, with the first element always being zero. The advantage of
 
8004
this is a simplification in the code, in that there is no special case
 
8005
for the first or last columns. A short example, demonstrating this in C
 
8006
is.
 
8007
 
 
8008
       for (j = 0; j < nc; j++)
 
8009
         for (i = cidx (j); i < cidx(j+1); i++)
 
8010
            printf ("non-zero element (%i,%i) is %d\n",
 
8011
           ridx(i), j, data(i));
 
8012
 
 
8013
   A clear understanding might be had by considering an example of how
 
8014
the above applies to an example matrix. Consider the matrix
 
8015
 
 
8016
         1   2   0  0
 
8017
         0   0   0  3
 
8018
         0   0   0  4
 
8019
 
 
8020
   The non-zero elements of this matrix are
 
8021
 
 
8022
        (1, 1)  => 1
 
8023
        (1, 2)  => 2
 
8024
        (2, 4)  => 3
 
8025
        (3, 4)  => 4
 
8026
 
 
8027
   This will be stored as three vectors CIDX, RIDX and DATA,
 
8028
representing the column indexing, row indexing and data respectively.
 
8029
The contents of these three vectors for the above matrix will be
 
8030
 
 
8031
       CIDX = [0, 1, 2, 2, 4]
 
8032
       RIDX = [0, 0, 1, 2]
 
8033
       DATA = [1, 2, 3, 4]
 
8034
 
 
8035
   Note that this is the representation of these elements with the
 
8036
first row and column assumed to start at zero, while in Octave itself
 
8037
the row and column indexing starts at one. Thus the number of elements
 
8038
in the I-th column is given by `CIDX (I + 1) - CIDX (I)'.
 
8039
 
 
8040
   Although Octave uses a compressed column format, it should be noted
 
8041
that compressed row formats are equally possible. However, in the
 
8042
context of mixed operations between mixed sparse and dense matrices, it
 
8043
makes sense that the elements of the sparse matrices are in the same
 
8044
order as the dense matrices. Octave stores dense matrices in column
 
8045
major ordering, and so sparse matrices are equally stored in this
 
8046
manner.
 
8047
 
 
8048
   A further constraint on the sparse matrix storage used by Octave is
 
8049
that all elements in the rows are stored in increasing order of their
 
8050
row index, which makes certain operations faster. However, it imposes
 
8051
the need to sort the elements on the creation of sparse matrices. Having
 
8052
disordered elements is potentially an advantage in that it makes
 
8053
operations such as concatenating two sparse matrices together easier
 
8054
and faster, however it adds complexity and speed problems elsewhere.
 
8055
 
 
8056
   ---------- Footnotes ----------
 
8057
 
 
8058
   (1) Youcef Saad "SPARSKIT: A basic toolkit for sparse matrix
 
8059
computation", 1994,
 
8060
`http://www-users.cs.umn.edu/~saad/software/SPARSKIT/paper.ps'
 
8061
 
 
8062
 
 
8063
File: octave.info,  Node: Creation,  Next: Information,  Prev: Storage,  Up: Basics
 
8064
 
 
8065
20.1.2 Creating Sparse Matrices
 
8066
-------------------------------
 
8067
 
 
8068
There are several means to create sparse matrix.
 
8069
 
 
8070
Returned from a function
 
8071
     There are many functions that directly return sparse matrices.
 
8072
     These include "speye", "sprand", "spdiag", etc.
 
8073
 
 
8074
Constructed from matrices or vectors
 
8075
     The function "sparse" allows a sparse matrix to be constructed from
 
8076
     three vectors representing the row, column and data.
 
8077
     Alternatively, the function "spconvert" uses a three column matrix
 
8078
     format to allow easy importation of data from elsewhere.
 
8079
 
 
8080
Created and then filled
 
8081
     The function "sparse" or "spalloc" can be used to create an empty
 
8082
     matrix that is then filled by the user
 
8083
 
 
8084
From a user binary program
 
8085
     The user can directly create the sparse matrix within an oct-file.
 
8086
 
 
8087
   There are several basic functions to return specific sparse
 
8088
matrices. For example the sparse identity matrix, is a matrix that is
 
8089
often needed. It therefore has its own function to create it as `speye
 
8090
(N)' or `speye (R, C)', which creates an N-by-N or R-by-C sparse
 
8091
identity matrix.
 
8092
 
 
8093
   Another typical sparse matrix that is often needed is a random
 
8094
distribution of random elements. The functions "sprand" and "sprandn"
 
8095
perform this for uniform and normal random distributions of elements.
 
8096
They have exactly the same calling convention, where `sprand (R, C, D)',
 
8097
creates an R-by-C sparse matrix with a density of filled elements of D.
 
8098
 
 
8099
   Other functions of interest that directly create sparse matrices, are
 
8100
"spdiag" or its generalization "spdiags", that can take the definition
 
8101
of the diagonals of the matrix and create the sparse matrix that
 
8102
corresponds to this. For example
 
8103
 
 
8104
     s = spdiag (sparse(randn(1,n)), -1);
 
8105
 
 
8106
   creates a sparse (N+1)-by-(N+1) sparse matrix with a single diagonal
 
8107
defined.
 
8108
 
 
8109
 -- Loadable Function:  spatan2 (Y, X)
 
8110
     Compute atan (Y / X) for corresponding sparse matrix elements of Y
 
8111
     and X.  The result is in range -pi to pi.
 
8112
 
 
8113
 -- Loadable Function: Y = spcumprod (X,DIM)
 
8114
     Cumulative product of elements along dimension DIM.  If DIM is
 
8115
     omitted, it defaults to 1 (column-wise cumulative products).
 
8116
 
 
8117
     *See also:* spcumsum.
 
8118
 
 
8119
 -- Loadable Function: Y = spcumsum (X,DIM)
 
8120
     Cumulative sum of elements along dimension DIM.  If DIM is
 
8121
     omitted, it defaults to 1 (column-wise cumulative sums).
 
8122
 
 
8123
     *See also:* spcumprod.
 
8124
 
 
8125
 -- Loadable Function:  spdiag (V, K)
 
8126
     Return a diagonal matrix with the sparse vector V on diagonal K.
 
8127
     The second argument is optional. If it is positive, the vector is
 
8128
     placed on the K-th super-diagonal. If it is negative, it is placed
 
8129
     on the -K-th sub-diagonal.  The default value of K is 0, and the
 
8130
     vector is placed on the main diagonal.  For example,
 
8131
 
 
8132
          spdiag ([1, 2, 3], 1)
 
8133
          ans =
 
8134
 
 
8135
          Compressed Column Sparse (rows=4, cols=4, nnz=3)
 
8136
            (1 , 2) -> 1
 
8137
            (2 , 3) -> 2
 
8138
            (3 , 4) -> 3
 
8139
 
 
8140
     Given a matrix argument, instead of a vector, `spdiag' extracts the
 
8141
     K-th diagonal of the sparse matrix.
 
8142
 
 
8143
     *See also:* diag.
 
8144
 
 
8145
 -- Function File: [B, C] = spdiags (A)
 
8146
 -- Function File: B = spdiags (A, C)
 
8147
 -- Function File: B = spdiags (V, C, A)
 
8148
 -- Function File: B = spdiags (V, C, M, N)
 
8149
     A generalization of the function `spdiag'. Called with a single
 
8150
     input argument, the non-zero diagonals C of A are extracted.  With
 
8151
     two arguments the diagonals to extract are given by the vector C.
 
8152
 
 
8153
     The other two forms of `spdiags' modify the input matrix by
 
8154
     replacing the diagonals. They use the columns of V to replace the
 
8155
     columns represented by the vector C. If the sparse matrix A is
 
8156
     defined then the diagonals of this matrix are replaced.  Otherwise
 
8157
     a matrix of M by N is created with the diagonals given by V.
 
8158
 
 
8159
     Negative values of C representive diagonals below the main
 
8160
     diagonal, and positive values of C diagonals above the main
 
8161
     diagonal.
 
8162
 
 
8163
     For example
 
8164
 
 
8165
          spdiags (reshape (1:12, 4, 3), [-1 0 1], 5, 4)
 
8166
          =>    5 10  0  0
 
8167
                1  6 11  0
 
8168
                0  2  7 12
 
8169
                0  0  3  8
 
8170
                0  0  0  4
 
8171
 
 
8172
 
 
8173
 -- Function File: Y = speye (M)
 
8174
 -- Function File: Y = speye (M, N)
 
8175
 -- Function File: Y = speye (SZ)
 
8176
     Returns a sparse identity matrix. This is significantly more
 
8177
     efficient than `sparse (eye (M))' as the full matrix is not
 
8178
     constructed.
 
8179
 
 
8180
     Called with a single argument a square matrix of size M by M is
 
8181
     created. Otherwise a matrix of M by N is created. If called with a
 
8182
     single vector argument, this argument is taken to be the size of
 
8183
     the matrix to create.
 
8184
 
 
8185
 -- Function File: Y = spfun (F,X)
 
8186
     Compute `f(X)' for the non-zero values of X.  This results in a
 
8187
     sparse matrix with the same structure as X. The function F can be
 
8188
     passed as a string, a function handle or an inline function.
 
8189
 
 
8190
 -- Mapping Function:  spmax (X, Y, DIM)
 
8191
 -- Mapping Function: [W, IW] = spmax (X)
 
8192
     For a vector argument, return the maximum value.  For a matrix
 
8193
     argument, return the maximum value from each column, as a row
 
8194
     vector, or over the dimension DIM if defined. For two matrices (or
 
8195
     a matrix and scalar), return the pair-wise maximum.  Thus,
 
8196
 
 
8197
          max (max (X))
 
8198
 
 
8199
     returns the largest element of X, and
 
8200
 
 
8201
          max (2:5, pi)
 
8202
              =>  3.1416  3.1416  4.0000  5.0000
 
8203
     compares each element of the range `2:5' with `pi', and returns a
 
8204
     row vector of the maximum values.
 
8205
 
 
8206
     For complex arguments, the magnitude of the elements are used for
 
8207
     comparison.
 
8208
 
 
8209
     If called with one input and two output arguments, `max' also
 
8210
     returns the first index of the maximum value(s). Thus,
 
8211
 
 
8212
          [x, ix] = max ([1, 3, 5, 2, 5])
 
8213
              =>  x = 5
 
8214
                  ix = 3
 
8215
 
 
8216
 -- Mapping Function:  spmin (X, Y, DIM)
 
8217
 -- Mapping Function: [W, IW] = spmin (X)
 
8218
     For a vector argument, return the minimum value.  For a matrix
 
8219
     argument, return the minimum value from each column, as a row
 
8220
     vector, or over the dimension DIM if defined. For two matrices (or
 
8221
     a matrix and scalar), return the pair-wise minimum.  Thus,
 
8222
 
 
8223
          min (min (X))
 
8224
 
 
8225
     returns the smallest element of X, and
 
8226
 
 
8227
          min (2:5, pi)
 
8228
              =>  2.0000  3.0000  3.1416  3.1416
 
8229
     compares each element of the range `2:5' with `pi', and returns a
 
8230
     row vector of the minimum values.
 
8231
 
 
8232
     For complex arguments, the magnitude of the elements are used for
 
8233
     comparison.
 
8234
 
 
8235
     If called with one input and two output arguments, `min' also
 
8236
     returns the first index of the minimum value(s). Thus,
 
8237
 
 
8238
          [x, ix] = min ([1, 3, 0, 2, 5])
 
8239
              =>  x = 0
 
8240
                  ix = 3
 
8241
 
 
8242
 -- Function File: Y = spones (X)
 
8243
     Replace the non-zero entries of X with ones. This creates a sparse
 
8244
     matrix with the same structure as X.
 
8245
 
 
8246
 -- Loadable Function: Y = spprod (X,DIM)
 
8247
     Product of elements along dimension DIM.  If DIM is omitted, it
 
8248
     defaults to 1 (column-wise products).
 
8249
 
 
8250
     *See also:* spsum, spsumsq.
 
8251
 
 
8252
 -- Function File:  sprand (M, N, D)
 
8253
 -- Function File:  sprand (S)
 
8254
     Generate a random sparse matrix. The size of the matrix will be M
 
8255
     by N, with a density of values given by D.  D should be between 0
 
8256
     and 1. Values will be uniformly distributed between 0 and 1.
 
8257
 
 
8258
     Note: sometimes the actual density  may be a bit smaller than D.
 
8259
     This is unlikely to happen for large really sparse matrices.
 
8260
 
 
8261
     If called with a single matrix argument, a random sparse matrix is
 
8262
     generated wherever the matrix S is non-zero.
 
8263
 
 
8264
     *See also:* sprandn.
 
8265
 
 
8266
 -- Function File:  sprandn (M, N, D)
 
8267
 -- Function File:  sprandn (S)
 
8268
     Generate a random sparse matrix. The size of the matrix will be M
 
8269
     by N, with a density of values given by D.  D should be between 0
 
8270
     and 1. Values will be normally distributed with mean of zero and
 
8271
     variance 1.
 
8272
 
 
8273
     Note: sometimes the actual density  may be a bit smaller than D.
 
8274
     This is unlikely to happen for large really sparse matrices.
 
8275
 
 
8276
     If called with a single matrix argument, a random sparse matrix is
 
8277
     generated wherever the matrix S is non-zero.
 
8278
 
 
8279
     *See also:* sprand.
 
8280
 
 
8281
 -- Function File:  sprandsym (N, D)
 
8282
 -- Function File:  sprandsym (S)
 
8283
     Generate a symmetric random sparse matrix. The size of the matrix
 
8284
     will be N by N, with a density of values given by D.  D should be
 
8285
     between 0 and 1. Values will be normally distributed with mean of
 
8286
     zero and variance 1.
 
8287
 
 
8288
     Note: sometimes the actual density  may be a bit smaller than D.
 
8289
     This is unlikely to happen for large really sparse matrices.
 
8290
 
 
8291
     If called with a single matrix argument, a random sparse matrix is
 
8292
     generated wherever the matrix S is non-zero in its lower
 
8293
     triangular part.
 
8294
 
 
8295
     *See also:* sprand, sprandn.
 
8296
 
 
8297
 -- Loadable Function: Y = spsum (X,DIM)
 
8298
     Sum of elements along dimension DIM.  If DIM is omitted, it
 
8299
     defaults to 1 (column-wise sum).
 
8300
 
 
8301
     *See also:* spprod, spsumsq.
 
8302
 
 
8303
 -- Loadable Function: Y = spsumsq (X,DIM)
 
8304
     Sum of squares of elements along dimension DIM.  If DIM is
 
8305
     omitted, it defaults to 1 (column-wise sum of squares).  This
 
8306
     function is equivalent to computing
 
8307
          spsum (x .* spconj (x), dim)
 
8308
     but it uses less memory and avoids calling `spconj' if X is real.
 
8309
 
 
8310
     *See also:* spprod, spsum.
 
8311
 
 
8312
   The recommended way for the user to create a sparse matrix, is to
 
8313
create two vectors containing the row and column index of the data and
 
8314
a third vector of the same size containing the data to be stored. For
 
8315
example
 
8316
 
 
8317
       ri = ci = d = [];
 
8318
       for j = 1:c
 
8319
         ri = [ri; randperm(r)(1:n)'];
 
8320
         ci = [ci; j*ones(n,1)];
 
8321
         d = [d; rand(n,1)];
 
8322
       endfor
 
8323
       s = sparse (ri, ci, d, r, c);
 
8324
 
 
8325
   creates an R-by-C sparse matrix with a random distribution of N (<R)
 
8326
elements per column. The elements of the vectors do not need to be
 
8327
sorted in any particular order as Octave will sort them prior to
 
8328
storing the data. However, pre-sorting the data will make the creation
 
8329
of the sparse matrix faster.
 
8330
 
 
8331
   The function "spconvert" takes a three or four column real matrix.
 
8332
The first two columns represent the row and column index respectively
 
8333
and the third and four columns, the real and imaginary parts of the
 
8334
sparse matrix. The matrix can contain zero elements and the elements
 
8335
can be sorted in any order. Adding zero elements is a convenient way to
 
8336
define the size of the sparse matrix. For example
 
8337
 
 
8338
     s = spconvert ([1 2 3 4; 1 3 4 4; 1 2 3 0]')
 
8339
     => Compressed Column Sparse (rows=4, cols=4, nnz=3)
 
8340
           (1 , 1) -> 1
 
8341
           (2 , 3) -> 2
 
8342
           (3 , 4) -> 3
 
8343
 
 
8344
   An example of creating and filling a matrix might be
 
8345
 
 
8346
     k = 5;
 
8347
     nz = r * k;
 
8348
     s = spalloc (r, c, nz)
 
8349
     for j = 1:c
 
8350
       idx = randperm (r);
 
8351
       s (:, j) = [zeros(r - k, 1); ...
 
8352
             rand(k, 1)] (idx);
 
8353
     endfor
 
8354
 
 
8355
   It should be noted, that due to the way that the Octave assignment
 
8356
functions are written that the assignment will reallocate the memory
 
8357
used by the sparse matrix at each iteration of the above loop.
 
8358
Therefore the "spalloc" function ignores the NZ argument and does not
 
8359
preassign the memory for the matrix. Therefore, it is vitally important
 
8360
that code using to above structure should be vectorized as much as
 
8361
possible to minimize the number of assignments and reduce the number of
 
8362
memory allocations.
 
8363
 
 
8364
 -- Loadable Function: FM = full (SM)
 
8365
     returns a full storage matrix from a sparse one
 
8366
 
 
8367
     *See also:* sparse.
 
8368
 
 
8369
 -- Function File: S = spalloc (R, C, NZ)
 
8370
     Returns an empty sparse matrix of size R-by-C. As Octave resizes
 
8371
     sparse matrices at the first opportunity, so that no additional
 
8372
     space is needed, the argument NZ is ignored. This function is
 
8373
     provided only for compatibility reasons.
 
8374
 
 
8375
     It should be noted that this means that code like
 
8376
 
 
8377
          k = 5;
 
8378
          nz = r * k;
 
8379
          s = spalloc (r, c, nz)
 
8380
          for j = 1:c
 
8381
            idx = randperm (r);
 
8382
            s (:, j) = [zeros(r - k, 1); rand(k, 1)] (idx);
 
8383
          endfor
 
8384
 
 
8385
     will reallocate memory at each step. It is therefore vitally
 
8386
     important that code like this is vectorized as much as possible.
 
8387
 
 
8388
     *See also:* sparse, nzmax.
 
8389
 
 
8390
 -- Loadable Function: S = sparse (A)
 
8391
     Create a sparse matrix from the full matrix A.  is forced back to
 
8392
     a full matrix is resulting matrix is sparse
 
8393
 
 
8394
 -- Loadable Function: S = sparse (I, J, SV, M, N, NZMAX)
 
8395
     Create a sparse matrix given integer index vectors I and J, a
 
8396
     1-by-`nnz' vector of real of complex values SV, overall dimensions
 
8397
     M and N of the sparse matrix.  The argument `nzmax' is ignored but
 
8398
     accepted for compatibility with MATLAB.
 
8399
 
 
8400
     *Note*: if multiple values are specified with the same I, J
 
8401
     indices, the corresponding values in S will be added.
 
8402
 
 
8403
     The following are all equivalent:
 
8404
 
 
8405
          s = sparse (i, j, s, m, n)
 
8406
          s = sparse (i, j, s, m, n, "summation")
 
8407
          s = sparse (i, j, s, m, n, "sum")
 
8408
 
 
8409
 -- Loadable Function: S = sparse (I, J, S, M, N, "unique")
 
8410
     Same as above, except that if more than two values are specified
 
8411
     for the same I, J indices, the last specified value will be used.
 
8412
 
 
8413
 -- Loadable Function: S = sparse (I, J, SV)
 
8414
     Uses `M = max (I)', `N = max (J)'
 
8415
 
 
8416
 -- Loadable Function: S = sparse (M, N)
 
8417
     Equivalent to `sparse ([], [], [], M, N, 0)'
 
8418
 
 
8419
     If any of SV, I or J are scalars, they are expanded to have a
 
8420
     common size.
 
8421
 
 
8422
     *See also:* full.
 
8423
 
 
8424
 -- Function File: X = spconvert (M)
 
8425
     This function converts for a simple sparse matrix format easily
 
8426
     produced by other programs into Octave's internal sparse format.
 
8427
     The input X is either a 3 or 4 column real matrix, containing the
 
8428
     row, column, real and imaginary parts of the elements of the
 
8429
     sparse matrix. An element with a zero real and imaginary part can
 
8430
     be used to force a particular matrix size.
 
8431
 
 
8432
 -- Loadable Function:  spfind (X)
 
8433
 -- Loadable Function:  spfind (X, N)
 
8434
 -- Loadable Function:  spfind (X, N, DIRECTION)
 
8435
 -- Loadable Function: [I, J, V spfind (...)
 
8436
     A sparse version of the `find' function. Please see the `find' for
 
8437
     details of its use.
 
8438
 
 
8439
     Note that this function is particularly useful for sparse
 
8440
     matrices, as it extracts the non-zero elements as vectors, which
 
8441
     can then be used to create the original matrix. For example,
 
8442
 
 
8443
          sz = size(a);
 
8444
          [i, j, v] = spfind (a);
 
8445
          b = sparse(i, j, v, sz(1), sz(2));
 
8446
 
 
8447
 
 
8448
     *See also:* sparse.
 
8449
 
 
8450
   The above problem can be avoided in oct-files. However, the
 
8451
construction of a sparse matrix from an oct-file is more complex than
 
8452
can be discussed in this brief introduction, and you are referred to
 
8453
chapter *note Dynamically Linked Functions::, to have a full
 
8454
description of the techniques involved.
 
8455
 
 
8456
 
 
8457
File: octave.info,  Node: Information,  Next: Operators and Functions,  Prev: Creation,  Up: Basics
 
8458
 
 
8459
20.1.3 Finding out Information about Sparse Matrices
 
8460
----------------------------------------------------
 
8461
 
 
8462
There are a number of functions that allow information concerning
 
8463
sparse matrices to be obtained. The most basic of these is "issparse"
 
8464
that identifies whether a particular Octave object is in fact a sparse
 
8465
matrix.
 
8466
 
 
8467
   Another very basic function is "nnz" that returns the number of
 
8468
non-zero entries there are in a sparse matrix, while the function
 
8469
"nzmax" returns the amount of storage allocated to the sparse matrix.
 
8470
Note that Octave tends to crop unused memory at the first opportunity
 
8471
for sparse objects. There are some cases of user created sparse objects
 
8472
where the value returned by "nzmaz" will not be the same as "nnz", but
 
8473
in general they will give the same result. The function "spstats"
 
8474
returns some basic statistics on the columns of a sparse matrix
 
8475
including the number of elements, the mean and the variance of each
 
8476
column.
 
8477
 
 
8478
 -- Loadable Function:  issparse (EXPR)
 
8479
     Return 1 if the value of the expression EXPR is a sparse matrix.
 
8480
 
 
8481
 -- Built-in Function: SCALAR = nnz (A)
 
8482
     Returns the number of non zero elements in A.
 
8483
 
 
8484
     *See also:* sparse.
 
8485
 
 
8486
 -- Function File:  nonzeros (S)
 
8487
     Returns a vector of the non-zero values of the sparse matrix S.
 
8488
 
 
8489
 -- Built-in Function: SCALAR = nzmax (SM)
 
8490
     Return the amount of storage allocated to the sparse matrix SM.
 
8491
     Note that Octave tends to crop unused memory at the first
 
8492
     opportunity for sparse objects. There are some cases of user
 
8493
     created sparse objects where the value returned by "nzmaz" will
 
8494
     not be the same as "nnz", but in general they will give the same
 
8495
     result.
 
8496
 
 
8497
     *See also:* sparse, spalloc.
 
8498
 
 
8499
 -- Function File: [COUNT, MEAN, VAR] = spstats (S)
 
8500
 -- Function File: [COUNT, MEAN, VAR] = spstats (S, J)
 
8501
     Return the stats for the non-zero elements of the sparse matrix S.
 
8502
     COUNT is the number of non-zeros in each column, MEAN is the mean
 
8503
     of the non-zeros in each column, and VAR is the variance of the
 
8504
     non-zeros in each column.
 
8505
 
 
8506
     Called with two input arguments, if S is the data and J is the bin
 
8507
     number for the data, compute the stats for each bin.  In this
 
8508
     case, bins can contain data values of zero, whereas with `spstats
 
8509
     (S)' the zeros may disappear.
 
8510
 
 
8511
   When solving linear equations involving sparse matrices Octave
 
8512
determines the means to solve the equation based on the type of the
 
8513
matrix as discussed in *note Sparse Linear Algebra::. Octave probes the
 
8514
matrix type when the div (/) or ldiv (\) operator is first used with
 
8515
the matrix and then caches the type. However the "matrix_type" function
 
8516
can be used to determine the type of the sparse matrix prior to use of
 
8517
the div or ldiv operators. For example
 
8518
 
 
8519
     a = tril (sprandn(1024, 1024, 0.02), -1) ...
 
8520
         + speye(1024);
 
8521
     matrix_type (a);
 
8522
     ans = Lower
 
8523
 
 
8524
   show that Octave correctly determines the matrix type for lower
 
8525
triangular matrices. "matrix_type" can also be used to force the type
 
8526
of a matrix to be a particular type. For example
 
8527
 
 
8528
     a = matrix_type (tril (sprandn (1024, ...
 
8529
        1024, 0.02), -1) + speye(1024), 'Lower');
 
8530
 
 
8531
   This allows the cost of determining the matrix type to be avoided.
 
8532
However, incorrectly defining the matrix type will result in incorrect
 
8533
results from solutions of linear equations, and so it is entirely the
 
8534
responsibility of the user to correctly identify the matrix type
 
8535
 
 
8536
   There are several graphical means of finding out information about
 
8537
sparse matrices. The first is the "spy" command, which displays the
 
8538
structure of the non-zero elements of the matrix. *Note fig:spmatrix::,
 
8539
for an example of the use of "spy".  More advanced graphical
 
8540
information can be obtained with the "treeplot", "etreeplot" and
 
8541
"gplot" commands.
 
8542
 
 
8543
[image src="spmatrix.png" text="
 
8544
            |  * *
 
8545
            |  * * * *
 
8546
            |    * *   * *
 
8547
            |    *   *     * *
 
8548
          5 -      *   *       * *
 
8549
            |      *     *         * *
 
8550
            |        *     *           * *
 
8551
            |        *       *             *
 
8552
            |          *       *
 
8553
         10 -          *         *
 
8554
            |            *         *
 
8555
            |            *           *
 
8556
            |              *           *
 
8557
            |              *             *
 
8558
         15 -                *             *
 
8559
            |----------|---------|---------|
 
8560
                       5        10        15"]
 
8561
 
 
8562
Figure 20.1: Structure of simple sparse matrix.
 
8563
 
 
8564
   One use of sparse matrices is in graph theory, where the
 
8565
interconnections between nodes are represented as an adjacency matrix.
 
8566
That is, if the i-th node in a graph is connected to the j-th node.
 
8567
Then the ij-th node (and in the case of undirected graphs the ji-th
 
8568
node) of the sparse adjacency matrix is non-zero. If each node is then
 
8569
associated with a set of co-ordinates, then the "gplot" command can be
 
8570
used to graphically display the interconnections between nodes.
 
8571
 
 
8572
   As a trivial example of the use of "gplot", consider the example
 
8573
 
 
8574
     A = sparse([2,6,1,3,2,4,3,5,4,6,1,5],
 
8575
         [1,1,2,2,3,3,4,4,5,5,6,6],1,6,6);
 
8576
     xy = [0,4,8,6,4,2;5,0,5,7,5,7]';
 
8577
     gplot(A,xy)
 
8578
 
 
8579
   which creates an adjacency matrix `A' where node 1 is connected to
 
8580
nodes 2 and 6, node 2 with nodes 1 and 3, etc. The co-ordinates of the
 
8581
nodes are given in the n-by-2 matrix `xy'.
 
8582
 
 
8583
   The dependencies between the nodes of a Cholesky factorization can be
 
8584
calculated in linear time without explicitly needing to calculate the
 
8585
Cholesky factorization by the `etree' command. This command returns the
 
8586
elimination tree of the matrix and can be displayed graphically by the
 
8587
command `treeplot(etree(A))' if `A' is symmetric or
 
8588
`treeplot(etree(A+A'))' otherwise.
 
8589
 
 
8590
 -- Function File:  spy (X)
 
8591
 -- Function File:  spy (..., MARKERSIZE)
 
8592
 -- Function File:  spy (..., LINESPEC)
 
8593
     Plot the sparsity pattern of the sparse matrix X. If the argument
 
8594
     MARKERSIZE is given as an scalar value, it is used to determine the
 
8595
     point size in the plot. If the string LINESPEC is given it is
 
8596
     passed to `plot' and determines the appearance of the plot.
 
8597
 
 
8598
     *See also:* plot.
 
8599
 
 
8600
 -- Loadable Function: P = etree (S)
 
8601
 -- Loadable Function: P = etree (S, TYP)
 
8602
 -- Loadable Function: [P, Q] = etree (S, TYP)
 
8603
     Returns the elimination tree for the matrix S. By default S is
 
8604
     assumed to be symmetric and the symmetric elimination tree is
 
8605
     returned. The argument TYP controls whether a symmetric or column
 
8606
     elimination tree is returned. Valid values of TYP are 'sym' or
 
8607
     'col', for symmetric or column elimination tree respectively
 
8608
 
 
8609
     Called with a second argument, "etree" also returns the postorder
 
8610
     permutations on the tree.
 
8611
 
 
8612
 -- Function File:  etreeplot (TREE)
 
8613
 -- Function File:  etreeplot (TREE, NODE_STYLE, EDGE_STYLE)
 
8614
     Plot the elimination tree of the matrix S or `S+S''  if S in
 
8615
     non-symmetric.  The optional parameters LINE_STYLE and EDGE_STYLE
 
8616
     define the output style.
 
8617
 
 
8618
     *See also:* treeplot, gplot.
 
8619
 
 
8620
 -- Function File:  gplot (A, XY)
 
8621
 -- Function File:  gplot (A, XY, LINE_STYLE)
 
8622
 -- Function File: [X, Y] = gplot (A, XY)
 
8623
     Plot a graph defined by A and XY in the graph theory sense.  A is
 
8624
     the adjacency matrix of the array to be plotted and XY is an
 
8625
     N-by-2 matrix containing the coordinates of the nodes of the graph.
 
8626
 
 
8627
     The optional parameter LINE_STYLE defines the output style for the
 
8628
     plot.  Called with no output arguments the graph is plotted
 
8629
     directly.  Otherwise, return the coordinates of the plot in X and
 
8630
     Y.
 
8631
 
 
8632
     *See also:* treeplot, etreeplot, spy.
 
8633
 
 
8634
 -- Function File:  treeplot (TREE)
 
8635
 -- Function File:  treeplot (TREE, LINESTYLE, EDGESTYLE)
 
8636
     Produces a graph of tree or forest. The first argument is vector of
 
8637
     predecessors, optional parameters LINESTYLE and EDGESTYLE define
 
8638
     the output style. The complexity of the algorithm is O(n) in terms
 
8639
     of is time and memory requirements.
 
8640
 
 
8641
     *See also:* etreeplot, gplot.
 
8642