1
This is octave.info, produced by makeinfo version 4.11 from ./octave.texi.
4
* Octave: (octave). Interactive language for numerical computations.
7
Copyright (C) 1996, 1997, 1999, 2000, 2001, 2002, 2005, 2006, 2007
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.
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.
19
Permission is granted to copy and distribute translations of this
20
manual into another language, under the above conditions for modified
24
File: octave.info, Node: Organization of Functions, Prev: Commands, Up: Functions and Scripts
26
11.11 Organization of Functions Distributed with Octave
27
=======================================================
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.
33
The following is a list of all the function file subdirectories, and
34
the types of functions you will find there.
37
Functions for playing and recording sounds.
40
Functions for design and simulation of automatic control systems.
46
Functions for computing interest payments, investment values, and
50
Miscellaneous matrix manipulations, like `flipud', `rot90', and
51
`triu', as well as other basic functions, like `ismatrix',
55
Image processing tools. These functions require the X Window
59
Input-ouput functions.
62
Functions for linear algebra.
65
Functions that don't really belong anywhere else.
68
Minimization of functions.
71
Functions to manage the directory path Octave uses to find
75
Install external packages of functions in Octave.
78
Functions for displaying and printing two- and three-dimensional
82
Functions for manipulating polynomials.
85
Functions for creating and manipulating sets of unique values.
88
Functions for signal processing applications.
91
Functions for handling sparse matrices.
97
Functions that create special matrix forms.
100
Octave's system-wide startup file.
103
Statistical functions.
106
Miscellaneous string-handling functions.
109
Perform unit tests on other functions.
112
Functions related to time keeping.
115
File: octave.info, Node: Errors and Warnings, Next: Debugging, Prev: Functions and Scripts, Up: Top
117
12 Errors and Warnings
118
**********************
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.
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.
131
* Handling Warnings::
134
File: octave.info, Node: Handling Errors, Next: Handling Warnings, Up: Errors and Warnings
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
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::.
156
File: octave.info, Node: Raising Errors, Next: Catching Errors, Up: Handling Errors
158
12.1.1 Raising Errors
159
---------------------
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.
167
error("not enough input arguments");
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.
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: '.
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.
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:
191
function f () g (); end
192
function g () h (); end
193
function h () nargin == 1 || error ("nargin != 1"); end
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:
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'
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:
212
function h () nargin == 1 || error ("nargin != 1\n"); end
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.
225
Consider the following function.
227
## @deftypefn {Function File} f (@var{arg1})
228
## Function help text goes here...
236
When it is called with no input arguments it produces the following
240
-| Invalid call to f. Correct usage is:
242
-| -- Function File: f (ARG1)
246
-| error: evaluating if command near line 6, column 3
247
-| error: called from `f' in file `/home/jwe/octave/f.m'
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.
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.
262
After `usage' is evaluated, Octave will print a traceback of all
263
the function calls leading to the usage message.
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
272
usage ("foo (a, b)");
275
to check for the proper number of arguments.
277
-- Function File: beep ()
278
Produce a beep from the speaker (or visual bell).
280
*See also:* puts, fputs, printf, fprintf.
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
289
File: octave.info, Node: Catching Errors, Prev: Raising Errors, Up: Handling Errors
291
12.1.2 Catching Errors
292
----------------------
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
299
number_of_errors = 0;
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.
315
number_of_errors = 0;
320
msg = lasterror.message;
321
if (strfind (msg, "operator *"))
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:
335
The text of the last error message
338
The message identifier of this error message
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:
347
The name of the file where the error occurred
350
The name of function in which the error occurred
353
The line number at which the error occurred
356
An optional field with the column number at which the
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.
365
If `lasterror' is called with the argument 'reset', all values take
366
their default values.
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.
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
380
number_of_errors = 0;
385
msg = lasterror.message;
386
if (strfind (msg, "operator *"))
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
401
*See also:* lasterror, lasterr, error.
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
411
-- Built-in Function: errno_list ()
412
Return a structure containing the system-dependent errno values.
415
File: octave.info, Node: Handling Warnings, Prev: Handling Errors, Up: Errors and Warnings
417
12.2 Handling Warnings
418
======================
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
427
-| warning: division by zero
433
* Enabling and Disabling Warnings::
436
File: octave.info, Node: Issuing Warnings, Next: Enabling and Disabling Warnings, Up: Handling Warnings
438
12.2.1 Issuing Warnings
439
-----------------------
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.
449
warning ("'a' must be non-negative. Setting 'a' to zero.");
452
-| 'a' must be non-negative. Setting 'a' to zero.
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
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.
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.
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.
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.
488
*See also:* warning_ids.
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.
496
File: octave.info, Node: Enabling and Disabling Warnings, Prev: Issuing Warnings, Up: Handling Warnings
498
12.2.2 Enabling and Disabling Warnings
499
--------------------------------------
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.
506
It is also possible to enable and disable individual warnings through
507
their string identifications. The following code will issue a warning
509
warning ("non-negative-variable",
510
"'a' must be non-negative. Setting 'a' to zero.");
512
while the following won't issue a warning
514
warning ("off", "non-negative-variable");
515
warning ("non-negative-variable",
516
"'a' must be non-negative. Setting 'a' to zero.");
518
The functions distributed with Octave can issue one of the following
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
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
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
540
since such statements are not common, and it is likely that the
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
555
are common in C programming.
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
561
if (x = 1) # intended to test (x == 1)!
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
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.
577
By default, the `Octave:assign-as-truth-value' warning is enabled.
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.
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.
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
596
a = [1, [], 3, [], 5]
598
By default, the `Octave:empty-list-elements' warning is enabled.
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.
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.
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'
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
625
`Octave:matlab-incompatible'
626
Print warnings for Octave language features that may cause
627
compatibility problems with MATLAB.
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
635
`Octave:neg-dim-as-zero'
636
If the `Octave:neg-dim-as-zero' warning is enabled, print a warning
641
By default, the `Octave:neg-dim-as-zero' warning is disabled.
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,
651
elicits a warning if the `Octave:num-to-str' warning is enabled.
652
By default, the `Octave:num-to-str' warning is enabled.
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.
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.
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.
675
`Octave:separator-insert'
676
Print warning if commas or semicolons might be inserted
677
automatically in literal matrices.
679
`Octave:single-quote-string'
680
Print warning if a signle quote character is used to introduce a
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,
689
elicits a warning if the `Octave:str-to-num' warning is enabled.
690
By default, the `Octave:str-to-num' warning is disabled.
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.
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.
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.
710
File: octave.info, Node: Debugging, Next: Input and Output, Prev: Errors and Warnings, Up: Top
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
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
728
debug> for i = 1:n, foo(i); endfor
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'.
736
* Entering Debug Mode::
741
File: octave.info, Node: Entering Debug Mode, Next: Breakpoints, Up: Debugging
743
13.1 Entering Debug Mode
744
========================
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.
750
Octave supports three means to stop execution based on the values
751
set in the functions `debug_on_interrupt', `debug_on_warning' and
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.
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.
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).
775
File: octave.info, Node: Breakpoints, Next: Debug Mode, Prev: Entering Debug Mode, Up: Debugging
780
Breakpoints can be set in any Octave function, using the `dbstop'
783
-- Loadable Function: rline = dbstop (FUNC, LINE, ...)
784
Set a breakpoint in a function
786
String representing the function name. When already in debug
787
mode this should be left out and only the line should be
791
Line you would like the breakpoint to be set on. Multiple
792
lines might be given as separate arguments or as a vector.
794
The rline returned is the real line that the breakpoint was set at.
796
*See also:* dbclear, dbstatus, dbnext.
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
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.
812
-- Loadable Function: lst = dbstatus (FUNC)
813
Return a vector containing the lines on which a function has
816
String representing the function name. When already in debug
817
mode this should be left out.
820
*See also:* dbclear, dbwhere.
822
Taking the above as an example, `dbstatus ("asind")' should return 27.
823
The breakpoints can then be cleared with the `dbclear' function
825
-- Loadable Function: dbclear (FUNC, LINE, ...)
826
Delete a breakpoint in a function
828
String representing the function name. When already in debug
829
mode this should be left out and only the line should be
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.
838
*See also:* dbstop, dbstatus, dbwhere.
840
To clear all of the breakpoints in a function the recommended means,
841
following the above example, is then
843
dbclear ("asind", dbstatus ("asind"));
845
Another simple means of setting a breakpoint in an Octave script is
846
the use of the `keyboard' function.
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
858
If `keyboard' is invoked without any arguments, a default prompt of
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.
866
File: octave.info, Node: Debug Mode, Prev: Breakpoints, Up: Debugging
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.
876
-- Loadable Function: dbwhere ()
877
Show where we are in the code
879
*See also:* dbclear, dbstatus, dbstop.
881
-- Loadable Function: dbtype ()
882
List script file with line numbers.
884
*See also:* dbclear, dbstatus, dbstop.
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.
894
File: octave.info, Node: Input and Output, Next: Plotting, Prev: Debugging, Up: Top
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.
907
* Basic Input and Output::
908
* C-Style I/O Functions::
911
File: octave.info, Node: Basic Input and Output, Next: C-Style I/O Functions, Up: Input and Output
913
14.1 Basic Input and Output
914
===========================
921
* Rational Approximations::
924
File: octave.info, Node: Terminal Output, Next: Terminal Input, Up: Basic Input and Output
926
14.1.1 Terminal Output
927
----------------------
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
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'.
941
The `format' command offers some control over the way Octave prints
942
values with `disp' and through the normal echoing mechanism.
944
-- Automatic Variable: ans
945
The most recently computed result that was not explicitly assigned
946
to a variable. For example, after the expression
950
is evaluated, the value returned by `ans' is 25.
952
-- Built-in Function: disp (X)
953
Display the value of X. For example,
955
disp ("The value of pi is:"), disp (pi)
957
-| the value of pi is:
960
Note that the output from `disp' always ends with a newline.
962
If an output value is requested, `disp' prints nothing and returns
963
the formatted output in a string.
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
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).
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.
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).
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.
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'.
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'.
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]'
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
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'.
1043
Print in a fixed format with two places to the right of the
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.
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
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
1073
The same as `native-hex', but always print the most
1074
significant byte first.
1077
Print the bit representation of numbers as stored in memory.
1078
For example, the value of `pi' is
1080
01000000000010010010000111111011
1081
01010100010001000010110100011000
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.
1089
The same as `native-bit', but always print the most
1090
significant bits first.
1093
Remove extra blank space around column number labels.
1096
Insert blank lines above and below column number labels (this
1100
Print a rational approximation. That is the values are
1101
approximated by one small integer divided by another.
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
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.
1111
If `format' is invoked without any options, the default format
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
1122
* Paging Screen Output::
1125
File: octave.info, Node: Paging Screen Output, Up: Terminal Output
1127
14.1.1.1 Paging Screen Output
1128
.............................
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.
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.
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'.
1151
-- Command: more off
1152
Turn output pagination on or off. Without an argument, `more'
1153
toggles the current state.
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::.
1162
*See also:* more, page_screen_output, page_output_immediately,
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
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.
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.
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'.
1193
`fflush' returns 0 on success and an OS dependent error value (-1
1196
*See also:* fopen, fclose.
1199
File: octave.info, Node: Terminal Input, Next: Simple File I/O, Prev: Terminal Output, Up: Basic Input and Output
1201
14.1.2 Terminal Input
1202
---------------------
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.
1209
-- Built-in Function: input (PROMPT)
1210
-- Built-in Function: input (PROMPT, "s")
1211
Print a prompt and wait for user input. For example,
1213
input ("Pick a number, any number! ")
1217
Pick a number, any number!
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.
1223
Currently, `input' only returns one value, regardless of the number
1224
of values produced by the evaluation of the expression.
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.
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::.
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.
1244
*See also:* disp, printf, input.
1246
For `input', the normal command line history and editing functions
1247
are available at the prompt.
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
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,
1259
will set X to the next character typed at the keyboard as soon as
1264
identical to the above example, but don't wait for a keypress,
1265
returning the empty string if no key is available.
1268
File: octave.info, Node: Simple File I/O, Next: Rational Approximations, Prev: Terminal Input, Up: Basic Input and Output
1270
14.1.3 Simple File I/O
1271
----------------------
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'.
1278
As an example the following code creates a 3-by-3 matrix and saves it
1279
to the file `myfile.mat'.
1281
A = [ 1:3; 4:6; 7:9 ];
1284
Once one or more variables have been saved to a file, they can be
1285
read into memory using the `load' command.
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'.
1304
If save is invoked using the functional form
1306
save ("-option1", ..., "file", "v1", ...)
1308
then the OPTIONS, FILE, and variable name arguments (V1, ...) must
1309
be specified as character strings.
1312
Save a single matrix in a text file.
1315
Save the data in Octave's binary data format.
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
1327
Save the data in MATLAB's v7 binary data format.
1334
Save the data in MATLAB's v6 binary data format.
1340
Save the data in the binary format written by MATLAB version
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.)
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.
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.
1360
The list of variables to save may include wildcard patterns
1361
containing the following special characters:
1363
Match any single character.
1366
Match zero or more characters.
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.
1375
Save the data in Octave's text data format.
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.
1384
save -binary data a b*
1386
saves the variable `a' and all variables beginning with `b' to the
1387
file `data' in Octave's binary format.
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
1397
If load is invoked using the functional form
1399
load ("-option1", ..., "file", "v1", ...)
1401
then the OPTIONS, FILE, and variable name arguments (V1, ...) must
1402
be specified as character strings.
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.
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.
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).
1425
Valid options for `load' are listed in the following table.
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.
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.
1439
Force Octave to assume the file is in Octave's binary format.
1447
Force Octave to assume the file is in MATLAB's version 6 or 7
1454
Force Octave to assume the file is in the binary format
1455
written by MATLAB version 4.
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
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.
1472
Force Octave to assume the file is in Octave's text format.
1474
There are three functions that modify the behavior of `save'.
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
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.
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
1501
"# Created by Octave VERSION, %a %b %d %H:%M:%S %Y %Z <USER@HOST>"
1504
*See also:* strftime.
1506
-- Built-in Function: native_float_format ()
1507
Return the native floating point format as a string
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'.
1514
fid = fopen ("myfile.txt", "w");
1515
fdisp (fid, "3/8 is ");
1519
*Note Opening and Closing Files::, for details on how to use `fopen'
1522
-- Built-in Function: fdisp (FID, X)
1523
Display the value of X on the stream FID. For example,
1525
fdisp (stdout, "The value of pi is:"), fdisp (stdout, pi)
1527
-| the value of pi is:
1530
Note that the output from `fdisp' always ends with a newline.
1536
* Saving Data on Unexpected Exits::
1539
File: octave.info, Node: Saving Data on Unexpected Exits, Up: Simple File I/O
1541
14.1.3.1 Saving Data on Unexpected Exits
1542
........................................
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.
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.
1556
*See also:* octave_core_file_limit, octave_core_file_name,
1557
octave_core_file_options.
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.
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.
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
1579
*See also:* crash_dumps_octave_core, octave_core_file_name,
1580
octave_core_file_limit.
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)
1593
*See also:* crash_dumps_octave_core, octave_core_file_name,
1594
octave_core_file_options.
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"'
1602
*See also:* crash_dumps_octave_core, octave_core_file_name,
1603
octave_core_file_options.
1606
File: octave.info, Node: Rational Approximations, Prev: Simple File I/O, Up: Basic Input and Output
1608
14.1.4 Rational Approximations
1609
------------------------------
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,
1616
rat(pi) = 3 + 1/(7 + 1/16) = 355/113
1617
rat(e) = 3 + 1/(-4 + 1/(2 + 1/(5 + 1/(-2 + 1/(-7)))))
1620
Called with two arguments returns the numerator and denominator
1621
separately as two matrices.
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:
1633
The optional second argument defines the maximum length of the
1634
string representing the elements of X. By default LEN is 9.
1636
*See also:* format, rat.
1639
File: octave.info, Node: C-Style I/O Functions, Prev: Basic Input and Output, Up: Input and Output
1641
14.2 C-Style I/O Functions
1642
==========================
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.
1649
In the following, FILE refers to a file name and `fid' refers to an
1650
integer file number, as returned by `fopen'.
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.
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.
1662
*See also:* stdout, stderr.
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
1669
*See also:* stdin, stderr.
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.
1676
*See also:* stdin, stdout.
1680
* Opening and Closing Files::
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::
1691
* Input Conversion Syntax::
1692
* Table of Input Conversions::
1693
* Numeric Input Conversions::
1694
* String Input Conversions::
1698
* File Positioning::
1701
File: octave.info, Node: Opening and Closing Files, Next: Simple Output, Up: C-Style I/O Functions
1703
14.2.1 Opening and Closing Files
1704
--------------------------------
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.
1714
filename = "myfile.txt";
1715
fid = fopen (filename, "w");
1716
# Do the actual I/O here...
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.
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.
1735
The third form of the `fopen' function returns information about
1736
the open file given its file id.
1740
myfile = fopen ("splat.dat", "r", "ieee-le");
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.
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.
1752
The possible values `mode' may have are
1755
Open a file for reading.
1758
Open a file for writing. The previous contents are discarded.
1761
Open or create a file for writing at the end of the file.
1764
Open an existing file for reading and writing.
1767
Open a file for reading or writing. The previous contents are
1771
Open or create a file for reading or writing at the end of the
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.
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.
1785
The parameter ARCH is a string specifying the default data format
1786
for the file. Valid values for ARCH are:
1788
`native' The format of the current machine (this is the
1791
`ieee-be' IEEE big endian format.
1793
`ieee-le' IEEE little endian format.
1795
`vaxd' VAX D floating format.
1797
`vaxg' VAX G floating format.
1799
`cray' Cray floating format.
1801
however, conversions are currently only supported for `native'
1802
`ieee-be', and `ieee-le' formats.
1804
*See also:* fclose, fread, fseek.
1806
-- Built-in Function: fclose (FID)
1807
Closes the specified file. If successful, `fclose' returns 0,
1808
otherwise, it returns -1.
1810
*See also:* fopen, fseek, ftell.
1813
File: octave.info, Node: Simple Output, Next: Line-Oriented Input, Prev: Opening and Closing Files, Up: C-Style I/O Functions
1815
14.2.2 Simple Output
1816
--------------------
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
1823
filename = "free.txt";
1824
fid = fopen (filename, "w");
1825
fputs (fid, "Free Software is needed for Free Science");
1828
-- Built-in Function: fputs (FID, STRING)
1829
Write a string to a file with no formatting.
1831
Return a non-negative number on success and EOF on error.
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.
1837
-- Built-in Function: puts (STRING)
1838
Write a string to the standard output with no formatting.
1840
Return a non-negative number on success and EOF on error.
1843
File: octave.info, Node: Line-Oriented Input, Next: Formatted Output, Prev: Simple Output, Up: C-Style I/O Functions
1845
14.2.3 Line-Oriented Input
1846
--------------------------
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
1852
fid = fopen ("free.txt");
1854
-| Free Software is needed for Free Science
1857
This of course assumes that the file `free.txt' exists and contains the
1858
line `Free Software is needed for Free Science'.
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.
1865
If LEN is omitted, `fgetl' reads until the next newline character.
1867
If there are no more characters to read, `fgetl' returns -1.
1869
*See also:* fread, fscanf.
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.
1876
If LEN is omitted, `fgets' reads until the next newline character.
1878
If there are no more characters to read, `fgets' returns -1.
1880
*See also:* fread, fscanf.
1883
File: octave.info, Node: Formatted Output, Next: Output Conversion for Matrices, Prev: Line-Oriented Input, Up: C-Style I/O Functions
1885
14.2.4 Formatted Output
1886
-----------------------
1888
This section describes how to call `printf' and related functions.
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.
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
1900
*See also:* fprintf, sprintf, scanf.
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'.
1906
*See also:* printf, sprintf, fread, fscanf, fopen, fclose.
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.
1915
*See also:* printf, fprintf, sscanf.
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.
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,
1928
filename = "foo.txt";
1929
printf ("Processed %d%% of `%s'.\nPlease be patient.\n",
1932
produces output like
1934
Processed 37% of `foo.txt'.
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.
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').
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
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.
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.
1964
File: octave.info, Node: Output Conversion for Matrices, Next: Output Conversion Syntax, Prev: Formatted Output, Up: C-Style I/O Functions
1966
14.2.5 Output Conversion for Matrices
1967
-------------------------------------
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,
1973
printf ("%4.2f %10.2e %8.4g\n", hilb (3));
1975
-| 1.00 5.00e-01 0.3333
1976
-| 0.50 3.33e-01 0.25
1977
-| 0.33 2.50e-01 0.2
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,
1985
printf ("%4.2f %10.2e %8.4g\n", [1, 2], [3, 4]);
1990
If this is not what you want, use a series of calls instead of just
1994
File: octave.info, Node: Output Conversion Syntax, Next: Table of Output Conversions, Prev: Output Conversion for Matrices, Up: C-Style I/O Functions
1996
14.2.6 Output Conversion Syntax
1997
-------------------------------
1999
This section provides details about the precise syntax of conversion
2000
specifications that can appear in a `printf' template string.
2002
Characters in the template string that are not part of a conversion
2003
specification are printed as-is to the output stream.
2005
The conversion specifications in a `printf' template string have the
2008
% FLAGS WIDTH [ . PRECISION ] TYPE CONVERSION
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.)
2017
In more detail, output conversion specifications consist of an
2018
initial `%' character followed in sequence by:
2020
* Zero or more "flag characters" that modify the normal behavior of
2021
the conversion specification.
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.
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
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).
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.
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'.
2051
* A character that specifies the conversion to be applied.
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.
2059
File: octave.info, Node: Table of Output Conversions, Next: Integer Conversions, Prev: Output Conversion Syntax, Up: C-Style I/O Functions
2061
14.2.7 Table of Output Conversions
2062
----------------------------------
2064
Here is a table summarizing what all the different conversions do:
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::).
2073
Print an integer as an unsigned octal number. *Note Integer
2074
Conversions::, for details.
2077
Print an integer as an unsigned decimal number. *Note Integer
2078
Conversions::, for details.
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.
2086
Print a floating-point number in normal (fixed-point) notation.
2087
*Note Floating-Point Conversions::, for details.
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.
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.
2101
Print a single character. *Note Other Output Conversions::.
2104
Print a string. *Note Other Output Conversions::.
2107
Print a literal `%' character. *Note Other Output Conversions::.
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.
2118
File: octave.info, Node: Integer Conversions, Next: Floating-Point Conversions, Prev: Table of Output Conversions, Up: C-Style I/O Functions
2120
14.2.8 Integer Conversions
2121
--------------------------
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.
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
2134
The following flags are meaningful:
2137
Left-justify the result in the field (instead of the normal
2138
right-justification).
2141
For the signed `%d' and `%i' conversions, print a plus sign if the
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.
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'
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.
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.
2169
File: octave.info, Node: Floating-Point Conversions, Next: Other Output Conversions, Prev: Integer Conversions, Up: C-Style I/O Functions
2171
14.2.9 Floating-Point Conversions
2172
---------------------------------
2174
This section discusses the conversion specifications for floating-point
2175
numbers: the `%f', `%e', `%E', `%g', and `%G' conversions.
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.
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'
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
2195
The following flags can be used to modify the behavior:
2198
Left-justify the result in the field. Normally the result is
2202
Always include a plus or minus sign in the result.
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.
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.
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
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.
2233
File: octave.info, Node: Other Output Conversions, Next: Formatted Input, Prev: Floating-Point Conversions, Up: C-Style I/O Functions
2235
14.2.10 Other Output Conversions
2236
--------------------------------
2238
This section describes miscellaneous conversions for `printf'.
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:
2244
printf ("%c%c%c%c%c", "h", "e", "l", "l", "o");
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:
2256
printf ("%3s%-6s", "no", "where");
2258
prints ` nowhere ' (note the leading and trailing spaces).
2261
File: octave.info, Node: Formatted Input, Next: Input Conversion Syntax, Prev: Other Output Conversions, Up: C-Style I/O Functions
2263
14.2.11 Formatted Input
2264
-----------------------
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
2271
-- Built-in Function: [VAL, COUNT] = fscanf (FID, TEMPLATE, SIZE)
2272
-- Built-in Function: [V1, V2, ..., COUNT] = fscanf (FID, TEMPLATE,
2274
In the first form, read from FID according to TEMPLATE, returning
2275
the result in the matrix VAL.
2277
The optional argument SIZE specifies the amount of data to read
2281
Read as much as possible, returning a column vector.
2284
Read up to NR elements, returning a column vector.
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.
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.
2296
If SIZE is omitted, a value of `Inf' is assumed.
2298
A string is returned if TEMPLATE specifies only character
2301
The number of items successfully read is returned in COUNT.
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
2309
*See also:* scanf, sscanf, fread, fprintf.
2311
-- Built-in Function: [VAL, COUNT] = sscanf (STRING, TEMPLATE, SIZE)
2312
-- Built-in Function: [V1, V2, ..., COUNT] = sscanf (STRING,
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.
2318
*See also:* fscanf, scanf, sprintf.
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.
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.
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.
2344
File: octave.info, Node: Input Conversion Syntax, Next: Table of Input Conversions, Prev: Formatted Input, Up: C-Style I/O Functions
2346
14.2.12 Input Conversion Syntax
2347
-------------------------------
2349
A `scanf' template string is a string that contains ordinary multibyte
2350
characters interspersed with conversion specifications that start with
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.
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.
2364
The conversion specifications in a `scanf' template string have the
2367
% FLAGS WIDTH TYPE CONVERSION
2369
In more detail, an input conversion specification consists of an
2370
initial `%' character followed in sequence by:
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.
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.
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'.
2391
* A character that specifies the conversion to be applied.
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.
2399
File: octave.info, Node: Table of Input Conversions, Next: Numeric Input Conversions, Prev: Input Conversion Syntax, Up: C-Style I/O Functions
2401
14.2.13 Table of Input Conversions
2402
----------------------------------
2404
Here is a table that summarizes the various conversion specifications:
2407
Matches an optionally signed integer written in decimal. *Note
2408
Numeric Input Conversions::.
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::.
2416
Matches an unsigned integer written in octal radix. *Note Numeric
2417
Input Conversions::.
2420
Matches an unsigned integer written in decimal radix. *Note
2421
Numeric Input Conversions::.
2424
Matches an unsigned integer written in hexadecimal radix. *Note
2425
Numeric Input Conversions::.
2427
`%e', `%f', `%g', `%E', `%G'
2428
Matches an optionally signed floating-point number. *Note Numeric
2429
Input Conversions::.
2432
Matches a string containing only non-whitespace characters. *Note
2433
String Input Conversions::.
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::.
2441
This matches a literal `%' character in the input stream. No
2442
corresponding argument is used.
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.
2452
File: octave.info, Node: Numeric Input Conversions, Next: String Input Conversions, Prev: Table of Input Conversions, Up: C-Style I/O Functions
2454
14.2.14 Numeric Input Conversions
2455
---------------------------------
2457
This section describes the `scanf' conversions for reading numeric
2460
The `%d' conversion matches an optionally signed integer in decimal
2463
The `%i' conversion matches an optionally signed integer in any of
2464
the formats that the C language defines for specifying an integer
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'.
2471
The `%o', `%u', and `%x' conversions match unsigned integers in
2472
octal, decimal, and hexadecimal radices, respectively.
2474
The `%X' conversion is identical to the `%x' conversion. They both
2475
permit either uppercase or lowercase letters to be used as digits.
2477
Unlike the C language `scanf', Octave ignores the `h', `l', and `L'
2481
File: octave.info, Node: String Input Conversions, Next: Binary I/O, Prev: Numeric Input Conversions, Up: C-Style I/O Functions
2483
14.2.15 String Input Conversions
2484
--------------------------------
2486
This section describes the `scanf' input conversions for reading string
2487
and character values: `%s' and `%c'.
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.
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.
2499
For example, reading the input:
2503
with the conversion `%10c' produces `" hello, wo"', but reading the
2504
same input with the conversion `%10s' produces `"hello,"'.
2507
File: octave.info, Node: Binary I/O, Next: Temporary Files, Prev: String Input Conversions, Up: C-Style I/O Functions
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
2518
-- Built-in Function: [VAL, COUNT] = fread (FID, SIZE, PRECISION,
2520
Read binary data of type PRECISION from the specified file ID FID.
2522
The optional argument SIZE specifies the amount of data to read
2526
Read as much as possible, returning a column vector.
2529
Read up to NR elements, returning a column vector.
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.
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.
2541
If SIZE is omitted, a value of `Inf' is assumed.
2543
The optional argument PRECISION is a string specifying the type of
2544
data to read and may be one of
2556
8-bit signed integer.
2560
16-bit signed integer.
2564
32-bit signed integer.
2568
64-bit signed integer.
2571
8-bit unsigned integer.
2574
16-bit unsigned integer.
2577
32-bit unsigned integer.
2580
64-bit unsigned integer.
2585
32-bit floating point number.
2590
64-bit floating point number.
2597
Short integer (size is platform dependent).
2600
Integer (size is platform dependent).
2603
Long integer (size is platform dependent).
2607
Unsigned short integer (size is platform dependent).
2611
Unsigned integer (size is platform dependent).
2615
Unsigned long integer (size is platform dependent).
2618
Single precision floating point number (size is platform
2621
The default precision is `"uchar"'.
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.
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'.
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
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,
2645
fread (f, 10, "3*single=>single", 8)
2647
will omit the final 8-byte skip because the last read will not be
2648
a complete block of 3 values.
2650
The optional argument ARCH is a string specifying the data format
2651
for the file. Valid values are
2654
The format of the current machine.
2663
VAX D floating format.
2666
VAX G floating format.
2669
Cray floating format.
2671
Conversions are currently only supported for `"ieee-be"' and
2672
`"ieee-le"' formats.
2674
The data read from the file is returned in VAL, and the number of
2675
values read is returned in `count'
2677
*See also:* fwrite, fopen, fclose.
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
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.
2687
The remaining arguments PRECISION, SKIP, and ARCH are optional,
2688
and are interpreted as described for `fread'.
2690
The behavior of `fwrite' is undefined if the values in DATA are
2691
too large to fit in the specified precision.
2693
*See also:* fread, fopen, fclose.
2696
File: octave.info, Node: Temporary Files, Next: EOF and Errors, Prev: Binary I/O, Up: C-Style I/O Functions
2698
14.2.17 Temporary Files
2699
-----------------------
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.
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.
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.
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.
2723
*See also:* tmpfile, tmpnam, P_tmpdir.
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
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
2735
*See also:* tmpnam, mkstemp, P_tmpdir.
2737
-- Built-in Function: tmpnam (DIR, PREFIX)
2738
Return a unique temporary file name as a string.
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.
2747
*See also:* tmpfile, mkstemp, P_tmpdir.
2750
File: octave.info, Node: EOF and Errors, Next: File Positioning, Prev: Temporary Files, Up: C-Style I/O Functions
2752
14.2.18 End of File and Errors
2753
------------------------------
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.
2761
filename = "myfile.txt";
2762
fid = fopen (filename, "r");
2763
while (! feof (fid) )
2764
text_line = fgetl (fid);
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
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.
2779
*See also:* fread, fopen, fclose.
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.
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,
2801
File: octave.info, Node: File Positioning, Prev: EOF and Errors, Up: C-Style I/O Functions
2803
14.2.19 File Positioning
2804
------------------------
2806
Three functions are available for setting and determining the position
2807
of the file pointer for a given file.
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.
2813
*See also:* fseek, fopen, fclose.
2815
-- Built-in Function: fseek (FID, OFFSET, ORIGIN)
2816
Set the file pointer to any location within the file FID.
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').
2825
Return 0 on success and -1 on error.
2827
*See also:* ftell, fopen, fclose.
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:
2835
Position file relative to the beginning.
2838
Position file relative to the current position.
2841
Position file relative to the end.
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)'.
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.
2852
marker = ftell (myfile);
2854
fourch = fgets (myfile, 4);
2855
fseek (myfile, marker, SEEK_SET);
2858
File: octave.info, Node: Plotting, Next: Matrix Manipulation, Prev: Input and Output, Up: Top
2866
* Advanced Plotting::
2869
File: octave.info, Node: Plotting Basics, Next: Advanced Plotting, Up: Plotting
2871
15.1 Plotting Basics
2872
====================
2874
Octave makes it easy to create many different types of two- and
2875
three-dimensional plots using a few high-level functions.
2877
If you need finer control over graphics, see *note Advanced
2882
* Two-Dimensional Plots::
2883
* Three-Dimensional Plotting::
2884
* Plot Annotations::
2885
* Multiple Plots on One Page::
2886
* Multiple Plot Windows::
2888
* Test Plotting Functions::
2891
File: octave.info, Node: Two-Dimensional Plots, Next: Three-Dimensional Plotting, Up: Plotting Basics
2893
15.1.1 Two-Dimensional Plots
2894
----------------------------
2896
The `plot' function allows you to create simple x-y plots with linear
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.