• Non ci sono risultati.

GNU Octave A high-level interactive language for numerical computations Edition 3 for Octave version 3.8.0 February 2011

N/A
N/A
Protected

Academic year: 2021

Condividi "GNU Octave A high-level interactive language for numerical computations Edition 3 for Octave version 3.8.0 February 2011"

Copied!
900
0
0

Testo completo

(1)

GNU Octave

A high-level interactive language for numerical computations Edition 3 for Octave version 3.8.0 February 2011

Free Your Numbers

John W. Eaton

David Bateman

Søren Hauberg

Rik Wehbring

(2)

Copyright c 1996, 1997, 1999, 2000, 2001, 2002, 2005, 2006, 2007, 2011, 2013 John W.

Eaton.

This is the third edition of the Octave documentation, and is consistent with version 3.8.0 of Octave.

Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.

Permission is granted to copy and distribute modified versions of this manual under the con- ditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.

Permission is granted to copy and distribute translations of this manual into another lan- guage, under the same conditions as for modified versions.

Portions of this document have been adapted from the gawk, readline, gcc, and C library

manuals, published by the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,

Boston, MA 02110-1301–1307, USA.

(3)

i

Table of Contents

Preface . . . . 1

Acknowledgements . . . . 1

Citing Octave in Publications . . . . 4

How You Can Contribute to Octave . . . . 5

Distribution . . . . 5

1 A Brief Introduction to Octave . . . . 7

1.1 Running Octave . . . . 7

1.2 Simple Examples . . . . 7

1.2.1 Elementary Calculations. . . . 7

1.2.2 Creating a Matrix . . . . 8

1.2.3 Matrix Arithmetic . . . . 8

1.2.4 Solving Systems of Linear Equations . . . . 8

1.2.5 Integrating Differential Equations . . . . 9

1.2.6 Producing Graphical Output . . . . 10

1.2.7 Editing What You Have Typed . . . . 10

1.2.8 Help and Documentation . . . . 10

1.3 Conventions . . . . 11

1.3.1 Fonts . . . . 11

1.3.2 Evaluation Notation . . . . 11

1.3.3 Printing Notation . . . . 12

1.3.4 Error Messages . . . . 12

1.3.5 Format of Descriptions . . . . 12

1.3.5.1 A Sample Function Description . . . . 12

1.3.5.2 A Sample Command Description . . . . 13

2 Getting Started . . . . 15

2.1 Invoking Octave from the Command Line . . . . 15

2.1.1 Command Line Options . . . . 15

2.1.2 Startup Files . . . . 19

2.2 Quitting Octave . . . . 19

2.3 Commands for Getting Help . . . . 20

2.4 Command Line Editing . . . . 24

2.4.1 Cursor Motion . . . . 25

2.4.2 Killing and Yanking . . . . 26

2.4.3 Commands For Changing Text . . . . 26

2.4.4 Letting Readline Type For You . . . . 27

2.4.5 Commands For Manipulating The History . . . . 27

2.4.6 Customizing readline . . . . 31

2.4.7 Customizing the Prompt . . . . 31

2.4.8 Diary and Echo Commands . . . . 33

2.5 How Octave Reports Errors . . . . 34

(4)

ii GNU Octave

2.6 Executable Octave Programs . . . . 35

2.7 Comments in Octave Programs . . . . 36

2.7.1 Single Line Comments . . . . 36

2.7.2 Block Comments . . . . 36

2.7.3 Comments and the Help System . . . . 37

3 Data Types . . . . 39

3.1 Built-in Data Types. . . . 39

3.1.1 Numeric Objects . . . . 41

3.1.2 Missing Data. . . . 42

3.1.3 String Objects . . . . 42

3.1.4 Data Structure Objects . . . . 42

3.1.5 Cell Array Objects . . . . 43

3.2 User-defined Data Types . . . . 43

3.3 Object Sizes . . . . 43

4 Numeric Data Types . . . . 47

4.1 Matrices . . . . 48

4.1.1 Empty Matrices . . . . 51

4.2 Ranges . . . . 52

4.3 Single Precision Data Types . . . . 53

4.4 Integer Data Types . . . . 54

4.4.1 Integer Arithmetic . . . . 56

4.5 Bit Manipulations . . . . 57

4.6 Logical Values . . . . 59

4.7 Promotion and Demotion of Data Types . . . . 60

4.8 Predicates for Numeric Objects . . . . 61

5 Strings . . . . 65

5.1 Escape Sequences in String Constants . . . . 65

5.2 Character Arrays . . . . 66

5.3 Creating Strings . . . . 67

5.3.1 Concatenating Strings . . . . 68

5.3.2 Converting Numerical Data to Strings . . . . 71

5.4 Comparing Strings . . . . 73

5.5 Manipulating Strings . . . . 75

5.6 String Conversions . . . . 88

5.7 Character Class Functions . . . . 93

(5)

iii

6 Data Containers . . . . 97

6.1 Structures . . . . 97

6.1.1 Basic Usage and Examples . . . . 97

6.1.2 Structure Arrays . . . . 100

6.1.3 Creating Structures . . . . 102

6.1.4 Manipulating Structures . . . . 105

6.1.5 Processing Data in Structures . . . . 108

6.2 Cell Arrays . . . . 109

6.2.1 Basic Usage of Cell Arrays . . . . 109

6.2.2 Creating Cell Arrays . . . . 111

6.2.3 Indexing Cell Arrays . . . . 113

6.2.4 Cell Arrays of Strings . . . . 116

6.2.5 Processing Data in Cell Arrays . . . . 116

6.3 Comma Separated Lists . . . . 117

6.3.1 Comma Separated Lists Generated from Cell Arrays . . . . 118

6.3.2 Comma Separated Lists Generated from Structure Arrays . . . . 119

7 Variables . . . . 121

7.1 Global Variables . . . . 123

7.2 Persistent Variables . . . . 124

7.3 Status of Variables . . . . 126

8 Expressions . . . . 131

8.1 Index Expressions. . . . 131

8.1.1 Advanced Indexing . . . . 132

8.2 Calling Functions . . . . 135

8.2.1 Call by Value . . . . 135

8.2.2 Recursion . . . . 136

8.3 Arithmetic Operators . . . . 137

8.4 Comparison Operators . . . . 140

8.5 Boolean Expressions . . . . 142

8.5.1 Element-by-element Boolean Operators . . . . 142

8.5.2 Short-circuit Boolean Operators . . . . 143

8.6 Assignment Expressions . . . . 145

8.7 Increment Operators . . . . 147

8.8 Operator Precedence . . . . 148

9 Evaluation . . . . 151

9.1 Calling a Function by its Name . . . . 151

9.2 Evaluation in a Different Context . . . . 153

(6)

iv GNU Octave

10 Statements . . . . 155

10.1 The if Statement . . . . 155

10.2 The switch Statement. . . . 157

10.2.1 Notes for the C Programmer . . . . 158

10.3 The while Statement . . . . 159

10.4 The do-until Statement . . . . 160

10.5 The for Statement . . . . 160

10.5.1 Looping Over Structure Elements . . . . 161

10.6 The break Statement . . . . 162

10.7 The continue Statement . . . . 163

10.8 The unwind protect Statement. . . . 164

10.9 The try Statement . . . . 164

10.10 Continuation Lines . . . . 165

11 Functions and Scripts . . . . 167

11.1 Introduction to Function and Script Files . . . . 167

11.2 Defining Functions . . . . 167

11.3 Multiple Return Values . . . . 170

11.4 Variable-length Argument Lists . . . . 173

