• Non ci sono risultati.

GNU Octave A high-level interactive language for numerical computations Edition 3 for Octave version 3.6.1 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.6.1 February 2011"

Copied!
812
0
0

Testo completo

(1)

GNU Octave

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

Free Your Numbers

John W. Eaton

David Bateman

Søren Hauberg

(2)

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

This is the third edition of the Octave documentation, and is consistent with version 3.6.1 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

How You Can Contribute to Octave . . . 4

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 . . . 11

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

1.3.5.3 A Sample Variable 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 . . . 18

2.2 Quitting Octave . . . 19

2.3 Commands for Getting Help. . . 19

2.4 Command Line Editing . . . 23

2.4.1 Cursor Motion . . . 24

2.4.2 Killing and Yanking . . . 24

2.4.3 Commands For Changing Text . . . 25

2.4.4 Letting Readline Type For You . . . 25

2.4.5 Commands For Manipulating The History . . . 26

2.4.6 Customizing readline . . . 29

2.4.7 Customizing the Prompt . . . 29

2.4.8 Diary and Echo Commands . . . 31

2.5 How Octave Reports Errors . . . 32

(4)

ii GNU Octave

2.6 Executable Octave Programs . . . 33

2.7 Comments in Octave Programs . . . 34

2.7.1 Single Line Comments . . . 34

2.7.2 Block Comments . . . 34

2.7.3 Comments and the Help System . . . 35

3 Data Types . . . . 37

3.1 Built-in Data Types . . . 37

3.1.1 Numeric Objects . . . 39

3.1.2 Missing Data . . . 40

3.1.3 String Objects . . . 40

3.1.4 Data Structure Objects . . . 40

3.1.5 Cell Array Objects . . . 40

3.2 User-defined Data Types . . . 41

3.3 Object Sizes . . . 41

4 Numeric Data Types . . . . 45

4.1 Matrices . . . 46

4.1.1 Empty Matrices . . . 49

4.2 Ranges . . . 50

4.3 Single Precision Data Types . . . 51

4.4 Integer Data Types . . . 52

4.4.1 Integer Arithmetic . . . 53

4.5 Bit Manipulations . . . 54

4.6 Logical Values . . . 57

4.7 Promotion and Demotion of Data Types . . . 58

4.8 Predicates for Numeric Objects . . . 58

5 Strings . . . . 63

5.1 Escape Sequences in String Constants . . . 63

5.2 Character Arrays . . . 64

5.3 Creating Strings . . . 65

5.3.1 Concatenating Strings . . . 65

5.3.2 Conversion of Numerical Data to Strings. . . 69

5.4 Comparing Strings . . . 70

5.5 Manipulating Strings . . . 72

5.6 String Conversions . . . 82

5.7 Character Class Functions . . . 87

(5)

iii

6 Data Containers . . . . 91

6.1 Structures . . . 91

6.1.1 Basic Usage and Examples . . . 91

6.1.2 Structure Arrays . . . 94

6.1.3 Creating Structures . . . 96

6.1.4 Manipulating Structures . . . 98

6.1.5 Processing Data in Structures . . . 101

6.2 Cell Arrays . . . 102

6.2.1 Basic Usage of Cell Arrays . . . 102

6.2.2 Creating Cell Array . . . 103

6.2.3 Indexing Cell Arrays . . . 106

6.2.4 Cell Arrays of Strings . . . 108

6.2.5 Processing Data in Cell Arrays . . . 109

6.3 Comma Separated Lists . . . 110

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

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

7 Variables . . . . 113

7.1 Global Variables . . . 114

7.2 Persistent Variables . . . 116

7.3 Status of Variables . . . 117

8 Expressions . . . . 123

8.1 Index Expressions . . . 123

8.1.1 Advanced Indexing . . . 124

8.2 Calling Functions . . . 127

8.2.1 Call by Value . . . 127

8.2.2 Recursion . . . 128

8.3 Arithmetic Operators . . . 129

8.4 Comparison Operators . . . 132

8.5 Boolean Expressions . . . 133

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

8.5.2 Short-circuit Boolean Operators . . . 135

8.6 Assignment Expressions . . . 137

8.7 Increment Operators . . . 139

8.8 Operator Precedence . . . 139

9 Evaluation . . . . 141

9.1 Calling a Function by its Name . . . 141

9.2 Evaluation in a Different Context . . . 143

(6)

iv GNU Octave

10 Statements . . . . 145

10.1 The if Statement . . . 145