11.5 Ignoring Arguments . . . . 175

11.6 Variable-length Return Lists . . . . 175

11.7 Returning from a Function . . . . 176

11.8 Default Arguments . . . . 177

11.9 Function Files . . . . 178

11.9.1 Manipulating the Load Path . . . . 180

11.9.2 Subfunctions . . . . 182

11.9.3 Private Functions . . . . 183

11.9.4 Nested Functions . . . . 183

11.9.5 Overloading and Autoloading . . . . 185

11.9.6 Function Locking . . . . 186

11.9.7 Function Precedence . . . . 188

11.10 Script Files . . . . 188

11.11 Function Handles, Anonymous Functions, Inline Functions . . . . 190

11.11.1 Function Handles . . . . 190

11.11.2 Anonymous Functions . . . . 191

11.11.3 Inline Functions . . . . 191

11.12 Commands . . . . 192

11.13 Organization of Functions Distributed with Octave . . . . 192

12 Errors and Warnings . . . . 195

12.1 Handling Errors . . . . 195

12.1.1 Raising Errors . . . . 195

12.1.2 Catching Errors . . . . 198

12.1.3 Recovering From Errors . . . . 201

12.2 Handling Warnings . . . . 202

12.2.1 Issuing Warnings . . . . 202

12.2.2 Enabling and Disabling Warnings . . . . 208

(7)

v

13 Debugging . . . . 209

13.1 Entering Debug Mode . . . . 209

13.2 Leaving Debug Mode . . . . 210

13.3 Breakpoints . . . . 210

13.4 Debug Mode . . . . 212

13.5 Call Stack . . . . 214

13.6 Profiling . . . . 214

13.7 Profiler Example. . . . 216

14 Input and Output . . . . 221

14.1 Basic Input and Output . . . . 221

14.1.1 Terminal Output . . . . 221

14.1.1.1 Paging Screen Output . . . . 224

14.1.2 Terminal Input . . . . 226

14.1.3 Simple File I/O . . . . 227

14.1.3.1 Saving Data on Unexpected Exits . . . . 236

14.2 C-Style I/O Functions . . . . 237

14.2.1 Opening and Closing Files . . . . 238

14.2.2 Simple Output . . . . 239

14.2.3 Line-Oriented Input . . . . 240

14.2.4 Formatted Output . . . . 241

14.2.5 Output Conversion for Matrices . . . . 242

14.2.6 Output Conversion Syntax . . . . 243

14.2.7 Table of Output Conversions . . . . 243

14.2.8 Integer Conversions . . . . 244

14.2.9 Floating-Point Conversions . . . . 245

14.2.10 Other Output Conversions . . . . 246

14.2.11 Formatted Input . . . . 246

14.2.12 Input Conversion Syntax . . . . 247

14.2.13 Table of Input Conversions . . . . 248

14.2.14 Numeric Input Conversions . . . . 249

14.2.15 String Input Conversions. . . . 249

14.2.16 Binary I/O . . . . 250

14.2.17 Temporary Files . . . . 252

14.2.18 End of File and Errors . . . . 253

14.2.19 File Positioning . . . . 254

15 Plotting . . . . 257

15.1 Introduction to Plotting . . . . 257

15.2 High-Level Plotting . . . . 257

15.2.1 Two-Dimensional Plots . . . . 257

15.2.1.1 Axis Configuration . . . . 282

15.2.1.2 Two-dimensional Function Plotting . . . . 284

15.2.1.3 Two-dimensional Geometric Shapes . . . . 288

15.2.2 Three-Dimensional Plots . . . . 288

15.2.2.1 Aspect Ratio . . . . 304

15.2.2.2 Three-dimensional Function Plotting . . . . 305

(8)

vi GNU Octave

15.2.2.3 Three-dimensional Geometric Shapes . . . . 309

15.2.3 Plot Annotations . . . . 310

15.2.4 Multiple Plots on One Page . . . . 315

15.2.5 Multiple Plot Windows . . . . 316

15.2.6 Manipulation of Plot Windows . . . . 316

15.2.7 Use of the interpreter Property . . . . 320

15.2.8 Printing and Saving Plots . . . . 324

15.2.9 Interacting with Plots . . . . 329

15.2.10 Test Plotting Functions . . . . 330

15.3 Graphics Data Structures . . . . 331

15.3.1 Introduction to Graphics Structures . . . . 331

15.3.2 Graphics Objects . . . . 333

15.3.2.1 Creating Graphics Objects . . . . 333

15.3.2.2 Handle Functions . . . . 336

15.3.3 Graphics Object Properties . . . . 340

15.3.3.1 Root Figure Properties . . . . 341

15.3.3.2 Figure Properties . . . . 342

15.3.3.3 Axes Properties . . . . 344

15.3.3.4 Line Properties . . . . 348

15.3.3.5 Text Properties . . . . 350

15.3.3.6 Image Properties . . . . 351

15.3.3.7 Patch Properties . . . . 352

15.3.3.8 Surface Properties . . . . 354

15.3.4 Searching Properties . . . . 356

15.3.5 Managing Default Properties . . . . 357

15.4 Advanced Plotting . . . . 358

15.4.1 Colors . . . . 358

15.4.2 Line Styles. . . . 358

15.4.3 Marker Styles . . . . 358

15.4.4 Callbacks . . . . 359

15.4.5 Application-defined Data . . . . 360

15.4.6 Object Groups . . . . 361

15.4.6.1 Data Sources in Object Groups. . . . 364

15.4.6.2 Area Series . . . . 365

15.4.6.3 Bar Series . . . . 366

15.4.6.4 Contour Groups. . . . 366

15.4.6.5 Error Bar Series . . . . 368

15.4.6.6 Line Series . . . . 368

15.4.6.7 Quiver Group . . . . 369

15.4.6.8 Scatter Group . . . . 370

15.4.6.9 Stair Group . . . . 370

15.4.6.10 Stem Series . . . . 371

15.4.6.11 Surface Group . . . . 372

15.4.7 Graphics Toolkits . . . . 372

15.4.7.1 Customizing Toolkit Behavior . . . . 373

(9)

vii

16 Matrix Manipulation . . . . 375

16.1 Finding Elements and Checking Conditions . . . . 375

16.2 Rearranging Matrices . . . . 378

16.3 Special Utility Matrices . . . . 387

16.4 Famous Matrices . . . . 395

17 Arithmetic . . . . 403

17.1 Exponents and Logarithms . . . . 403

17.2 Complex Arithmetic . . . . 405

17.3 Trigonometry . . . . 406

17.4 Sums and Products . . . . 410

17.5 Utility Functions . . . . 411

17.6 Special Functions . . . . 418

17.7 Rational Approximations . . . . 424

17.8 Coordinate Transformations . . . . 425

17.9 Mathematical Constants . . . . 426

18 Linear Algebra . . . . 431

18.1 Techniques Used for Linear Algebra . . . . 431

18.2 Basic Matrix Functions . . . . 431

18.3 Matrix Factorizations . . . . 438

18.4 Functions of a Matrix . . . . 448

18.5 Specialized Solvers . . . . 449

19 Vectorization and Faster Code Execution . . . . 453

19.1 Basic Vectorization . . . . 453

19.2 Broadcasting . . . . 455

19.2.1 Broadcasting and Legacy Code . . . . 458

19.3 Function Application . . . . 458

19.4 Accumulation. . . . 462

19.5 JIT Compiler . . . . 465

19.6 Miscellaneous Techniques . . . . 466

19.7 Examples . . . . 467

20 Nonlinear Equations . . . . 469

20.1 Solvers . . . . 469

20.2 Minimizers . . . . 472

(10)

viii GNU Octave

21 Diagonal and Permutation Matrices . . . . 475

21.1 Creating and Manipulating Diagonal/Permutation Matrices . . . . 475

21.1.1 Creating Diagonal Matrices . . . . 475

21.1.2 Creating Permutation Matrices . . . . 476

21.1.3 Explicit and Implicit Conversions . . . . 477

21.2 Linear Algebra with Diagonal/Permutation Matrices . . . . 477

21.2.1 Expressions Involving Diagonal Matrices . . . . 477

21.2.2 Expressions Involving Permutation Matrices . . . . 479

21.3 Functions That Are Aware of These Matrices . . . . 479

21.3.1 Diagonal Matrix Functions . . . . 479

21.3.2 Permutation Matrix Functions . . . . 479

21.4 Examples of Usage. . . . 480

21.5 Differences in Treatment of Zero Elements . . . . 480

22 Sparse Matrices . . . . 483

22.1 Creation and Manipulation of Sparse Matrices . . . . 483

22.1.1 Storage of Sparse Matrices . . . . 483

22.1.2 Creating Sparse Matrices . . . . 484

22.1.3 Finding Information about Sparse Matrices . . . . 489

22.1.4 Basic Operators and Functions on Sparse Matrices . . . . 492

22.1.4.1 Sparse Functions . . . . 492

22.1.4.2 Return Types of Operators and Functions . . . . 493

22.1.4.3 Mathematical Considerations . . . . 494

22.2 Linear Algebra on Sparse Matrices . . . . 503

22.3 Iterative Techniques Applied to Sparse Matrices . . . . 511

22.4 Real Life Example using Sparse Matrices . . . . 516

23 Numerical Integration . . . . 521

23.1 Functions of One Variable . . . . 521

23.2 Orthogonal Collocation . . . . 528

23.3 Functions of Multiple Variables . . . . 529

24 Differential Equations . . . . 531

24.1 Ordinary Differential Equations . . . . 531

24.2 Differential-Algebraic Equations . . . . 533

25 Optimization . . . . 543

25.1 Linear Programming . . . . 543

25.2 Quadratic Programming . . . . 549

25.3 Nonlinear Programming . . . . 551

25.4 Linear Least Squares . . . . 553

(11)

ix

26 Statistics . . . . 557

26.1 Descriptive Statistics . . . . 557

26.2 Basic Statistical Functions . . . . 563

26.3 Statistical Plots . . . . 566

26.4 Correlation and Regression Analysis . . . . 567

26.5 Distributions . . . . 569

26.6 Tests . . . . 577

26.7 Random Number Generation. . . . 584

27 Sets . . . . 593

27.1 Set Operations . . . . 593

28 Polynomial Manipulations . . . . 597

28.1 Evaluating Polynomials . . . . 597

28.2 Finding Roots . . . . 598

28.3 Products of Polynomials . . . . 599

28.4 Derivatives / Integrals / Transforms . . . . 602

28.5 Polynomial Interpolation . . . . 602

28.6 Miscellaneous Functions . . . . 611

29 Interpolation . . . . 613

29.1 One-dimensional Interpolation . . . . 613

29.2 Multi-dimensional Interpolation . . . . 617

30 Geometry . . . . 621

30.1 Delaunay Triangulation . . . . 621

30.1.1 Plotting the Triangulation . . . . 623

30.1.2 Identifying Points in Triangulation . . . . 626

30.2 Voronoi Diagrams . . . . 628

30.3 Convex Hull . . . . 631

30.4 Interpolation on Scattered Data . . . . 633

31 Signal Processing . . . . 635

32 Image Processing . . . . 647

32.1 Loading and Saving Images . . . . 647

32.2 Displaying Images . . . . 653

32.3 Representing Images . . . . 654

32.4 Plotting on top of Images . . . . 662

32.5 Color Conversion . . . . 662

33 Audio Processing . . . . 665

(12)

x GNU Octave

34 Object Oriented Programming . . . . 669

34.1 Creating a Class . . . . 669

34.2 Manipulating Classes . . . . 671

34.3 Indexing Objects . . . . 674

34.3.1 Defining Indexing And Indexed Assignment . . . . 674

34.3.2 Indexed Assignment Optimization . . . . 678

34.4 Overloading Objects . . . . 678

34.4.1 Function Overloading . . . . 679

34.4.2 Operator Overloading . . . . 679

34.4.3 Precedence of Objects. . . . 680

34.5 Inheritance and Aggregation . . . . 682

35 GUI Development . . . . 687

35.1 I/O Dialogs . . . . 687

35.2 Progress Bar . . . . 688

35.3 GUI Utility Functions . . . . 689

35.4 User-Defined Preferences . . . . 691

36 System Utilities . . . . 693

36.1 Timing Utilities . . . . 693

36.2 Filesystem Utilities . . . . 703

36.3 File Archiving Utilities . . . . 712

36.4 Networking Utilities . . . . 713

36.4.1 FTP Objects . . . . 713

36.4.2 URL Manipulation . . . . 715

36.4.3 Base64 and Binary Data Transmission . . . . 716

36.5 Controlling Subprocesses . . . . 717

36.6 Process, Group, and User IDs . . . . 724

36.7 Environment Variables . . . . 724

36.8 Current Working Directory . . . . 724

36.9 Password Database Functions . . . . 726

36.10 Group Database Functions . . . . 727

36.11 System Information . . . . 727

36.12 Hashing Functions . . . . 731

37 Java Interface . . . . 733

37.1 Java Interface Functions . . . . 733

37.2 Dialog Box Functions . . . . 736

37.3 FAQ - Frequently asked Questions . . . . 739

37.3.1 How to distinguish between Octave and Matlab? . . . . 739

37.3.2 How to make Java classes available to Octave? . . . . 740

37.3.3 How to create an instance of a Java class? . . . . 741

37.3.4 How can I handle memory limitations? . . . . 741

37.3.5 Which TEX symbols are implemented in dialog functions? . . . . 742

(13)

xi

38 Packages . . . . 745

38.1 Installing and Removing Packages . . . . 745

38.2 Using Packages . . . . 748

38.3 Administrating Packages . . . . 749

38.4 Creating Packages . . . . 749

38.4.1 The DESCRIPTION File . . . . 751

38.4.2 The INDEX File . . . . 753

38.4.3 PKG ADD and PKG DEL Directives . . . . 754

38.4.4 Missing Components . . . . 754

Appendix A External Code Interface . . . . 755

A.1 Oct-Files . . . . 756

A.1.1 Getting Started with Oct-Files . . . . 756

A.1.2 Matrices and Arrays in Oct-Files . . . . 759

A.1.3 Character Strings in Oct-Files . . . . 762

A.1.4 Cell Arrays in Oct-Files . . . . 764

A.1.5 Structures in Oct-Files . . . . 764

A.1.6 Sparse Matrices in Oct-Files . . . . 766

A.1.6.1 Array and Sparse Class Differences . . . . 766

A.1.6.2 Creating Sparse Matrices in Oct-Files . . . . 767

A.1.6.3 Using Sparse Matrices in Oct-Files . . . . 770

A.1.7 Accessing Global Variables in Oct-Files . . . . 771

A.1.8 Calling Octave Functions from Oct-Files . . . . 772

A.1.9 Calling External Code from Oct-Files . . . . 773

A.1.10 Allocating Local Memory in Oct-Files . . . . 776

A.1.11 Input Parameter Checking in Oct-Files . . . . 776

A.1.12 Exception and Error Handling in Oct-Files . . . . 777