10.2 The switch Statement . . . 147

10.2.1 Notes for the C Programmer . . . 148

10.3 The while Statement . . . 149

10.4 The do-until Statement . . . 150

10.5 The for Statement . . . 150

10.5.1 Looping Over Structure Elements . . . 151

10.6 The break Statement . . . 152

10.7 The continue Statement . . . 153

10.8 The unwind_protect Statement . . . 154

10.9 The try Statement . . . 154

10.10 Continuation Lines . . . 155

11 Functions and Scripts . . . . 157

11.1 Defining Functions . . . 157

11.2 Multiple Return Values . . . 159

11.3 Variable-length Argument Lists . . . 163

11.4 Ignoring Arguments . . . 164

11.5 Variable-length Return Lists . . . 165

11.6 Returning from a Function . . . 166

11.7 Default Arguments . . . 166

11.8 Function Files . . . 167

11.8.1 Manipulating the Load Path . . . 170

11.8.2 Subfunctions . . . 172

11.8.3 Private Functions . . . 172

11.8.4 Overloading and Autoloading . . . 173

11.8.5 Function Locking . . . 173

11.8.6 Function Precedence . . . 175

11.9 Script Files . . . 175

11.10 Function Handles, Inline Functions, and Anonymous Functions . . . 177

11.10.1 Function Handles . . . 177

11.10.2 Anonymous Functions . . . 178

11.10.3 Inline Functions . . . 178

11.11 Commands . . . 179

11.12 Organization of Functions Distributed with Octave . . . 179

12 Errors and Warnings . . . . 181

12.1 Handling Errors . . . 181

12.1.1 Raising Errors . . . 181

12.1.2 Catching Errors . . . 184

12.1.3 Recovering From Errors . . . 186

12.2 Handling Warnings . . . 186

12.2.1 Issuing Warnings . . . 186

12.2.2 Enabling and Disabling Warnings . . . 188

(7)

v

13 Debugging . . . . 193

13.1 Entering Debug Mode . . . 193

13.2 Leaving Debug Mode . . . 194

13.3 Breakpoints . . . 194

13.4 Debug Mode . . . 196

13.5 Call Stack . . . 197

13.6 Profiling . . . 198

13.7 Profiler Example . . . 199

14 Input and Output . . . . 203

14.1 Basic Input and Output . . . 203

14.1.1 Terminal Output . . . 203

14.1.1.1 Paging Screen Output . . . 206

14.1.2 Terminal Input . . . 208

14.1.3 Simple File I/O . . . 209

14.1.3.1 Saving Data on Unexpected Exits . . . 216

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

14.2.1 Opening and Closing Files . . . 219

14.2.2 Simple Output . . . 220

14.2.3 Line-Oriented Input . . . 221

14.2.4 Formatted Output . . . 222

14.2.5 Output Conversion for Matrices . . . 223

14.2.6 Output Conversion Syntax . . . 223

14.2.7 Table of Output Conversions . . . 224

14.2.8 Integer Conversions . . . 225

14.2.9 Floating-Point Conversions . . . 225

14.2.10 Other Output Conversions . . . 226

14.2.11 Formatted Input . . . 227

14.2.12 Input Conversion Syntax . . . 228

14.2.13 Table of Input Conversions . . . 229

14.2.14 Numeric Input Conversions . . . 230

14.2.15 String Input Conversions . . . 230

14.2.16 Binary I/O . . . 230

14.2.17 Temporary Files . . . 233

14.2.18 End of File and Errors . . . 234

14.2.19 File Positioning . . . 235

15 Plotting . . . . 237

15.1 Introduction to Plotting . . . 237

15.2 High-Level Plotting . . . 237

15.2.1 Two-Dimensional Plots . . . 237

15.2.1.1 Axis Configuration . . . 256

15.2.1.2 Two-dimensional Function Plotting . . . 258

15.2.1.3 Two-dimensional Geometric Shapes . . . 260

15.2.2 Three-Dimensional Plots . . . 261

15.2.2.1 Aspect Ratio . . . 272

15.2.2.2 Three-dimensional Function Plotting . . . 273

(8)

vi GNU Octave

15.2.2.3 Three-dimensional Geometric Shapes . . . 275

15.2.3 Plot Annotations . . . 276

15.2.4 Multiple Plots on One Page . . . 280

15.2.5 Multiple Plot Windows . . . 280

15.2.6 Use of axis, line, and patch functions . . . 281

15.2.7 Manipulation of plot windows . . . 282