A.1.13 Documentation and Test of Oct-Files . . . . 779

A.2 Mex-Files . . . . 780

A.2.1 Getting Started with Mex-Files . . . . 780

A.2.2 Working with Matrices and Arrays in Mex-Files . . . . 782

A.2.3 Character Strings in Mex-Files . . . . 784

A.2.4 Cell Arrays with Mex-Files . . . . 784

A.2.5 Structures with Mex-Files . . . . 785

A.2.6 Sparse Matrices with Mex-Files . . . . 787

A.2.7 Calling Other Functions in Mex-Files . . . . 791

A.3 Standalone Programs . . . . 791

Appendix B Test and Demo Functions . . . . 795

B.1 Test Functions . . . . 795

B.2 Demonstration Functions . . . . 801

Appendix C Tips and Standards . . . . 805

C.1 Writing Clean Octave Programs . . . . 805

C.2 Tips on Writing Comments . . . . 805

C.3 Conventional Headers for Octave Functions . . . . 806

C.4 Tips for Documentation Strings . . . . 807

(14)

xii GNU Octave

Appendix D Contributing Guidelines. . . . 815

D.1 How to Contribute . . . . 815

D.2 Building the Development Sources . . . . 815

D.3 Basics of Generating a Changeset . . . . 815

D.4 General Guidelines . . . . 817

D.5 Octave Sources (m-files) . . . . 818

D.6 C++ Sources . . . . 819

D.7 Other Sources . . . . 820

Appendix E Obsolete Functions . . . . 821

Appendix F Known Causes of Trouble . . . . 825

F.1 Actual Bugs We Haven’t Fixed Yet . . . . 825

F.2 Reporting Bugs . . . . 825

F.2.1 Have You Found a Bug? . . . . 825

F.2.2 Where to Report Bugs . . . . 826

F.2.3 How to Report Bugs . . . . 826

F.2.4 Sending Patches for Octave . . . . 827

F.3 How To Get Help with Octave . . . . 828

Appendix G Installing Octave . . . . 829

G.1 Build Dependencies . . . . 829

G.1.1 Obtaining the Dependencies Automatically . . . . 829

G.1.2 Build Tools . . . . 829

G.1.3 External Packages . . . . 830

G.2 Running Configure and Make . . . . 832

G.3 Compiling Octave with 64-bit Indexing . . . . 836

G.4 Installation Problems. . . . 838

Appendix H Emacs Octave Support . . . . 843

H.1 Installing EOS . . . . 843

H.2 Using Octave Mode . . . . 843

H.3 Running Octave from Within Emacs . . . . 847

H.4 Using the Emacs Info Reader for Octave . . . . 848

Appendix I Grammar and Parser . . . . 851

I.1 Keywords . . . . 851

I.2 Parser . . . . 851

Appendix J GNU GENERAL PUBLIC LICENSE . . . . 853

Concept Index . . . . 865

Function Index . . . . 871

Operator Index . . . . 885

(15)

Preface 1

Preface

Octave was originally intended to be companion software for an undergraduate-level text- book on chemical reactor design being written by James B. Rawlings of the University of Wisconsin-Madison and John G. Ekerdt of the University of Texas.

Clearly, Octave is now much more than just another ‘courseware’ package with limited utility beyond the classroom. Although our initial goals were somewhat vague, we knew that we wanted to create something that would enable students to solve realistic problems, and that they could use for many things other than chemical reactor design problems. We find that most students pick up the basics of Octave quickly, and are using it confidently in just a few hours.

Although it was originally intended to be used to teach reactor design, it has been used in several other undergraduate and graduate courses in the Chemical Engineering Department at the University of Texas, and the math department at the University of Texas has been using it for teaching differential equations and linear algebra as well. More recently, Octave has been used as the primary computational tool for teaching Stanford’s online Machine Learning class (ml-class.org) taught by Andrew Ng. Tens of thousands of students participated in the course.

If you find Octave useful, please let us know. We are always interested to find out how Octave is being used.

Virtually everyone thinks that the name Octave has something to do with music, but it is actually the name of one of John W. Eaton’s former professors who wrote a famous textbook on chemical reaction engineering, and who was also well known for his ability to do quick ‘back of the envelope’ calculations. We hope that this software will make it possible for many people to do more ambitious computations just as easily.

Everyone is encouraged to share this software with others under the terms of the GNU General Public License (see Appendix J [Copying], page 853). You are also encouraged to help make Octave more useful by writing and contributing additional functions for it, and by reporting any problems you may have.

Acknowledgements

Many people have contributed to Octave’s development. The following people have helped code parts of Octave or aided in various other ways (listed alphabetically).

Ben Abbott Andy Adler Adam H. Aitkenhead

Giles Anderson Joel Andersson Muthiah Annamalai

Markus Appel Marco Atzeri Shai Ayal

Roger Banks Ben Barrowes Alexander Barth

David Bateman Heinz Bauschke Julien Bect

Roman Belov Karl Berry David Billinghurst

Don Bindner Jakub Bogusz Moritz Borgmann

Paul Boven Richard Bovey John Bradshaw

Marcus Brinkmann Max Brister Remy Bruno

Clemens Buchacher Ansgar Burchard Marco Caliari

Daniel Calvelo John C. Campbell Juan Pablo Carbajal

Jean-Francois Cardoso Joao Cardoso Larrie Carr

(16)

2 GNU Octave

David Castelow Vincent Cautaerts Clinton Chee

Albert Chin-A-Young Carsten Clark Catalin Codreanu

J. D. Cole Martin Costabel Michael Creel

Richard Crozier Jeff Cunningham Martin Dalecki

Jacob Dawid Jorge Barros de Abreu Carlo de Falco

Thomas D. Dean Philippe Defert Bill Denney

Fabian Deutsch Christos Dimitrakakis Pantxo Diribarne

Vivek Dogra John Donoghue David M. Doolin

Carn Draug Pascal A. Dupuis John W. Eaton

Dirk Eddelbuettel Pieter Eendebak Paul Eggert

Stephen Eglen Peter Ekberg Rolf Fabian

Gunnar Farnebck Stephen Fegan Ramon Garcia Fernandez

Torsten Finke Jose Daniel Munoz Frias Brad Froehle

Castor Fu Eduardo Gallestey Walter Gautschi

Klaus Gebhardt Driss Ghaddab Nicolo Giorgetti

Arun Giridhar Michael D. Godfrey Michael Goffioul

Glenn Golden Tomislav Goles Keith Goodman

Brian Gough Steffen Groot Etienne Grossmann

David Grundberg Kyle Guinn Peter Gustafson

Kai Habel Patrick Hcker William P. Y. Hadisoeseno

Jaroslav Hajek Benjamin Hall Kim Hansen

Sren Hauberg Dave Hawthorne Daniel Heiserer

Martin Helm Stefan Hepp Martin Hepperle

Jordi Gutirrez Hermoso Yozo Hida Ryan Hinton

Roman Hodek A. Scottedward Hodel Richard Allan Holcombe

Tom Holroyd David Hoover Kurt Hornik

Christopher Hulbert Cyril Humbert John Hunt

Teemu Ikonen Alan W. Irwin Geoff Jacobsen

Mats Jansson Cai Jianming Steven G. Johnson

Heikki Junes Matthias Jschke Atsushi Kajita

Jarkko Kaleva Mohamed Kamoun Lute Kamstra

Fotios Kasolis Thomas Kasper Joel Keay

Mumit Khan Paul Kienzle Aaron A. King

Erik Kjelsson Arno J. Klaassen Alexander Klein

Geoffrey Knauth Heine Kolltveit Ken Kouno

Kacper Kowalik Daniel Kraft Nir Krakauer

Aravindh Krishnamoorthy Oyvind Kristiansen Artem Krosheninnikov

Piotr Krzyzanowski Volker Kuhlmann Tetsuro Kurita

Philipp Kutin Miroslaw Kwasniak Rafael Laboissiere

Kai Labusch Claude Lacoursiere Walter Landry

Bill Lash Dirk Laurie Maurice LeBrun

Friedrich Leisch Thorsten Liebig Jyh-miin Lin

Timo Lindfors Benjamin Lindner Ross Lippert

David Livings Sebastien Loisel Erik de Castro Lopo

Massimo Lorenzin Emil Lucretiu Hoxide Ma

Colin Macdonald James Macnicol Jens-Uwe Mager

Rob Mahurin Alexander Mamonov Ricardo Marranita

(17)

Preface 3

Orestes Mas Axel Mathi Makoto Matsumoto

Tatsuro Matsuoka Christoph Mayer Laurent Mazet

G. D. McBain Ronald van der Meer Jlio Hoffimann Mendes

Ed Meyer Thorsten Meyer Petr Mikulik

Mike Miller Stefan Monnier Antoine Moreau

Kai P. Mueller Hannes Mller Victor Munoz

Iain Murray Carmen Navarrete Todd Neal

Philip Nienhuis Al Niessner Felipe G. Nievinski

Rick Niles Takuji Nishimura Kai Noda

Patrick Noffke Eric Norum Krzesimir Nowak

Michael O’Brien Peter O’Gorman Thorsten Ohl

Arno Onken Valentin Ortega-Clavero Luis F. Ortiz

Carl Osterwisch Janne Olavi Paanajrvi Scott Pakin

Gabriele Pannocchia Sylvain Pelissier Per Persson

Primozz Peterlin Jim Peterson Danilo Piazzalunga

Nicholas Piper Elias Pipping Robert Platt

Hans Ekkehard Plesser Tom Poage Orion Poplawski

Ondrej Popp Jef Poskanzer Francesco Potort

Konstantinos Poulios Jarno Rajahalme James B. Rawlings

Eric S. Raymond Balint Reczey Joshua Redstone

Lukas Reichlin Michael Reifenberger Jens Restemeier

Anthony Richardson Jason Riedy E. Joshua Rigler

Sander van Rijn Petter Risholm Matthew W. Roberts

Peter Rosin Andrew Ross Fabio Rossi

Mark van Rossum Joe Rothweiler Kevin Ruland

Kristian Rumberg Ryan Rusaw Olli Saarela

Toni Saarela Juhani Saastamoinen Radek Salac

Ben Sapp Aleksej Saushev Alois Schlgl

Michel D. Schmid Julian Schnidder Nicol N. Schraudolph

Sebastian Schubert Ludwig Schwardt Thomas L. Scofield

Daniel J. Sebald Dmitri A. Sergatskov Vanya Sergeev

Baylis Shanks Andriy Shinkarchuck Robert T. Short

Joseph P. Skudlarek John Smith Julius Smith

Shan G. Smith Peter L. Sondergaard Joerg Specht

Quentin H. Spencer Christoph Spiel Richard Stallman

Russell Standish Brett Stewart Doug Stewart

Jonathan Stickel Judd Storrs Thomas Stuart

Ivan Sutoris John Swensen Daisuke Takago

Ariel Tankus Falk Tannhuser Duncan Temple Lang

Matthew Tenny Kris Thielemans Georg Thimm

Corey Thomasson Olaf Till Christophe Tournery

Thomas Treichl Karsten Trulsen David Turner

Frederick Umminger Utkarsh Upadhyay Stefan van der Walt

Peter Van Wieren James R. Van Zandt Risto Vanhanen

Gregory Vanuxem Mihas Varantsou Ivana Varekova

Sbastien Villemot Daniel Wagenaar Thomas Walter

Andreas Weber Olaf Weber Thomas Weber

(18)

4 GNU Octave

Rik Wehbring Bob Weigel Andreas Weingessel

Martin Weiser Michael Weitzel David Wells

Fook Fah Yap Sean Young Michael Zeising

Federico Zenith Alex Zvoleff

Special thanks to the following people and organizations for supporting the development of Octave:

• The United States Department of Energy, through grant number DE-FG02-04ER25635.

• Ashok Krishnamurthy, David Hudak, Juan Carlos Chaves, and Stanley C. Ahalt of the Ohio Supercomputer Center.

• The National Science Foundation, through grant numbers CTS-0105360, CTS-9708497, CTS-9311420, CTS-8957123, and CNS-0540147.

• The industrial members of the Texas-Wisconsin Modeling and Control Consortium (TWMCC).

• The Paul A. Elfers Endowed Chair in Chemical Engineering at the University of Wisconsin-Madison.

• Digital Equipment Corporation, for an equipment grant as part of their External Re- search Program.

• Sun Microsystems, Inc., for an Academic Equipment grant.

• International Business Machines, Inc., for providing equipment as part of a grant to the University of Texas College of Engineering.

• Texaco Chemical Company, for providing funding to continue the development of this software.

• The University of Texas College of Engineering, for providing a Challenge for Excellence Research Supplement, and for providing an Academic Development Funds grant.

• The State of Texas, for providing funding through the Texas Advanced Technology Program under Grant No. 003658-078.

• Noel Bell, Senior Engineer, Texaco Chemical Company, Austin Texas.

• John A. Turner, Group Leader, Continuum Dynamics (CCS-2), Los Alamos National Laboratory, for registering the octave.org domain name.

• James B. Rawlings, Professor, University of Wisconsin-Madison, Department of Chem- ical and Biological Engineering.

• Richard Stallman, for writing GNU.

This project would not have been possible without the GNU software used in and to produce Octave.

Citing Octave in Publications

In view of the many contributions made by numerous developers over many years it is

common courtesy to cite Octave in publications when it has been used during the course of

research or the preparation of figures. The citation function can automatically generate

a recommended citation text for Octave or any of its packages. See the help text below on

how to use citation.

(19)

Preface 5

[Command]

citation

[Command]

citation package

Display instructions for citing GNU Octave or its packages in publications.

When called without an argument, display information on how to cite the core GNU Octave system. When given a package name package, display information on citing the specific named package. Note that some packages may not yet have instructions on how to cite them.

The GNU Octave developers and its active community of package authors have in- vested a lot of time and effort in creating GNU Octave as it is today. Please give credit where credit is due and cite GNU Octave and its packages when you use them.

How You Can Contribute to Octave

There are a number of ways that you can contribute to help make Octave a better system.

Perhaps the most important way to contribute is to write high-quality code for solving new problems, and to make your code freely available for others to use. See Appendix D [Contributing Guidelines], page 815, for detailed information on contributing new code.

If you find Octave useful, consider providing additional funding to continue its develop- ment. Even a modest amount of additional funding could make a significant difference in the amount of time that is available for development and support.

Donations supporting Octave development may be made on the web at https://my.fsf.org/donate/working-together/octave. These donations also help to support the Free Software Foundation

If you’d prefer to pay by check or money order, you can do so by sending a check to the FSF at the following address:

Free Software Foundation 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA

If you pay by check, please be sure to write “GNU Octave” in the memo field of your check.

If you cannot provide funding or contribute code, you can still help make Octave better and more reliable by reporting any bugs you find and by offering suggestions for ways to improve Octave. See Appendix F [Trouble], page 825, for tips on how to write useful bug reports.