15.2.8 Use of the interpreter Property . . . 284

15.2.9 Printing and Saving Plots . . . 287

15.2.10 Interacting with Plots . . . 291

15.2.11 Test Plotting Functions . . . 292

15.3 Graphics Data Structures . . . 293

15.3.1 Introduction to Graphics Structures . . . 293

15.3.2 Graphics Objects . . . 294

15.3.2.1 Handle Functions . . . 295

15.3.3 Graphics Object Properties . . . 297

15.3.3.1 Root Figure Properties . . . 297

15.3.3.2 Figure Properties . . . 298

15.3.3.3 Axes Properties . . . 301

15.3.3.4 Line Properties . . . 305

15.3.3.5 Text Properties . . . 307

15.3.3.6 Image Properties . . . 308

15.3.3.7 Patch Properties . . . 309

15.3.3.8 Surface Properties . . . 311

15.3.4 Searching Properties . . . 313

15.3.5 Managing Default Properties . . . 314

15.4 Advanced Plotting . . . 315

15.4.1 Colors . . . 315

15.4.2 Line Styles . . . 315

15.4.3 Marker Styles . . . 315

15.4.4 Callbacks . . . 316

15.4.5 Application-defined Data . . . 317

15.4.6 Object Groups . . . 317

15.4.6.1 Data Sources in Object Groups . . . 321

15.4.6.2 Area Series . . . 321

15.4.6.3 Bar Series . . . 322

15.4.6.4 Contour Groups . . . 323

15.4.6.5 Error Bar Series . . . 324

15.4.6.6 Line Series . . . 325

15.4.6.7 Quiver Group . . . 325

15.4.6.8 Scatter Group . . . 326

15.4.6.9 Stair Group . . . 327

15.4.6.10 Stem Series . . . 327

15.4.6.11 Surface Group . . . 328

15.4.7 Graphics Toolkits . . . 329

15.4.7.1 Customizing Toolkit Behavior . . . 329

(9)

vii

16 Matrix Manipulation . . . . 331

16.1 Finding Elements and Checking Conditions . . . 331

16.2 Rearranging Matrices . . . 334

16.3 Special Utility Matrices . . . 343

16.4 Famous Matrices . . . 350

17 Arithmetic . . . . 353

17.1 Exponents and Logarithms . . . 353

17.2 Complex Arithmetic . . . 355

17.3 Trigonometry . . . 356

17.4 Sums and Products . . . 359

17.5 Utility Functions . . . 360

17.6 Special Functions . . . 367

17.7 Rational Approximations . . . 372

17.8 Coordinate Transformations . . . 372

17.9 Mathematical Constants . . . 373

18 Linear Algebra . . . . 377

18.1 Techniques Used for Linear Algebra . . . 377

18.2 Basic Matrix Functions . . . 377

18.3 Matrix Factorizations . . . 383

18.4 Functions of a Matrix . . . 392

18.5 Specialized Solvers . . . 394

19 Vectorization and Faster Code Execution . . . . 397

19.1 Basic Vectorization . . . 397

19.2 Broadcasting . . . 399

19.2.1 Broadcasting and Legacy Code . . . 402

19.3 Function Application . . . 402

19.4 Accumulation . . . 406

19.5 Miscellaneous Techniques . . . 408

19.6 Examples . . . 410

20 Nonlinear Equations . . . . 411

20.1 Solvers . . . 411

20.2 Minimizers . . . 414

(10)

viii GNU Octave

21 Diagonal and Permutation Matrices . . . . 417

21.1 Creating and Manipulating Diagonal and Permutation Matrices . . . 417

21.1.1 Creating Diagonal Matrices . . . 417

21.1.2 Creating Permutation Matrices . . . 418

21.1.3 Explicit and Implicit Conversions . . . 419

21.2 Linear Algebra with Diagonal and Permutation Matrices . . . . 419

21.2.1 Expressions Involving Diagonal Matrices . . . 419

21.2.2 Expressions Involving Permutation Matrices . . . 421

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

21.3.1 Diagonal Matrix Functions . . . 421

21.3.2 Permutation Matrix Functions . . . 421

21.4 Some Examples of Usage . . . 422

21.5 The Differences in Treatment of Zero Elements . . . 422

22 Sparse Matrices . . . . 425

22.1 The Creation and Manipulation of Sparse Matrices . . . 425

22.1.1 Storage of Sparse Matrices . . . 425

22.1.2 Creating Sparse Matrices . . . 426