Distribution

Octave is free software. This means that everyone is free to use it and free to redistribute it on certain conditions. Octave is not, however, in the public domain. It is copyrighted and there are restrictions on its distribution, but the restrictions are designed to ensure that others will have the same freedom to use and redistribute Octave that you have. The precise conditions can be found in the GNU General Public License that comes with Octave and that also appears in Appendix J [Copying], page 853.

To download a copy of Octave, please visit http://www.octave.org/download.html.

(20)
(21)

Chapter 1: A Brief Introduction to Octave 7

1 A Brief Introduction to Octave

GNU Octave is a high-level language, primarily intended for numerical computations. It is typically used for such problems as solving linear and nonlinear equations, numerical linear algebra, statistical analysis, and for performing other numerical experiments. It may also be used as a batch-oriented language for automated data processing.

Until recently GNU Octave provided a command-line interface with graphical results displayed in separate windows. The current version (version 3.8, released in late 2013) also provides, by default, a graphical user interface.

GNU Octave is freely redistributable software. You may redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. The GPL is included in this manual, see Appendix J [Copying], page 853.

This manual provides comprehensive documentation on how to install, run, use, and extend GNU Octave. Additional chapters describe how to report bugs and help contribute code.

This document corresponds to Octave version 3.8.0.

1.1 Running Octave

On most systems, Octave is started with the shell command ‘octave’. This, by default, starts the graphical user interface (GUI). The central window in the GUI is the Octave command-line interface. Octave displays an initial message and then a prompt indicating it is ready to accept input. If you have chosen the traditional command-line interface only the command prompt appears. In any case, you can immediately begin typing Octave commands.

If you get into trouble, you can usually interrupt Octave by typing Control-C (written C-c for short). C-c gets its name from the fact that you type it by holding down CTRL and then pressing C. Doing this will normally return you to Octave’s prompt.

To exit Octave, type quit, or exit at the Octave prompt.

On systems that support job control, you can suspend Octave by sending it a SIGTSTP signal, usually by typing C-z.

1.2 Simple Examples

The following chapters describe all of Octave’s features in detail, but before doing that, it might be helpful to give a sampling of some of its capabilities.

If you are new to Octave, I recommend that you try these examples to begin learning Octave by using it. Lines marked like so, ‘octave:13>’, are lines you type, ending each with a carriage return. Octave will respond with an answer, or by displaying a graph.

1.2.1 Elementary Calculations

Octave can easily be used for basic numerical calculations. Octave knows about arithmetic

operations (+,-,*,/), exponentiation (^), natural logarithms/exponents (log, exp), and the

trigonometric functions (sin, cos, . . . ). Moreover, Octave calculations work on real or

imaginary numbers (i,j). In addition, some mathematical constants such as the base of

(22)

8 GNU Octave

the natural logarithm (e) and the ratio of a circle’s circumference to its diameter (pi) are pre-defined.

For example, to verify Euler’s Identity,

e

ıπ

= −1

type the following which will evaluate to -1 within the tolerance of the calculation.

octave:1> exp (i*pi)

1.2.2 Creating a Matrix

Vectors and matrices are the basic building blocks for numerical analysis. To create a new matrix and store it in a variable so that you can refer to it later, type the command

octave:1> A = [ 1, 1, 2; 3, 5, 8; 13, 21, 34 ]

Octave will respond by printing the matrix in neatly aligned columns. Octave uses a comma or space to separate entries in a row, and a semicolon or carriage return to separate one row from the next. Ending a command with a semicolon tells Octave not to print the result of the command. For example,

octave:2> B = rand (3, 2);

will create a 3 row, 2 column matrix with each element set to a random value between zero and one.

To display the value of a variable, simply type the name of the variable at the prompt.

For example, to display the value stored in the matrix B, type the command octave:3> B

1.2.3 Matrix Arithmetic

Octave has a convenient operator notation for performing matrix arithmetic. For example, to multiply the matrix A by a scalar value, type the command

octave:4> 2 * A

To multiply the two matrices A and B, type the command octave:5> A * B

and to form the matrix product A

T

A, type the command octave:6> A’ * A

1.2.4 Solving Systems of Linear Equations

Systems of linear equations are ubiquitous in numerical analysis. To solve the set of linear equations Ax = b, use the left division operator, ‘\’:

x = A \ b

This is conceptually equivalent to A

−1

b, but avoids computing the inverse of a matrix directly.

If the coefficient matrix is singular, Octave will print a warning message and compute a

minimum norm solution.

(23)

Chapter 1: A Brief Introduction to Octave 9

A simple example comes from chemistry and the need to obtain balanced chemical equations. Consider the burning of hydrogen and oxygen to produce water.

H

2

+ O

2

→ H

2

O

The equation above is not accurate. The Law of Conservation of Mass requires that the num- ber of molecules of each type balance on the left- and right-hand sides of the equation. Writ- ing the variable overall reaction with individual equations for hydrogen and oxygen one finds:

x

1

H

2

+ x

2

O

2

→ H

2

O H : 2x

1

+ 0x

2

→ 2 O : 0x

1

+ 2x

2

→ 1 The solution in Octave is found in just three steps.

octave:1> A = [ 2, 0; 0, 2 ];

octave:2> b = [ 2; 1 ];

octave:3> x = A \ b

1.2.5 Integrating Differential Equations

Octave has built-in functions for solving nonlinear differential equations of the form dx

dt = f (x, t), x(t = t

0

) = x

0

For Octave to integrate equations of this form, you must first provide a definition of the function f (x, t). This is straightforward, and may be accomplished by entering the function body directly on the command line. For example, the following commands define the right- hand side function for an interesting pair of nonlinear differential equations. Note that while you are entering a function, Octave responds with a different prompt, to indicate that it is waiting for you to complete your input.

octave:1> function xdot = f (x, t)

>

> r = 0.25;

> k = 1.4;

> a = 1.5;

> b = 0.16;

> c = 0.9;

> d = 0.8;

>

> xdot(1) = r*x(1)*(1 - x(1)/k) - a*x(1)*x(2)/(1 + b*x(1));

> xdot(2) = c*a*x(1)*x(2)/(1 + b*x(1)) - d*x(2);

>

> endfunction Given the initial condition

octave:2> x0 = [1; 2];

and the set of output times as a column vector (note that the first output time corresponds

to the initial condition given above)

(24)

10 GNU Octave

octave:3> t = linspace (0, 50, 200)’;

it is easy to integrate the set of differential equations:

octave:4> x = lsode ("f", x0, t);

The function lsode uses the Livermore Solver for Ordinary Differential Equations, described in A. C. Hindmarsh, ODEPACK, a Systematized Collection of ODE Solvers, in: Scientific Computing, R. S. Stepleman et al. (Eds.), North-Holland, Amsterdam, 1983, pages 55–64.

1.2.6 Producing Graphical Output

To display the solution of the previous example graphically, use the command octave:1> plot (t, x)

If you are using a graphical user interface, Octave will automatically create a separate window to display the plot.

To save a plot once it has been displayed on the screen, use the print command. For example,

print -deps foo.eps

will create a file called ‘foo.eps’ that contains a rendering of the current plot in Encapsu- lated PostScript format. The command

help print

explains more options for the print command and provides a list of additional output file formats.

1.2.7 Editing What You Have Typed

At the Octave prompt, you can recall, edit, and reissue previous commands using Emacs- or vi-style editing commands. The default keybindings use Emacs-style commands. For example, to recall the previous command, press Control-p (written C-p for short). Doing this will normally bring back the previous line of input. C-n will bring up the next line of input, C-b will move the cursor backward on the line, C-f will move the cursor forward on the line, etc.