22.1.3 Finding out Information about Sparse Matrices . . . 431

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

22.1.4.1 Sparse Functions . . . 434

22.1.4.2 The Return Types of Operators and Functions . . . 435

22.1.4.3 Mathematical Considerations . . . 436

22.2 Linear Algebra on Sparse Matrices . . . 445

22.3 Iterative Techniques applied to sparse matrices . . . 453

22.4 Real Life Example of the use of Sparse Matrices . . . 458

23 Numerical Integration . . . . 463

23.1 Functions of One Variable . . . 463

23.2 Orthogonal Collocation . . . 470

23.3 Functions of Multiple Variables . . . 471

24 Differential Equations . . . . 473

24.1 Ordinary Differential Equations . . . 473

24.2 Differential-Algebraic Equations . . . 475

25 Optimization . . . . 485

25.1 Linear Programming . . . 485

25.2 Quadratic Programming . . . 491

25.3 Nonlinear Programming . . . 493

25.4 Linear Least Squares . . . 495

(11)

ix

26 Statistics . . . . 499

26.1 Descriptive Statistics . . . 499

26.2 Basic Statistical Functions . . . 504

26.3 Statistical Plots . . . 507

26.4 Correlation and Regression Analysis . . . 508

26.5 Distributions . . . 510

26.6 Tests . . . 518

26.7 Random Number Generation . . . 525

27 Sets . . . . 533

27.1 Set Operations . . . 533

28 Polynomial Manipulations . . . . 537

28.1 Evaluating Polynomials . . . 537

28.2 Finding Roots . . . 538

28.3 Products of Polynomials . . . 539

28.4 Derivatives / Integrals / Transforms . . . 542

28.5 Polynomial Interpolation . . . 542

28.6 Miscellaneous Functions . . . 545

29 Interpolation . . . . 547

29.1 One-dimensional Interpolation . . . 547

29.2 Multi-dimensional Interpolation . . . 552

30 Geometry . . . . 557

30.1 Delaunay Triangulation . . . 557

30.1.1 Plotting the Triangulation . . . 559

30.1.2 Identifying Points in Triangulation . . . 560

30.2 Voronoi Diagrams . . . 562

30.3 Convex Hull . . . 566

30.4 Interpolation on Scattered Data . . . 567

31 Signal Processing . . . . 569

32 Image Processing . . . . 581

32.1 Loading and Saving Images . . . 581

32.2 Displaying Images . . . 584

32.3 Representing Images . . . 585

32.4 Plotting on top of Images . . . 590

32.5 Color Conversion . . . 590

33 Audio Processing . . . . 591

(12)

x GNU Octave

34 Object Oriented Programming . . . . 593

34.1 Creating a Class . . . 593

34.2 Manipulating Classes . . . 595

34.3 Indexing Objects . . . 598

34.3.1 Defining Indexing And Indexed Assignment . . . 599

34.3.2 Indexed Assignment Optimization . . . 602

34.4 Overloading Objects . . . 603

34.4.1 Function Overloading . . . 603

34.4.2 Operator Overloading . . . 605

34.4.3 Precedence of Objects . . . 606

34.5 Inheritance and Aggregation . . . 607

35 GUI Development . . . . 613

35.1 I/O Dialogs . . . 613

35.2 Progress Bar . . . 614

35.3 GUI Utility Functions . . . 615

35.4 User-Defined Preferences . . . 616

36 System Utilities . . . . 619

36.1 Timing Utilities . . . 619

36.2 Filesystem Utilities . . . 629

36.3 File Archiving Utilities . . . 637

36.4 Networking Utilities . . . 638

36.4.1 FTP Objects. . . 639

36.4.2 URL Manipulation . . . 639

36.5 Controlling Subprocesses . . . 640

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

36.7 Environment Variables . . . 648

36.8 Current Working Directory . . . 648

36.9 Password Database Functions . . . 649

36.10 Group Database Functions . . . 650

36.11 System Information . . . 650

36.12 Hashing Functions . . . 654

37 Packages . . . . 657

37.1 Installing and Removing Packages . . . 657

37.2 Using Packages . . . 660

37.3 Administrating Packages . . . 661

37.4 Creating Packages . . . 661

37.4.1 The DESCRIPTION File . . . 663

37.4.2 The INDEX File . . . 664

37.4.3 PKG ADD and PKG DEL Directives . . . 665

(13)

xi

Appendix A Dynamically Linked Functions

. . . . 667

A.1 Oct-Files . . . 667

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

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

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

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

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

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