A complete description of the command line editing capability is given in this manual, see Section 2.4 [Command Line Editing], page 24.

1.2.8 Help and Documentation

Octave has an extensive help facility. The same documentation that is available in printed form is also available from the Octave prompt, because both forms of the documentation are created from the same input file.

In order to get good help you first need to know the name of the command that you want to use. This name of the function may not always be obvious, but a good place to start is to type help --list. This will show you all the operators, keywords, built-in functions, and loadable functions available in the current session of Octave. An alternative is to search the documentation using the lookfor function. This function is described in Section 2.3 [Getting Help], page 20.

Once you know the name of the function you wish to use, you can get more help on the

function by simply including the name as an argument to help. For example,

(25)

Chapter 1: A Brief Introduction to Octave 11

help plot

will display the help text for the plot function.

Octave sends output that is too long to fit on one screen through a pager like less or more. Type a RET to advance one line, a SPC to advance one page, and Q to exit the pager.

The part of Octave’s help facility that allows you to read the complete text of the printed manual from within Octave normally uses a separate program called Info. When you invoke Info you will be put into a menu driven program that contains the entire Octave manual.

Help for using Info is provided in this manual, see Section 2.3 [Getting Help], page 20.

1.3 Conventions

This section explains the notational conventions that are used in this manual. You may want to skip this section and refer back to it later.

1.3.1 Fonts

Examples of Octave code appear in this font or form: svd (a). Names that represent variables or function arguments appear in this font or form: first-number. Commands that you type at the shell prompt appear in this font or form: ‘octave --no-init-file’.

Commands that you type at the Octave prompt sometimes appear in this font or form: foo --bar --baz. Specific keys on your keyboard appear in this font or form: ANY.

1.3.2 Evaluation Notation

In the examples in this manual, results from expressions that you evaluate are indicated with ‘⇒’. For example:

sqrt (2)

⇒ 1.4142

You can read this as “sqrt (2) evaluates to 1.4142”.

In some cases, matrix values that are returned by expressions are displayed like this [1, 2; 3, 4] == [1, 3; 2, 4]

⇒ [ 1, 0; 0, 1 ]

and in other cases, they are displayed like this eye (3)

⇒ 1 0 0

0 1 0

0 0 1

in order to clearly show the structure of the result.

Sometimes to help describe one expression, another expression is shown that produces identical results. The exact equivalence of expressions is indicated with ‘ ≡ ’. For example:

rot90 ([1, 2; 3, 4], -1)

rot90 ([1, 2; 3, 4], 3)

rot90 ([1, 2; 3, 4], 7)

(26)

12 GNU Octave

1.3.3 Printing Notation

Many of the examples in this manual print text when they are evaluated. In this manual the printed text resulting from an example is indicated by ‘ a ’. The value that is returned by evaluating the expression is displayed with ‘⇒’ (1 in the next example) and follows on a separate line.

printf ("foo %s\n", "bar") a foo bar

⇒ 1

1.3.4 Error Messages

Some examples signal errors. This normally displays an error message on your terminal.

Error messages are shown on a line beginning with error:.

fieldnames ([1, 2; 3, 4])

error: fieldnames: Invalid input argument

1.3.5 Format of Descriptions

Functions and commands are described in this manual in a uniform format. The first line of a description contains the name of the item followed by its arguments, if any. The category—

function, command, or whatever—is printed next to the right margin. The description follows on succeeding lines, sometimes with examples.

1.3.5.1 A Sample Function Description

In a function description, the name of the function being described appears first. It is followed on the same line by a list of parameters. The names used for the parameters are also used in the body of the description.

Here is a description of an imaginary function foo:

[Function File]

foo ( x )

[Function File]

foo ( x , y )

[Function File]

foo ( x , y , . . . )

The function foo subtracts x from y, then adds the remaining arguments to the result.

If y is not supplied, then the number 19 is used by default.

foo (1, [3, 5], 3, 9)

⇒ [ 14, 16 ] foo (5)

⇒ 14 More generally,

foo (w, x, y, ...)

x - w + y + ...

Any parameter whose name contains the name of a type (e.g., integer or matrix) is

expected to be of that type. Parameters named object may be of any type. Parameters

with other sorts of names (e.g., new file) are discussed specifically in the description of

the function. In some sections, features common to parameters of several functions are

described at the beginning.

(27)

Chapter 1: A Brief Introduction to Octave 13

Functions in Octave may be defined in several different ways. The category name for functions may include another name that indicates the way that the function is defined.

These additional tags include Function File

The function described is defined using Octave commands stored in a text file.

See Section 11.9 [Function Files], page 178.

Built-in Function

The function described is written in a language like C++, C, or Fortran, and is part of the compiled Octave binary.

Loadable Function

The function described is written in a language like C++, C, or Fortran. On systems that support dynamic linking of user-supplied functions, it may be automatically linked while Octave is running, but only if it is needed. See Appendix A [External Code Interface], page 755.

Mapping Function

The function described works element-by-element for matrix and vector argu- ments.

1.3.5.2 A Sample Command Description

Command descriptions have a format similar to function descriptions, except that the word

‘Function’ is replaced by ‘Command’. Commands are functions that may be called with- out surrounding their arguments in parentheses. For example, here is the description for Octave’s cd command:

[Command]

cd dir

[Command]

chdir dir

Change the current working directory to dir. For example, cd ~/octave changes the

current working directory to ‘~/octave’. If the directory does not exist, an error

message is printed and the working directory is not changed.

(28)
(29)

Chapter 2: Getting Started 15

2 Getting Started

This chapter explains some of Octave’s basic features, including how to start an Octave ses- sion, get help at the command prompt, edit the command line, and write Octave programs that can be executed as commands from your shell.

2.1 Invoking Octave from the Command Line

Normally, Octave is used interactively by running the program ‘octave’ without any ar- guments. Once started, Octave reads commands from the terminal until you tell it to exit.

You can also specify the name of a file on the command line, and Octave will read and execute the commands from the named file and then exit when it is finished.

You can further control how Octave starts by using the command-line options described in the next section, and Octave itself can remind you of the options available. Type ‘octave --help’ to display all available options and briefly describe their use (‘octave -h’ is a shorter equivalent).

2.1.1 Command Line Options

Here is a complete list of the command line options that Octave accepts.

--built-in-docstrings-file filename

Specify the name of the file containing documentation strings for the built-in functions of Octave. This value is normally correct and should only need to specified in extraordinary situations.

--debug

-d Enter parser debugging mode. Using this option will cause Octave’s parser to print a lot of information about the commands it reads, and is probably only useful if you are actually trying to debug the parser.

--debug-jit

Enable JIT compiler debugging and tracing.

--doc-cache-file filename

Specify the name of the doc cache file to use. The value of filename specified on the command line will override any value of OCTAVE_DOC_CACHE_FILE found in the environment, but not any commands in the system or user startup files that use the doc_cache_file function.

--echo-commands

-x Echo commands as they are executed.

--eval code

Evaluate code and exit when finished unless ‘--persist’ is also specified.

--exec-path path

Specify the path to search for programs to run. The value of path specified on

the command line will override any value of OCTAVE_EXEC_PATH found in the

environment, but not any commands in the system or user startup files that set

the built-in variable EXEC_PATH.

(30)

16 GNU Octave

--force-gui

Force the graphical user interface (GUI) to start.

--help -h

-? Print short help message and exit.

--image-path path