A.1.6.1 The Differences between the Array and Sparse Classes . . . 677

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

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

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

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

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

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

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

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

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

A.2 Mex-Files . . . 690

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

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

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

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

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

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

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

A.3 Standalone Programs . . . 702

Appendix B Test and Demo Functions . . . . 707

B.1 Test Functions . . . 707

B.2 Demonstration Functions . . . 712

Appendix C Tips and Standards . . . . 715

C.1 Writing Clean Octave Programs . . . 715

C.2 Tips on Writing Comments . . . 715

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

C.4 Tips for Documentation Strings . . . 717

(14)

xii GNU Octave

Appendix D Contributing Guidelines . . . . 725

D.1 How to Contribute . . . 725

D.2 Building the Development Sources . . . 725

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

D.4 General Guidelines . . . 727

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

D.6 C++ Sources . . . 729

D.7 Other Sources . . . 730

Appendix E Obsolete Functions . . . . 731

Appendix F Known Causes of Trouble . . . . 735

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

F.2 Reporting Bugs . . . 735

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

F.2.2 Where to Report Bugs . . . 736

F.2.3 How to Report Bugs . . . 736

F.2.4 Sending Patches for Octave . . . 737

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

Appendix G Installing Octave . . . . 739

G.1 Build Dependencies . . . 739

G.1.1 Obtaining the Depencies Automatically . . . 739

G.1.2 Build Tools . . . 739

G.1.3 External Packages . . . 740

G.2 Running Configure and Make . . . 742

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

G.4 Installation Problems . . . 749

Appendix H Emacs Octave Support . . . . 753

H.1 Installing EOS . . . 753

H.2 Using Octave Mode . . . 753

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

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

Appendix I Grammar and Parser . . . . 761

I.1 Keywords . . . 761

I.2 Parser . . . 761

Appendix J GNU GENERAL PUBLIC LICENSE . . . . 763

Concept Index . . . . 775

Function Index . . . . 781

(15)

xiii

Operator Index . . . . 795

(16)
(17)

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 763). 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 Giles Anderson

Joel Andersson Muthiah Annamalai Marco Atzeri

Shai Ayal Roger Banks Ben Barrowes

Alexander Barth David Bateman Heinz Bauschke

Roman Belov Karl Berry David Billinghurst

Don Bindner Jakub Bogusz Moritz Borgmann

Paul Boven Richard Bovey John Bradshaw

Marcus Brinkmann Remy Bruno Ansgar Burchard

Marco Caliari Daniel Calvelo John C. Campbell

Juan Pablo Carbajal Jean-Francois Cardoso Joao Cardoso

Larrie Carr David Castelow Vincent Cautaerts

Clinton Chee Albert Chin-A-Young Carsten Clark

(18)

2 GNU Octave

J. D. Cole Martin Costabel Michael Creel

Jeff Cunningham Martin Dalecki Jorge Barros de Abreu

Carlo de Falco Jacob Dawid Thomas D. Dean

Philippe Defert Bill Denney Fabian Deutsch

Christos Dimitrakakis 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 Michael D. Godfrey

Michael Goffioul Glenn Golden Tomislav Goles

Keith Goodman Brian Gough Steffen Groot

Etienne Grossmann David Grundberg 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 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 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 Arno J. Klaassen Alexander Klein

Geoffrey Knauth Heine Kolltveit Ken Kouno

Kacper Kowalik Daniel Kraft Aravindh Krishnamoorthy

Oyvind Kristiansen Piotr Krzyzanowski Volker Kuhlmann

Tetsuro Kurita Miroslaw Kwasniak Rafael Laboissiere

Kai Labusch Claude Lacoursiere Walter Landry

Bill Lash Dirk Laurie Maurice LeBrun

Friedrich Leisch Jyh-miin Lin Timo Lindfors

Benjamin Lindner Ross Lippert David Livings

Sebastien Loisel Erik de Castro Lopo Massimo Lorenzin

Emil Lucretiu Hoxide Ma James Macnicol

Jens-Uwe Mager Rob Mahurin Ricardo Marranita

Orestes Mas Makoto Matsumoto Tatsuro Matsuoka

Laurent Mazet G. D. McBain Alexander Mamonov

Christoph Mayer Jlio Hoffimann Mendes Thorsten Meyer

Petr Mikulik Stefan Monnier Antoine Moreau

Kai P. Mueller Hannes Mller Victor Munoz

Carmen Navarrete Todd Neal Philip Nienhuis

Al Niessner Rick Niles Takuji Nishimura

(19)

Preface 3

Kai Noda Eric Norum Krzesimir Nowak

Michael O’Brien Peter O’Gorman Thorsten Ohl

Arno Onken Luis F. Ortiz 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 Anthony Richardson

Jason Riedy E. Joshua Rigler Petter Risholm

Matthew W. Roberts Andrew Ross 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

Matthew Tenny Georg Thimm Duncan Temple Lang

Kris Thielemans Olaf Till Christophe Tournery

Thomas Treichl Karsten Trulsen Frederick Umminger

Utkarsh Upadhyay Stefan van der Walt Peter Van Wieren

James R. Van Zandt Gregory Vanuxem Ivana Varekova

Thomas Walter Andreas Weber Olaf Weber

Thomas Weber 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).

(20)

4 GNU Octave

• 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.orgdomain 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.

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 725, 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

(21)

Preface 5

improve Octave. See Appendix F [Trouble], page 735, 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 763.

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

(22)
(23)

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 provides a convenient interactive command line interface for solving linear and nonlinear problems numerically, and for performing other numerical experiments. It may also be used as a batch-oriented language for data processing.

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 inAppendix J [Copying], page 763.

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.6.1.

1.1 Running Octave

On most systems, Octave is started with the shell command ‘octave’. Octave displays an initial message and then a prompt indicating it is ready to accept input. You can begin typing Octave commands immediately afterward.

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 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)

(24)

8 GNU Octave

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 ATA, 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−1b, 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.

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

H2+ O2→ H2O

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:

(25)

Chapter 1: A Brief Introduction to Octave 9 x1H2+ x2O2→ H2O

H : 2x1+ 0x2→ 2 O : 0x1+ 2x2→ 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 = t0) = x0

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)

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.

(26)

10 GNU Octave

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 inSection 2.4 [Command Line Editing], page 23.

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 19.

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,

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

(27)

Chapter 1: A Brief Introduction to Octave 11

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 in Section 2.3 [Getting Help], page 19.

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)

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

(28)

12 GNU Octave

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: wrong type argument ‘matrix’

1.3.5 Format of Descriptions

Functions, commands, and variables 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, variable, 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.

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.

SeeSection 11.8 [Function Files], page 167.

Built-in Function

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

(29)

Chapter 1: A Brief Introduction to Octave 13

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 [Dynamically Linked Functions], page 667.

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.

1.3.5.3 A Sample Variable Description

A variable is a name that can hold a value. Although any variable can be set by the user, built-in variables typically exist specifically so that users can change them to alter the way Octave behaves (built-in variables are also sometimes called user options). Ordinary variables and built-in variables are described using a format like that for functions except that there are no arguments.

Here is a description of the imaginary variable do_what_i_mean_not_what_i_say.

[Built-in Variable]

do_what_i_mean_not_what_i_say

If the value of this variable is nonzero, Octave will do what you actually wanted, even if you have typed a completely different and meaningless list of commands.

Other variable descriptions have the same format, but ‘Built-in Variable’ is replaced by

‘Variable’, for ordinary variables, or ‘Constant’ for symbolic constants whose values cannot be changed.

(30)
(31)

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.

--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.

--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.

--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

(32)

16 GNU Octave

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, seeAppendix H [Emacs Octave Support], page 753.

--line-editing

Force readline use for command-line editing.

--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.

--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.

(33)

Chapter 2: Getting Started 17

--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

default_save_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 --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. SeeSection 2.6 [Executable Octave Programs], page 33, 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.

(34)

18 GNU Octave