Add path to the head of the search path for images. The value of path specified on the command line will override any value of OCTAVE_IMAGE_PATH found in the environment, but not any commands in the system or user startup files that set the built-in variable IMAGE_PATH.

--info-file filename

Specify the name of the info file to use. The value of filename specified on the command line will override any value of OCTAVE_INFO_FILE found in the environment, but not any commands in the system or user startup files that use the info_file function.

--info-program program

Specify the name of the info program to use. The value of program specified on the command line will override any value of OCTAVE_INFO_PROGRAM found in the environment, but not any commands in the system or user startup files that use the info_program function.

--interactive

-i Force interactive behavior. This can be useful for running Octave via a remote shell command or inside an Emacs shell buffer. For another way to run Octave within Emacs, see Appendix H [Emacs Octave Support], page 843.

--jit-compiler

Enable the JIT compiler used for accelerating loops.

--line-editing

Force readline use for command-line editing.

--no-gui Disable the graphical user interface (GUI) and use the command line interface (CLI) instead.

--no-history

-H Disable recording of command-line history.

--no-init-file

Don’t read the initialization files ‘~/.octaverc’ and ‘.octaverc’.

--no-init-path

Don’t initialize the search path for function files to include default locations.

--no-line-editing

Disable command-line editing.

--no-site-file

Don’t read the site-wide ‘octaverc’ initialization files.

(31)

Chapter 2: Getting Started 17

--no-window-system

-W Disable use of a windowing system including graphics. This forces a strictly terminal-only environment.

--norc

-f Don’t read any of the system or user initialization files at startup. This is equiv- alent to using both of the options ‘--no-init-file’ and ‘--no-site-file’.

--path path

-p path Add path to the head of the search path for function files. The value of path specified on the command line will override any value of OCTAVE_PATH found in the environment, but not any commands in the system or user startup files that set the internal load path through one of the path functions.

--persist

Go to interactive mode after ‘--eval’ or reading from a file named on the command line.

--silent --quiet

-q Don’t print the usual greeting and version message at startup.

--texi-macros-file filename

Specify the name of the file containing Texinfo macros for use by makeinfo.

--traditional --braindead

For compatibility with matlab, set initial values for user preferences to the following values

PS1 = ">> "

PS2 = ""

allow_noninteger_range_as_index = true

beep_on_error = true

confirm_recursive_rmdir = false

crash_dumps_octave_core = false

save_default_options = "-mat-binary"

do_braindead_shortcircuit_evaluation = true

fixed_point_format = true

history_timestamp_format_string = "%%-- %D %I:%M %p --%%"

page_screen_output = false

print_empty_dimensions = false

and disable the following warnings

Octave:abbreviated-property-match Octave:fopen-file-in-path

Octave:function-name-clash Octave:load-file-in-path

Note that this does not enable the Octave:matlab-incompatible warning,

which you might want if you want to be told about writing code that works in

Octave but not matlab (see [warning], page 202, [warning ids], page 203).

(32)

18 GNU Octave

--verbose

-V Turn on verbose output.

--version

-v Print the program version number and exit.

file Execute commands from file. Exit when done unless ‘--persist’ is also speci- fied.

Octave also includes several functions which return information about the command line, including the number of arguments and all of the options.

[Built-in Function]

argv ()

Return the command line arguments passed to Octave. For example, if you invoked Octave using the command

octave --no-line-editing --silent

argv would return a cell array of strings with the elements ‘--no-line-editing’ and

‘--silent’.

If you write an executable Octave script, argv will return the list of arguments passed to the script. See Section 2.6 [Executable Octave Programs], page 35, for an example of how to create an executable Octave script.

[Built-in Function]

program_name ()

Return the last component of the value returned by program_invocation_name.

See also: [program invocation name], page 18.

[Built-in Function]

program_invocation_name ()

Return the name that was typed at the shell prompt to run Octave.

If executing a script from the command line (e.g., octave foo.m) or using an ex- ecutable Octave script, the program name is set to the name of the script. See Section 2.6 [Executable Octave Programs], page 35, for an example of how to create an executable Octave script.

See also: [program name], page 18.

Here is an example of using these functions to reproduce the command line which invoked Octave.

printf ("%s", program_name ());

arg_list = argv ();

for i = 1:nargin

printf (" %s", arg_list{i});

endfor

printf ("\n");

See Section 6.2.3 [Indexing Cell Arrays], page 113, for an explanation of how to retrieve

objects from cell arrays, and Section 11.2 [Defining Functions], page 167, for information

about the variable nargin.

(33)

Chapter 2: Getting Started 19

2.1.2 Startup Files

When Octave starts, it looks for commands to execute from the files in the following list.

These files may contain any valid Octave commands, including function definitions.

octave-home /share/octave/site/m/startup/octaverc

where octave-home is the directory in which Octave is installed (the default is ‘/usr/local’). This file is provided so that changes to the default Octave environment can be made globally for all users at your site for all versions of Octave you have installed. Care should be taken when making changes to this file since all users of Octave at your site will be affected. The default file may be overridden by the environment variable OCTAVE_SITE_INITFILE.

octave-home /share/octave/version /m/startup/octaverc

where octave-home is the directory in which Octave is installed (the default is

‘/usr/local’), and version is the version number of Octave. This file is pro- vided so that changes to the default Octave environment can be made glob- ally for all users of a particular version of Octave. Care should be taken when making changes to this file since all users of Octave at your site will be affected. The default file may be overridden by the environment variable OCTAVE_VERSION_INITFILE.

~/.octaverc

This file is used to make personal changes to the default Octave environment.

.octaverc

This file can be used to make changes to the default Octave environment for a particular project. Octave searches for this file in the current directory after it reads ‘~/.octaverc’. Any use of the cd command in the ‘~/.octaverc’ file will affect the directory where Octave searches for ‘.octaverc’.

If you start Octave in your home directory, commands from the file

‘~/.octaverc’ will only be executed once.

A message will be displayed as each of the startup files is read if you invoke Octave with the ‘--verbose’ option but without the ‘--silent’ option.

The dump_prefs function is useful for determining what customizations to Octave are possible and which are in effect.

[Function File]

dump_prefs ()

[Function File]

dump_prefs ( fid )

Dump all of the current user preference variables in a format that can be parsed by Octave later. fid is a file descriptor as returned by fopen. If file is omitted, the listing is printed to stdout.

2.2 Quitting Octave

[Built-in Function]

exit ( status )

[Built-in Function]

quit ( status )

Exit the current Octave session. If the optional integer value status is supplied, pass

that value to the operating system as the Octave’s exit status. The default value is

zero.

Riferimenti

Documenti correlati

In order to better understand the value creation in architecture the research started focussing on the economic features of design, the research started ana- lysing

a) Any Party, and the committee mentioned in Article 16, may propose amendments to this Convention. b) Any proposal for amendment shall be notified to the Secretary General of

If current rule is a regular rule or a branch- exists rule, the engine replaces the goal with the first conclusion of the rule and determines the next rule to apply by invoking

Altri dati difficili da reperire sono stati quelli relativi agli assegnisti di ricerca, complessi da disaggregare per genere perché non gestiti a livello centralizzato, ma dai

(American Mathematical Monthly, Vol.118, November 2011) Proposed by Harm Derksen and Jeffrey Lagarias (USA).. The Farey series of order n is the set of reduced rational fractions j/k

[r]

Since Octave doesn’t look for definitions until they are needed, the following code will always print ‘bar = 3’ whether it is typed directly on the command line, read from a

The value of path specified on the command line will override any value of OCTAVE_EXEC_PATH found in the environment, but not any commands in the system or user startup files that