[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 33, for an example of how to create an executable Octave script.

See also: [program name], page 17.

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 106, for an explanation of how to retrieve objects from cell arrays, and Section 11.1 [Defining Functions], page 157, for information about the variable nargin.

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’.

(35)

Chapter 2: Getting Started 19

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.

[Built-in Function]

atexit (fcn)

[Built-in Function]

atexit (fcn,flag)

Register a function to be called when Octave exits. For example, function last_words ()

disp ("Bye bye");

endfunction

atexit ("last_words");

will print the message "Bye bye" when Octave exits.

The additional argument flag will register or unregister fcn from the list of functions to be called when Octave exits. If flag is true, the function is registered, and if flag is false, it is unregistered. For example, after registering the function last_words above,

atexit ("last_words", false);

will remove the function from the list and Octave will not call last_words when it exits.

Note that atexit only removes the first occurrence of a function from the list, so if a function was placed in the list multiple times with atexit, it must also be removed from the list multiple times.

2.3 Commands for Getting Help

The entire text of this manual is available from the Octave prompt via the command doc.

In addition, the documentation for individual user-written functions and variables is also available via the help command. This section describes the commands used for reading the manual and the documentation strings for user-supplied functions and variables. See

(36)

20 GNU Octave

Section 11.8 [Function Files], page 167, for more information about how to document the functions you write.

[Command]

help name

[Command]

help --list

Display the help text for name. For example, the command help help prints a short message describing the help command.

Given the single argument --list, list all operators, keywords, built-in functions, and loadable functions available in the current session of Octave.

If invoked without any arguments, help display instructions on how to access help from the command line.

The help command can give you information about operators, but not the comma and semicolons that are used as command separators. To get help for those, you must type help comma or help semicolon.

See also: [doc], page 20,[lookfor], page 20,[which], page 122.

[Command]

doc function_name

Display documentation for the function function name directly from an on-line ver- sion of the printed manual, using the GNU Info browser. If invoked without any arguments, the manual is shown from the beginning.

For example, the command doc rand starts the GNU Info browser at the rand node in the on-line version of the manual.

Once the GNU Info browser is running, help for using it is available using the com- mand C-h.

See also: [help], page 20.

[Command]

lookfor str

[Command]

lookfor -allstr

[Function File]

[func, helpstring ] = lookfor (str)

[Function File]

[func, helpstring ] = lookfor (’-all’,str)

Search for the string str in all functions found in the current function search path.

By default, lookfor searches for str in the first sentence of the help string of each function found. The entire help text of each function can be searched if the ’-all’

argument is supplied. All searches are case insensitive.

Called with no output arguments, lookfor prints the list of matching functions to the terminal. Otherwise, the output arguments func and helpstring define the matching functions and the first sentence of each of their help strings.

The ability of lookfor to correctly identify the first sentence of the help text is depen- dent on the format of the function’s help. All Octave core functions are correctly for- matted, but the same can not be guaranteed for external packages and user-supplied functions. Therefore, the use of the ’-all’ argument may be necessary to find related functions that are not a part of Octave.

See also: [help], page 20,[doc], page 20,[which], page 122.

To see what is new in the current release of Octave, use the news function.

(37)

Chapter 2: Getting Started 21

[Function File]

news (package)

Display the current NEWS file for Octave or installed package.

If package is the name of an installed package, display the current NEWS file for that package.

[Function File]

info ()

Display contact information for the GNU Octave community.

[Built-in Function]

warranty ()

Describe the conditions for copying and distributing Octave.

The following functions can be used to change which programs are used for displaying the documentation, and where the documentation can be found.

[Built-in Function]

val = info_file ()

[Built-in Function]

old_val = info_file (new_val)

[Built-in Function]

info_file (new_val,"local")

Query or set the internal variable that specifies the name of the Octave info file. The default value is ‘octave-home /info/octave.info’, in which octave-home is the root directory of the Octave installation. The default value may be overridden by the en- vironment variable OCTAVE_INFO_FILE, or the command line argument ‘--info-file NAME’.

When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.

See also: [info program], page 21,[doc], page 20,[help], page 20,[makeinfo program], page 21.

[Built-in Function]

val = info_program ()

[Built-in Function]

old_val = info_program (new_val)

[Built-in Function]

info_program (new_val,"local")

Query or set the internal variable that specifies the name of the info program to run.

The default value is ‘octave-home /libexec/octave/version /exec/arch /info’

in which octave-home is the root directory of the Octave installation, version is the Octave version number, and arch is the system type (for example, i686-pc-linux-gnu). The default value may be overridden by the environment variable OCTAVE_INFO_PROGRAM, or the command line argument ‘--info-program NAME’.

When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.

See also: [info file], page 21, [doc], page 20, [help], page 20, [makeinfo program], page 21.

[Built-in Function]

val = makeinfo_program ()

[Built-in Function]

old_val = makeinfo_program (new_val)

(38)

22 GNU Octave

[Built-in Function]

makeinfo_program (new_val,"local")

Query or set the internal variable that specifies the name of the program that Octave runs to format help text containing Texinfo markup commands. The default value is makeinfo.

When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.

See also: [info file], page 21,[info program], page 21,[doc], page 20,[help], page 20.

[Built-in Function]

val = doc_cache_file ()

[Built-in Function]

old_val = doc_cache_file (new_val)

[Built-in Function]

doc_cache_file (new_val,"local")

Query or set the internal variable that specifies the name of the Octave documentation cache file. A cache file significantly improves the performance of the lookfor com- mand. The default value is ‘octave-home /share/octave/version /etc/doc-cache’, in which octave-home is the root directory of the Octave installation, and version is the Octave version number. The default value may be overridden by the environment vari- able OCTAVE_DOC_CACHE_FILE, or the command line argument ‘--doc-cache-file NAME’.

When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.

See also: [lookfor], page 20, [info program], page 21,[doc], page 20, [help], page 20, [makeinfo program], page 21.

[Built-in Function]

val = suppress_verbose_help_message ()

[Built-in Function]

old_val = suppress_verbose_help_message (new_val)

[Built-in Function]

suppress_verbose_help_message (new_val,"local")

Query or set the internal variable that controls whether Octave will add additional help information to the end of the output from the help command and usage messages for built-in commands.

When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.

The following functions are principally used internally by Octave for generating the docu- mentation. They are documented here for completeness and because they may occasionally be useful for users.

[Function File]

gen_doc_cache (out_file,directory)

Generate documentation caches for all functions in a given directory.

A documentation cache is generated for all functions in directory. The resulting cache is saved in the file out file. The cache is used to speed up lookfor.

If no directory is given (or it is the empty matrix), a cache for builtin operators, etc.

is generated.

See also: [lookfor], page 20,[path], page 171.

(39)

Chapter 2: Getting Started 23

[Loadable Function]

[text, format ] = get_help_text (name) Return the raw help text of function name.

The raw help text is returned in text and the format in format The format is a string which is one of "texinfo", "html", or "plain text".

[Loadable Function]

[text, format ] = get_help_text_from_file (fname) Return the raw help text from the file fname.

The raw help text is returned in text and the format in format The format is a string which is one of "texinfo", "html", or "plain text".

[Function File]

[text, status ] = get_first_help_sentence (name)

[Function File]

[text, status ] = get_first_help_sentence (name,max_len) Return the first sentence of a function’s help text.

The first sentence is defined as the text after the function declaration until either the first period (".") or the first appearance of two consecutive newlines ("\n\n"). The text is truncated to a maximum length of max len, which defaults to 80.

The optional output argument status returns the status reported by makeinfo. If only one output argument is requested, and status is non-zero, a warning is displayed.

As an example, the first sentence of this help text is

get_first_help_sentence ("get_first_help_sentence")

a ans = Return the first sentence of a function’s help text.

2.4 Command Line Editing

Octave uses the GNU Readline library to provide an extensive set of command-line editing and history features. Only the most common features are described in this manual. In addition, all of the editing functions can be bound to different key strokes at the user’s discretion. This manual assumes no changes from the default Emacs bindings. See the GNU Readline Library manual for more information on customizing Readline and for a complete feature list.

To insert printing characters (letters, digits, symbols, etc.), simply type the character.

Octave will insert the character at the cursor and advance the cursor forward.

Many of the command-line editing functions operate using control characters. For ex- ample, the character Control-a moves the cursor to the beginning of the line. To type C-a, hold down CTRL and then press A. In the following sections, control characters such as Control-a are written as C-a.

Another set of command-line editing functions use Meta characters. To type M-u, hold down the META key and press U. Depending on the keyboard, the META key may be labeled ALT or even WINDOWS. If your terminal does not have a META key, you can still type Meta characters using two-character sequences starting with ESC. Thus, to enter M-u, you would type ESC U. The ESC character sequences are also allowed on terminals with real Meta keys. In the following sections, Meta characters such as Meta-u are written as M-u.

Riferimenti

Documenti correlati

In ciascuna riga gli elementi sono elencati da sinistra a destra Elementi nella stessa riga sono separati da uno spazio o una virgola. Le righe sono separate da new line o

Abstract We have implemented in Matlab/Octave two fast algorithms for bivariate Lagrange interpolation at the so-called Padua points on rectangles, and the corresponding versions

per dire di cercare il file in tale direttorio, quindi richiamare il file generato, dando il nome del file stesso:.

  In the help text of Matlab functions, function names and variables are in capital letters.. ➛ Don't

In the next video I’ll show you how, again, with one or two lines of code using Octave, you can quickly visualize your data or plot your data and use that picture to better

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

imagesc(M) Prende in input una matrice e restituisce un grafico con i quadretti colorati in funzione del valore contenuto nella cella.. roots(p) Restituisce le radici del

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