# O-Matrix Manual

O-Matrix Version 6
a: Contents
Getting Started: 2
Basic Concepts: 3
Expressions: 4
Controlling Program Flow: 5
Elementary Functions: 6
Working with Rows, Columns and Sub-Blocks of Matrices: 7
Strings, Searching and Sorting: 9
Graphics, Plotting, and Data Visualization: 10
User-Defined Functions: 11
Linear Algebra: 12
Curve Fitting, Optimization, and Derivatives: 13
FFTs, Filtering and Time Series: 14
Statistics and Statistical Distributions: 15
Special Functions: 16
Integration And Differential Equations: 17
Polynomials: 18
Graphical User Interface Programming: 19
O-Matrix Code Debugger: 21
Linking With Other Languages, Programs and COM Components: 22
The O-Matrix Development Kit: 23
Appendix: 24
Mlmode: MATLAB® Compatibility: 25
Glossary: 26
Alphabetic Listing of Cross Reference Tags: 27
Keyword Index: 28
O-Matrix Version 6: Omatrix6:
Getting Started: starting: 2
Starting O-Matrix: start: 2.3
Example Navigator: exnav: 2.4
The O-Matrix User Interface: omgui: 2.5
The Command Line: cmdline: 2.5.1
The Command Window: commandio: 2.5.2
Graphics Windows: graphicio: 2.5.3
The Debugger Window: debugio: 2.5.4
The O-Matrix Toolbar: omtoolbar: 2.5.6
Editor Windows: editorio: 2.5.7
The O-Matrix Help System: gethelp: 2.6
Customizing the Initial State of O-Matrix: customizing: 2.7
Finding Text in Files: findinfiles: 2.8
Exiting O-Matrix: exiting: 2.9
O-Matrix Tutorial: Tutorial: 2.10
Interactive GUI Tools: demo: 2.11
A Dialog for Plotting Files: fileplotdlg: 2.11.1
A Linear Least Squares Fitting Dialog: linlsqdlg: 2.11.2
A Dialog for Fitting Polynomials: polfitdlg: 2.11.3
Theoretical and Estimated Response for a Digital Filter: digfilter: 2.11.4
Basic Concepts: basic: 3
Assigning Values To Variables: assignment: 3.1
Starting A New Program: clear: 3.2
Assigning Values To Constants: const: 3.3
Representing Matrix Elements In Program Input: elements: 3.4
The Mathematical constant Pi: pi: 3.5
Building Matrices: building: 3.6
Terminating An O-Matrix Session: exit: 3.7
Explicit Inclusion of Commands or Functions from a File: include: 3.8
Implicit Inclusion of Commands or Functions from a File: auto_include: 3.9
Comments and Statement Continuation: comment: 3.10
Default Printing Of An Expression: printexp: 3.11
Printing A List Of Expressions: print: 3.12
Suspending Program Execution And Entering Debugger: stop: 3.13
Determining The Column Dimension Of A Matrix: coldim: 3.14
Determining The Row Dimension Of A Matrix: rowdim: 3.15
Determining the Dimensions of a Matrix: size: 3.16
Changing Matrix Dimensions: dim: 3.17
Copying and Changing the Dimensions of a Matrix: reshape: 3.18
Expressions: expression: 4
Positive Sign: positive: 4.1
Negative Sign: negative: 4.2
Automatic Conversion To A Higher Type: coercion: 4.4
Subtraction: subtraction: 4.5
Element-By-Element Multiplication: multiplication: 4.6
Element-By-Element Division: division: 4.7
Testing Numeric And Logical Equality: equality: 4.8
Ordered Numeric And Logical Comparisons: ordered: 4.9
Logical Operators: logicalOperator: 4.10
Matrix Multiplication: matrixMultiplication: 4.11
Linear Equations and Least Squares: matrixDivision: 4.12
Element-By-Element Exponentiation: exponentiation: 4.13
Matrix Transpose: transpose: 4.14
The Norm Operator: norm: 4.15
Testing String Equality: stringEquality: 4.16
Ordered String Comparisons: stringOrdered: 4.17
Sequence Operator: sequence: 4.18
Order Of Operations: operationOrder: 4.19
Controlling Program Flow: flow: 5
If Statement: if: 5.1
Grouping A Sequence Of Statements As A Block: block: 5.2
For Statement: for: 5.3
While Statement: while: 5.4
Breaking Out Of For And While Loops: break: 5.5
Transferring Control Using The Goto Statement: goto: 5.6
Halting Program Execution: halt: 5.7
Elementary Functions: elementary: 6
Algebraic Functions: algebraic: 6.1
Absolute Value Function: abs: 6.1.1
The Square Root Function: sqrt: 6.1.2
Determining The Maximum Element of a Matrix: max: 6.1.3
Determining The Indices Of The Maximum Element: pmax: 6.1.4
Computing The Maximum Element From Multiple Matrices: maxs: 6.1.5
Computing The Minimum Element From Multiple Matrices: mins: 6.1.6
The Complex Conjugate Function: conj: 6.1.7
The Imaginary Part Function: imag: 6.1.8
The Sign Function: sign: 6.1.9
Largest Integer Less Than or Equal a Specified Value: floor: 6.1.10
Smallest Integer Greater Than or Equal a Specified Value: ceil: 6.1.11
Rounding of to the Nearest Integer Value: round: 6.1.12
Rounding Numbers To The Nearest Integer: roundoff: 6.1.13
Modulo Function: mod: 6.1.14
Remainder Function: rem: 6.1.15
Undo The Modulo Function: colunmod: 6.1.16
Unwrap Angles To Absolute Angles Above Two Pie: unwrap: 6.1.17
The Factorial Function: factorl: 6.1.18
Computing Prime Numbers: primes: 6.1.19
Transcendental Functions: transcendental: 6.2
Inverse Cosine Function: acos: 6.2.1
Inverse Sine Function: asin: 6.2.2
Inverse Tangent Function: atan: 6.2.3
Cosine Function: cos: 6.2.4
Hyperbolic Cosine Function: cosh: 6.2.5
Exponential Function: exp: 6.2.6
Natural Logarithm Function: log: 6.2.7
Base Ten Logarithm Function: log10: 6.2.8
Sine Function: sin: 6.2.9
Hyperbolic Sine Function: sinh: 6.2.10
Tangent Function: tan: 6.2.11
Hyperbolic Tangent Function: tanh: 6.2.12
Base Two Logarithm Function: log2: 6.2.13
Base Two Exponentiation Function: pow2: 6.2.14
Inverse Tangent Function With Two Arguments: atan2: 6.2.15
Angle Corresponding to a Complex Value: angle: 6.2.16
Inverse Hyperbolic Sine Function: asinh: 6.2.17
Inverse Hyperbolic Cosine Function: acosh: 6.2.18
Inverse Hyperbolic Cotangent Function: acoth: 6.2.19
Hyperbolic Cotangent Function: coth: 6.2.20
Inverse Hyperbolic Tangent Function: atanh: 6.2.21
Square Root of Sum of Squares: hypot: 6.2.22
Special Matrices: specialmatrices: 6.3
Obtaining A Copy Of The Identity Matrix: identity: 6.3.1
Creating A Matrix Of Zeros: zeros: 6.3.2
Creating A Matrix Of Ones: ones: 6.3.3
Filling A Matrix With Copies of Another Matrix: fill: 6.3.4
Filling A Matrix With A Column Vector: fillcols: 6.3.5
Filling A Matrix With A Row Vector: fillrows: 6.3.6
Generating A Sequence Of Integers: seq: 6.3.7
Constructing Toeplitz Matrices: toeplitz: 6.3.8
Vandermonde Matrix: vander: 6.3.9
Hankel Matrix: hankel: 6.3.10
Hilbert Matrix: hilb: 6.3.11
Exact Inverse of a Hilbert Matrix: invhilb: 6.3.12
The Diagonal Function: diag: 6.3.13
Lower Triangular Part of a Matrix: tril: 6.3.14
Upper Triangular Part of a Matrix: triu: 6.3.15
The Novalue Type In O-Matrix: novalue: 6.3.16
Matrix Type Functions: matrixType: 6.4
Determining The Type Of An Expression: type: 6.4.1
Conversion To Integer: int: 6.4.2
Conversion To Single-Precision: real: 6.4.3
Conversion To Double-Precision: double: 6.4.4
Element-By-Element Conversion To Complex: complex: 6.4.5
Element-By-Element Conversion To Character: char: 6.4.6
Conversion To Logical: logical: 6.4.7
Matching The Types Of Two Matrices: matchtype: 6.4.8
System Functions: systemFunctions: 6.5
Elapsed Time Since Start of Session: time: 6.5.1
Determining The Date and Time: clock: 6.5.2
Starting and Reading an Elapsed Timer: tictoc: 6.5.3
Starting Another Process: system: 6.5.4
Getting And Setting The Current Working Directory: cwd: 6.5.5
Listing the Names of Files in a Directory: listdir: 6.5.6
Listing A Directory And All Its Subdirectories: listdirs: 6.5.7
Renaming A File: mvfile: 6.5.8
Removing A File: rmfile: 6.5.9
Removing A Directory: rmdir: 6.5.10
Removing A Directory And All Its Subdirectories: rmdirs: 6.5.11
Determining If There Is A Directory With A Specified Name: isdir: 6.5.12
Determines If Value Represents a Complete File Name: isfullpath: 6.5.13
Creates a Full Path File Name: fullpath: 6.5.14
Creating A Directory: mkdir: 6.5.15
Checking For A File Or Directory: exists: 6.5.16
Determining The Length Of A File: lenfile: 6.5.17
Copying Files: cpfile: 6.5.18
Creating A Temporary File Name: tempfile: 6.5.19
Slowing or Suspending Execution: sleep: 6.5.20
O-Matrix Version Specification: version: 6.5.21
Clearing the Command Window: clc: 6.5.22
Setting the Font for Editors: editorfont: 6.5.23
Generating Sounds: beep: 6.5.24
Getting an Environment Variable: getenv: 6.5.25
Checking For Certain Conditions: conditions: 6.6
Determining if All Elements are True: all: 6.6.1
Determining if All Elements are True (Mlmode): mlmode_all: 6.6.2
Determining if Any Elements are True: any: 6.6.3
Determining if Any Elements are True (Mlmode): mlmode_any: 6.6.4
Number of Nonzero Elements: nnz: 6.6.5
Checking For Matrix Equality: equal: 6.6.6
Determining Which Values Have Full Precision: fullprec: 6.6.7
Determines if a Matrix is Empty: isempty: 6.6.8
Checking For Matrix Equality: isequal: 6.6.9
Determines If All Elements Have Zero Imaginary Part: isreal: 6.6.10
Determines If Value is Numeric-Valued Scalar: isnumscalar: 6.6.11
Determines If Value is Character Matrix: ischarmatrix: 6.6.12
Determines If Value is Character Vector: ischarvector: 6.6.13
Determines If Value is Logical Scalar: islogicalscalar: 6.6.14
Determines If Value is Numeric Matrix: isnummatrix: 6.6.15
Determines If Value is a Numeric Vector: isnumvector: 6.6.16
Determines Which Elements Are Finite: isfinite: 6.6.17
Determines Which Elements Are Infinite: isinf: 6.6.18
Determines Which Elements Are Not A Number: isnan: 6.6.19
Determines If This is a Light Version of O-Matrix: islight: 6.6.20
Determines If This is an O-Matrix Run-Time Engine Version: isrte: 6.6.21
Determines If This is a O-Matrix Developer Version: isdeveloper: 6.6.22
The Binary Logical Exclusive Or Operation: xor: 6.7
Smallest Power of Two Greater or Equal a Specified Value: nextpow2: 6.8
Evenly Spaced Grid With a Specified Number of Points: linspace: 6.9
Create a Grid With Evenly Spaced Logarithms: logspace: 6.10
Difference Between Successive Elements In Each Column: coldiff: 6.11
Finite Differences of Arbitrary Order: diff: 6.12
Replaces Zero By a Small Value: nozero: 6.13
Working with Rows, Columns and Sub-Blocks of Matrices: submatrices: 7
Elements Of A Vector: vectorelem: 7.1
Elements Of A Matrix: matrixelem: 7.2
Accessing A Single Row Or Column: rowcol: 7.3
Accessing Sequential Rows Or Columns: seqrowcol: 7.4
Sequential Elements Of A Vector: seqsubvec: 7.5
Accessing A Subblock Of A Matrix: subblock: 7.6
Accessing Non-sequential Rows And Columns: nonseq: 7.7
Vector Indices: vecind: 7.8
Using End As An Index Value: endexp: 7.9
Changing Matrix Indices: base: 7.10
Determining The Base Column Index Of A Matrix: colbase: 7.11
Determining The Base Row Index Of A Matrix: rowbase: 7.12
Reading And Writing Data: io: 8
Determining The Number Of Matrix Rows In A File: nrows: 8.1
Determining The Number Of Columns In Each Row Of A File: ncols: 8.2
Specifying Value to be Used for Missing Input Data: read7: 8.9
Writing a Matrix to the Screen or a File: write: 8.10
Specifying Number of Elements per Output Line: write3: 8.11
Specifying Value for Separating File Output Data: writesep: 8.12
Closing Files: close: 8.13
Detecting End of File: eof: 8.14
Writing an O-Matrix Native Format Binary File: omwrite: 8.15
Setting and Getting Output Formats: IOformat: 8.17
Getting An Output Format: format: 8.17.1
Setting The Integer Output Format: formatint: 8.17.2
Setting Floating Point Output Formats: formatfloat: 8.17.3
Set Printing and Tracing Options: setprint: 8.17.4
Writing Excel Data: xlwrite: 8.19
Getting Excel Worksheet Names: xlsheets: 8.20
Writing Binary Files: bwrite: 8.23
Writing HDF Data: h5write: 8.26
Saving Output Written in Command Window: diary: 8.27
Listing the Variables in a MAT-File: mfvars: 8.28.2
Reading and Writing to Network Folders: netio: 8.29
Reading Data from the Internet: urlget: 8.30
Transferring Files Over the Internet Using FTP: ftp: 8.31
open - Opening an ftp Connection to a Remote Host: openftp: 8.31.1
close - Closing the ftp Connection to a Remote Host: closeftp: 8.31.2
get - Retrieving a File From a Remote Host: getftp: 8.31.3
put - Transferring a File To a Remote Host: putftp: 8.31.4
ls - Listing File and Directory Names On a Remote Host: lsftp: 8.31.5
delete - Deleting a File on a Remote Host: delftp: 8.31.6
cd - Changing Directories on a Remote Host: cdftp: 8.31.7
type - Setting the File Transfer Type: typeftp: 8.31.8
Strings, Searching and Sorting: stringssort: 9
Lining Up Data Fields In A Character Matrix: align: 9.1
Converting ASCII Numbers To Double-Precision Column Vector: atod: 9.2
Converting ASCII Numbers To Integer: atoi: 9.3
Conversion of Text Matrix to a Double Precision Matrix: char2dbl: 9.4
Converting A Number To ASCII Characters: ntoa: 9.5
Conversion of Numeric Matrix to Character Matrix: num2str: 9.6
Converting a Character Matrix to a Numeric Matrix: str2num: 9.7
Substituting Strings in Character Matrices: strreplace: 9.8
Removing Trailing Spaces: strclip: 9.9
Remove Leading and Trailing Spaces: clipstr: 9.10
Converting Lower Case to Upper Case: low2up: 9.11
Converting Upper Case to Lower Case: up2low: 9.12
Surrounding Text in Quotes: dquote: 9.13
Converts a Text File to a Character Row Vector: file2str: 9.14
Packs An Entire Character Matrix Into One Row Vector: pack: 9.15
Unpacks A Character Matrix From a Row Vector: unpack: 9.16
Convert a Character Row Vector to a Valid O-Matrix Identifier: char2id: 9.17
Replacing a Row of a Character Matrix: reprow: 9.18
Map All Occurrences of a String In a Directory: str2strdir: 9.19
Sorting Rows Of A Matrix: sort: 9.20
Sorting Rows With a Specified Key: sort3: 9.21
Sorting The Rows Of A Matrix By Pointers: psort: 9.22
Specifying Sort Key When Sorting By Pointers: psort3: 9.23
Sorting (Mlmode): mlmode_sort: 9.24
Reversing Row Order Of A Matrix: reverse: 9.25
Flipping the Row Order of a Matrix: flipud: 9.26
Flipping the Column Order of a Matrix: fliplr: 9.27
Rotate A Matrix By a Multiple of 90 Degrees: rot90: 9.28
Obtaining the Nonzero Elements of a Matrix: nonzeros: 9.29
Determining Indices Corresponding to Nonzero Elements: find: 9.30
Determining Indices Where A Text Pattern Occurs: find2: 9.31
Determining Indices Where A Character Is Between Limits: find3: 9.32
Conversion From Decimal to Hexadecimal: dec2hex: 9.33
Conversion From Hexadecimal to Decimal: hex2dec: 9.34
Searching Strings and Matrices using Regular Expressions: findstr: 9.35
Matching Rows of A Character Matrix: whichrow: 9.36
Graphics, Plotting, and Data Visualization: graphics: 10
Basic Graphics: basicGraphics: 10.1
Drawing Line Plots: gplot: 10.1.1
Drawing Line Plots With Specified Style: gplotstyle: 10.1.2
Drawing Line Plots Z denoted by Color: gplotlevels: 10.1.3
Setting Z Values Corresponding To Color Changes In Plots: glevel: 10.1.4
Initializing Graphic: ginit: 10.1.5
Setting The Line Plotting Style: gstyle: 10.1.6
Printing A Graphic Window: gprint: 10.1.7
Copying A Graphic Window To The Clipboard: gcopy: 10.1.8
Saving a Graphic to a File: gsave: 10.1.9
Line Color Sequence For The Current Viewport: gcolor: 10.1.10
Creating A New Graphics Window: gaddwin: 10.1.11
Specifying A Graphics Window's Caption: gaddwin1: 10.1.12
Specifying A Graphics Window's Geometry: gaddwin2: 10.1.13
Specifying A Graphics Window's Call Back Command: gaddwin3: 10.1.14
Specifying A Graphics Window's Initial Style: gaddwin4: 10.1.15
Using Identifier To Switch Between Graphic Windows: gwin: 10.1.16
Listing Graphic Window Identifiers: glistwin: 10.1.17
Creating A New Viewport In The Current Graphic Window: gaddview: 10.1.18
Setting Various Viewport Options: setview: 10.1.19
Using Identifier To Switch Between Graphic Viewports: gview: 10.1.20
Using Location To Switch Between Graphic Viewports: gview2: 10.1.21
Listing Viewport Identifiers For Current Graphic Window: glistview: 10.1.22
Clearing The Current Viewport: ginitview: 10.1.23
Deleting A Viewport: gdelview: 10.1.24
Removes The Border Around The Current Viewport: gdelborder: 10.1.26
Determining If There Is A Border Around Current Viewport: gborder: 10.1.27
Updating The Current Graphic Window: gupdate: 10.1.28
Axis Labeling And Manipulation: axis: 10.2
Defining A Title For Current Viewport: gtitle: 10.2.1
Defining A Title For An Axis In The Current Viewport: gxyztitle: 10.2.2
Setting Axis Parameters: gxyzaxis: 10.2.3
Setting Axis Minimum and Maximum: gxyzaxis3: 10.2.4
Setting Major Intervals On An Axis: gxyzaxis4: 10.2.5
Setting Minor Intervals On An Axis: gxyzaxis5: 10.2.6
Autoscaling Multiple Plots To Same Axis Limits: axiscale: 10.2.7
Two Scalings For Both X and Y Axis: g2scale: 10.2.8
Specifying Numeric Format For Tick Mark Labels: gtickform: 10.2.9
Specifying Tick Mark Locations: gtickloc: 10.2.10
Specifying Nonnumeric Tick Mark Labels: gticklabel: 10.2.11
Including A Grid In A Plot: gxygrid: 10.2.12
Setting The Axis Intercept Point For A Viewport: gintercept: 10.2.13
Using The Mouse To Specify A Graphic Window Location: gcoord: 10.2.14
Converting Plotting Coordinates To A Graphic Window Location: gcoord2: 10.2.15
Placing Text In The Current Graphic Window: gaddtext: 10.2.16
Listing Text In The Current Graphics Window: glisttext: 10.2.17
Removing Text From The Current Graphics Window: gdeltext: 10.2.18
Setting Graphics Text Font Type Face: gfont: 10.2.19
Setting Graphics Text Font Size: gfont2: 10.2.20
Setting Graphics Text Font Color: gfont3: 10.2.21
Setting Graphics Text Font Styles: gfont4: 10.2.22
Determining Available Font Names: gfontname: 10.2.23
Adjusting The Space Around The Plotting Region: gspace: 10.2.24
Setting Plotting Window Aspect Ratio: gaspect: 10.2.25
Plotting Functions Of Two Variables: fun2var: 10.3
Contour Plots: contour: 10.3.1
Specifying Contour Levels: contour2: 10.3.2
Specifying X And Y Values In A Contour Plot: contour4: 10.3.3
Specifying Plane For A Contour Plot: contour5: 10.3.4
Hiding Lines Behind A Contour Plot: contour6: 10.3.5
Mesh And Surface Plots: mesh: 10.3.6
Specifying Line Color In Mesh And Surface Plots: mesh2: 10.3.7
Specifying X and Y Values In Mesh And Surface Plots: mesh4: 10.3.8
Specifying Plotting Style In Mesh And Surface Plots: mesh5: 10.3.9
Rotating Plotting Axis: grotate: 10.3.10
Special Plots: specialplots: 10.4
Plotting Error Bars: errorbar: 10.4.1
Plotting Vectors: garrow: 10.4.2
Plotting Histograms: ghist: 10.4.3
Plotting A Bar Graph With Different Width Bars: gbar: 10.4.4
Plotting A Bar Graph With Uniform Width Bars: bar: 10.4.5
Plotting A Stair Graph: gstair: 10.4.6
Plotting In Polar Coordinates: polar: 10.4.7
Plotting a Smith Chart: smith: 10.4.8
Plotting The Response Of A Continuous Filter: fcplot: 10.4.9
Plotting The Response Of A Digital Filter: fdplot: 10.4.10
Line Plots Using One Command: plot: 10.5
Using Tecplot with O-Matrix: tecplot: 10.6
Line Color Sequence for XY Plots: tpcolors: 10.6.2
Creating Contour Plots: tpcontour: 10.6.3
Creating Tecplot Data Sets: tpdataset: 10.6.4
Getting Dataset and Zone Dimensions: tpdims: 10.6.5
Creating Image Files: tpexport: 10.6.6
Popping, Creating and Obtaining Frame Names: tpframe: 10.6.7
Transferring Data from Tecplot to O-Matrix: tpget: 10.6.8
Transferring Volume Data from Tecplot to O-Matrix: tpget3D: 10.6.9
Creating Histograms: tphist: 10.6.10
Running a Tecplot Macro File: tpmacrofile: 10.6.11
Running a Tecplot Macro String: tpmacrostring: 10.6.12
Copying Maps in a Data Set: tpmapcopy: 10.6.13
Determining the Number of Maps in the Current Frame: tpmapcount: 10.6.14
Opening Tecplot Data, Layout and Style Files: tpopen: 10.6.15
Creating XY Plots: tpplot: 10.6.16
Setting and Retrieving Current Frame Plot Type: tpplottype: 10.6.17
Printing the Current Frame: tpprint: 10.6.18
Transferring Data from O-Matrix to Tecplot: tpput: 10.6.19
Transferring Data from O-Matrix to a Tecplot Volume: tpput3D: 10.6.20
Checking if Tecplot is Running: tprunning: 10.6.21
Connecting with a Tecplot Server: tpstart: 10.6.22
Creating Surface Plots: tpsurface: 10.6.23
Setting Symbol Style for XY Plots: tpsymbols: 10.6.24
Obtaining a Variable Name from Variable Number: tpvarname: 10.6.25
Obtaining a Variable Number from Variable Name: tpvarnum: 10.6.26
Setting X, Y and Z Axes Minimum, Maximum, and Type: tpxyzaxes: 10.6.27
Setting the Zone for Plot Functions: tpzone: 10.6.28
Obtaining a Zone Name from Zone Number: tpzonename: 10.6.29
Obtaining a Zone Number from Zone Name: tpzonenum: 10.6.30
wtecplot - Writing and Creating Tecplot Files: wtecplot: 10.6.31
rtecplot - Reading Tecplot Files: rtecplot: 10.6.32
A GUI for Manipulating Tecplot Data Files: pltgui: 10.6.33
Data Visualizer for O-Matrix: DataVisualizer: 10.7
Getting Started with Data Visualizer: avstart: 10.7.1
Transferring Data: avput: 10.7.2
Saving Plots with Data: avsave: 10.7.3
Creating XY Plots: avplot: 10.7.4
Creating Image Plots: avimage: 10.7.5
Modifying the Data Visualizer Color Palette: avpalette: 10.7.6
Creating Surface Plots: avsurface: 10.7.7
Setting the Object to be Displayed by Data Visualizer: avpath: 10.7.8
User-Defined Functions: userdefined: 11
Defining Functions: definingfun: 11.1
Returning from a Function: return: 11.2
Clearing Functions: clearfun: 11.3
Defining Functions With Arguments: arguments: 11.4
Number of Arguments in a Function Call: nargin: 11.5
Defining Functions With Variable Numbers Of Arguments: argnumber: 11.6
Using Variables And Constants With Functions: varwithfun: 11.7
Using Recursion: recursion: 11.8
Forward And Joint Reference Of Functions: forward: 11.9
Functions As Arguments: funarguments: 11.10
Defining Functions With Multiple Return Values: multiplereturn: 11.11
Number of Return Values Corresponding to a Function Call: nargout: 11.12
Functions As Variables: funvar: 11.13
Local Variables: localvar: 11.14
Defining Local Functions: localfun: 11.15
Local Variable Functions: localvarfun: 11.16
Executing The Function Corresponding To A String: feval: 11.17
Timing User-Defined Function Execution: profile: 11.18
Linear Algebra: linear: 12
Kronecker Tensor Product: kron: 12.1
Inverting A Square Matrix: inv: 12.2
Computing The Trace Of A Matrix: trace: 12.3
The Determinant Function: det: 12.4
Log Of The Determinant Of A Matrix: logdet: 12.5
Computing The Rank Of A Matrix: rank: 12.6
Computing The Condition Number Of A Matrix: cond: 12.7
Orthogonal Basis for Null Space of a Matrix: null: 12.8
Orthogonal Basis for Range Space of a Matrix: orth: 12.9
Moore-Penrose Pseudo Inverse of a Matrix: pinv: 12.10
Cholesky Factoring Of A Matrix: cholesky: 12.11
Computing The LU Factorization Of A Matrix: lu: 12.12
Singular Value Decomposition: svd: 12.13
Simple Syntax for QR factorization: qr: 12.14
Alternate Syntax for Computing the QR Factorization: qred: 12.15
Eigenvalues and EigenVectors of a General Matrix: eigen: 12.16
Generalized Eigenvalues and Eigenvectors of a General Matrix: geneig: 12.17
Eigenvalues And Eigenvectors Of A Symmetric Matrix: eigsym: 12.18
Computing The Eigenvectors Of A Symmetric Matrix: symeig: 12.19
Schur Factorization: schur: 12.20
Solving A Symmetric Toeplitz System Using Levinson's Algorithm: levinson: 12.21
Solving A Tridiagonal System Of Linear Equations: tridiag: 12.22
Solves a Symmetric Block Tri-Diagonal System of Equations: BlockTriDiag: 12.23
Curve Fitting, Optimization, and Derivatives: fit: 13
Piecewise Linear Interpolation In One Dimension: interp: 13.1
Piecewise Linear Interpolation In One Dimension: interp1: 13.2
Lagrange Polynomial Interpolation: lagrange: 13.3
Least Squares Fit of a Descending Polynomial to Data: polyfit: 13.4
Smoothing Splines Of Arbitrary Order And Dimension: smospl: 13.5
Compute Cubic Spline Coefficients: cubespl: 13.6
Evaluate A Cubic Spline: cubeval: 13.7
Two Dimensional Piecewise Bilinear Interpolation: interp2: 13.8
Two Dimensional Piecewise Bilinear Interpolation (Mlmode): mlmode_interp2: 13.9
Newton's Method For Multiple Nonlinear Equations In One Variable: snewton: 13.10
Brent's Method for Multiple Nonlinear Equations Without Derivatives: brent: 13.11
Singular Linear Least Squares: linlsq: 13.12
Linear Least Squares With Box Constraints: linlsqb: 13.13
Nonlinear Least Squares: nlsq: 13.14
Nonlinear Least Squares With Derivatives: dnlsq: 13.15
Nonlinear least Squares With Box Constraints: nlsqbox: 13.16
Nonlinear Least Squares With Box Constraints and Derivatives: dnlsqb: 13.17
Optimization Without Derivatives Using Conjugate Directions: conjdir: 13.18
Minimization Along A Direction In A Vector Space: minline: 13.21
Solving Linear Complementarity Problems: lemke: 13.22
Quadratic Programming with Inequality and Positive Constraints: Qpos: 13.23
Quadratic Programming with Inequality and Box Constraints: Qbox: 13.24
Quadratic Programming with Equality and Inequality Constraints: Qpro: 13.25
Nonlinear Constrained Optimization by Successive Quadratic Programming: sqp: 13.26
Extended Least Squares: relative: 13.27
Forward Difference Derivative Approximation: fordiff: 13.28
Central Difference Derivative Approximation: cendiff: 13.29
Numerical Derivatives With Automatic Step Size Control: autodiff: 13.30
Testing Calculation of The Derivative of a Function: testder: 13.31
Testing Calculation of The Hessian of a Function: testhess: 13.33
FFTs, Filtering and Time Series: filtering: 14
Fourier Transforms: fourier: 14.1
The Discrete Fourier Transform: dft: 14.1.1
The Inverse Discrete Fourier Transform: idft: 14.1.2
The Centered Finite Fourier Transform: fft: 14.1.3
The Centered Finite Inverse Fourier Transform: ifft: 14.1.4
Forward Fourier Transform of a Double-Precision Vector: dbldft: 14.1.5
Inverse Fourier Transform of a Double-Precision Vector: idbldft: 14.1.6
The Unevenly Spaced Lomb-Fourier Transform: lombft: 14.1.7
Two Dimensional Fourier Transform: fft2d: 14.1.8
Two Dimensional Inverse Fourier Transform: ifft2d: 14.1.9
Two Dimensional Discrete Fourier Transform: dft2d: 14.1.10
Two Dimensional Inverse Discrete Fourier Transform: idft2d: 14.1.11
Circular Shift That Centers a Discrete Fourier Transform: fftshift: 14.1.12
Kalman-Bucy Filtering and Smoothing: kalman_bucy: 14.2
Advancing A Linear Kalman-Bucy Filter One Step At a Time: kalman: 14.2.1
Nonlinear Kalman-Bucy Filtering And Smoothing: itrsmo: 14.2.2
The Affine Kalman Bucy Smoother and Marginal Likelihood: AffineKbs: 14.2.3
Auto-Regressive And Moving Average Filtering: filter: 14.3
Auto-Regressive And Moving Average Filtering (Mlmode): mlmode_filter: 14.4
Simulating An AR Process With A Specified Covariance: arcov: 14.5
Estimating The Fourier Spectrum Of A Random Process: fspec: 14.6
Discrete Prolate Spheroidal Sequences: dpss: 14.7
Computing The Wavelet Transform: wavelet: 14.8
Inverse Wavelet Transform: iwavelet: 14.9
Normalized Butterworth Filter Polynomials: fnbut: 14.10
Normalized Chebyshev Filter Polynomials: fncheb: 14.11
Poles Of A Normalized Butterworth Filter: fnbpole: 14.12
Poles Of A Normalized Chebyshev Filter: fncpole: 14.13
Converting From A Normalized To Continuous Bandpass Filter: fn2cbp: 14.14
Converting From A Normalized To Continuous Lowpass Filter: fn2clp: 14.15
Converting From A Continuous To Digital Filter: fc2dig: 14.16
Converting From A Normalized To Digital Bandpass Filter: fn2dbp: 14.17
Converting From A Normalized To Digital LowPass Filter: fn2dlp: 14.18
Statistics and Statistical Distributions: statistics: 15
Percentiles of Each Column: prctile: 15.1
Compute Tail Probabilities For An F-Statistic: ftail: 15.2
The Probability Density For A T-statistic: tpdf: 15.3
Tail Probability Of A T-Statistic: ttail: 15.4
Inverse Of The Cumulative Distribution For T-Statistic: ittail: 15.5
The Cumulative Normal Distribution Function: cnormal: 15.6
Inverse Of The Cumulative Normal Distribution Function: inormal: 15.7
Generating Uniformly Distributed Pseudo Random Numbers: rand: 15.8
Generating Normally Distributed Pseudo Random Numbers: snormal: 15.9
Seeding Pseudo Random Number Generation: seed: 15.10
Computing The Mean Absolute Deviation Of Each Column: colmad: 15.11
Computing The Mean Squared Deviation Of Each Column: colmse: 15.12
Computing The Range of Data for Each Column: colrange: 15.13
Computing The Mode of Each Column: colmode: 15.14
Computing The Kurtosis of Each Column: kurtosis: 15.15
Computing The Skewness of Each Column: skewness: 15.16
Generating a Random Permutation: randperm: 15.17
Using Time To Seed Random Number Generation: ranseed: 15.18
Simulating a Mean Zero Variance One Uniform Random Variable: unifm0v1: 15.19
Generating Random Numbers with Uniform Distribution: unirnd: 15.20
Generating Random Numbers with Normal Distribution: normrnd: 15.21
Generating Random Numbers with Exponential Distribution: exprnd: 15.22
Generating Random Numbers with Gamma Distribution: gamrnd: 15.23
Generating Random Numbers with Cauchy Distribution: cauchyrnd: 15.24
Generating Random Numbers with Gumbel Distribution: gumbelrnd: 15.25
Generating Random Numbers with Laplace Distribution: laplacernd: 15.26
Generating Random Numbers with Log Normal Distribution: lognrnd: 15.27
Generating Random Numbers with Weibull Distribution: wblrnd: 15.28
Generating Random Numbers with Binomial Distribution: binornd: 15.29
Generating Random Numbers with Poisson Distribution: poissrnd: 15.30
Exponential Probability Density Function: exppdf: 15.31
Exponential Cumulative Distribution Function: expcdf: 15.32
Normal Probability Density Function: normpdf: 15.33
Uniform Probability Density Function: unifpdf: 15.34
Uniform Cumulative Distribution Function: unifcdf: 15.35
Weibull Probability Density Function: wblpdf: 15.36
Weibull Cumulative Density Function: wblcdf: 15.37
Correlation Coefficients Between Columns Of A Matrix: colcor: 15.38
Covariance Between Columns Of A Matrix: colcov: 15.39
Computing The Mean Of Each Column: colmean: 15.40
Computing the Standard Deviation of Each Column: colstd: 15.41
Determining The Maximum Element In Each Column: colmax: 15.42
Determining The Maximum Element In Each Row: rowmax: 15.43
Computing The Sum Of Each Column: colsum: 15.44
Computing The Sum Of Each Row: rowsum: 15.45
Computing The Norm Of Each Column: colnorm: 15.46
Computing The Euclidean Norm Of Each Row Of A Matrix: rownorm: 15.47
Computing The Median: median: 15.48
Computing The Median of Each Column: colmedian: 15.49
Computing The Median Absolute Deviation of Each Column: colmead: 15.50
Computing the Variance of Each Column: colvar: 15.51
Column-wise Correlation Of Matrices Using FFT: corr: 15.52
Column-wise Convolution Of Matrices Using FFT: conv: 15.53
Two Dimensional Convolution Of Matrices Using FFT: conv2: 15.54
Sum of Elements of a Matrix: sum: 15.55
Running Cumulative Sum of Elements of a Matrix: cumsum: 15.56
Product of Elements of a Matrix: prod: 15.57
Running Cumulative Product of Elements of a Matrix: cumprod: 15.58
Special Functions: special: 16
The Error Function: erf: 16.1
The Inverse Error Function: ierf: 16.2
The Complementary Error Function: erfc: 16.3
The Beta Function: beta: 16.4
The Incomplete Beta Function: betai: 16.5
The Gamma Function: gamma: 16.6
The Logarithm Of The Gamma Function: gammln: 16.7
The Incomplete Gamma Function: gammainc: 16.8
The Jn Bessel Function: besselj: 16.9
The Yn Bessel Function: bessely: 16.10
The In Bessel Function: besseli: 16.11
The Kn Bessel Function: besselk: 16.12
Carlson's Elliptic Integrals of the First Kind: elliprf: 16.13
Carlson's Elliptic Integrals of the Second Kind: elliprd: 16.14
Carlson's Elliptic Integrals of the Third Kind: elliprj: 16.15
Legendre's Elliptic Integrals of the First Kind: ellipf: 16.16
Legendre's Elliptic Integrals of the Second Kind: ellipe: 16.17
Legendre's Elliptic Integrals of the Third Kind: ellipi: 16.18
Kolmogorov-Smirnov Test: kolsmi: 16.19
Psi (digamma) Function: psi: 16.20
Airy Functions: airy: 16.21
Matrix Elements That are Prime Numbers: isprime: 16.22
Lentz's Method For Evaluating Continued Fractions: lentz: 16.23
Integration And Differential Equations: integration: 17
Trapezoidal Approximation for Integrals: trapz: 17.1
Fifth Order Gaussian Quadrature Numerical Integration: gaussq: 17.2
Two Dimensional Gaussian Quadrature Integration: gaussq2d: 17.4
Computing Gauss-Legendre Quadrature Weights: gaussleg: 17.5
Numerical Integration to Infinity: int2inf: 17.7
A Fourth Order Runge-Kutta ODE Solver: ode4rk: 17.8
Exponential Of A Matrix: expmat: 17.9
Fifth Order Runge-Kutta Method With Fourth Order Error Control: ode45rk: 17.10
Solving An ODE Using The Matrix Exponential: odepade: 17.11
Solving Stiff Ordinary Differential Equations: odestiff: 17.12
Polynomials: polynomial: 18
Displaying A Polynomial: pol2asc: 18.1
Evaluating A Polynomial: polval: 18.2
Evaluating A Descending Polynomial: polyval: 18.3
Evaluating A Descending Polynomial Using Matrix Multiplication: polyvalm: 18.4
Polynomial Multiplication: polmul: 18.6
Composition Of Polynomials As Functions: polcomp: 18.7
Computing the Derivative of a Polynomial: polder: 18.8
Converting A Set Of Roots To A Polynomial: zero2pol: 18.9
Finding Roots of a Descending Polynomial: roots: 18.10
Converting A Set Of Roots To A Descending Polynomial: poly: 18.11
Using Laguerre's Method to Find The Roots of a Polynomial: pol2zero: 18.12
Computing Chebyshev Polynomial Coefficients: polcheb: 18.13
Remove Leading Zero Coefficients from a Descending Polynomial: polyreduce: 18.14
Convolution of Vectors (Mlmode): mlmode_conv: 18.15
Deconvolution or Descending Polynomial Division: deconv: 18.16
Calculate the Residues for a Rational Function in Complex Plane: residue: 18.17
Compute the companion matrix corresponding to polynomial: compan: 18.18
Evaluating A Multiple Dimension Monomial And Its Derivatives: monomial: 18.19
Graphical User Interface Programming: gui: 19
Opening A File Using The System Browser Dialog: openfile: 19.1
Saving A File Using The System Browser Dialog: savefile: 19.2
Obtaining A Text String Using The Input Dialog: input: 19.3
Putting A Prompt In The Input Dialog: input1: 19.4
Entering Passwords In The Input Dialog: input2: 19.5
Dialog For Choosing File Names: chfile: 19.6
Posting a Dialog With an Error Message: errordlg: 19.7
Displaying Program Status in a Dialog: status: 19.8
An Easy to Use General Purpose Dialog Routine: easydlg: 19.9
Easy Dialog Caption and Button Arguments: easydlg2: 19.9.1
Easy Dialog Message Argument: easydlg3: 19.9.2
Easy Dialog Layout Argument: easydlg4: 19.9.3
Easy Dialog Text Fields: easydlg_textfield: 19.9.3.1
Easy Dialog Label Fields: easydlg_label: 19.9.3.2
Easy Dialog Check Box Fields: easydlg_checkbox: 19.9.3.3
Easy Dialog Slider Fields: easydlg_slider: 19.9.3.5
Easy Dialog Spinbox Fields: easydlg_spinbox: 19.9.3.6
Easy Dialog Label Button Fields: easydlg_labelbutton: 19.9.3.7
Easy Dialog Text Button Fields: easydlg_textbutton: 19.9.3.8
Easy Dialog Connection Argument: easydlg5: 19.9.4
Enable Easy Dialog Fields on True: easydlg_enable: 19.9.4.1
Disable Easy Dialog Fields on True: easydlg_disable: 19.9.4.2
Easy Dialog First Argument: easydlg1: 19.9.5
Easy Dialog Dismiss Option: easydlg1_dismiss: 19.9.5.1
Easy Dialog Enable Option: easydlg1_enable: 19.9.5.2
Easy Dialog Disable Option: easydlg1_disable: 19.9.5.3
Easy Dialog Setvalue Option: easydlg1_setvalue: 19.9.5.4
A Complex Easy Dialog Example: easydlg_example: 19.9.6
Creating A New Editor Window: addeditor: 19.11
Getting The Contents Of An Editor Window: geteditor: 19.12
Creating A New Table Window: addtable: 19.13
Getting The Values In a Table: gettable: 19.14
Determining Which Cells Are Selected In A Table: getcells: 19.15
Changing The Value In Cells Of A Table: setcells: 19.16
Creating A New Dialog Window: adddialog: 19.17
Determining The Size Of The Screen In Pixels: getscreen: 19.18
Determining The Current Size Of The O-Matrix Main Window: getvisible: 19.19
Getting and Setting a Window's Geometry: windowgeometry: 19.20
Creating and Using Controls In a Dialog Window: controls: 19.21
Using Push Buttons In A Dialog Window: pushbutton: 19.21.1
Using Text Labels In A Dialog Window: addlabel: 19.21.2
Using Text Input Fields In A Dialog Window: textfield: 19.21.3
Using A Check Box In A Dialog Window: checkbox: 19.21.5
Using A Multi-Selection List In A Dialog Window: multilist: 19.21.6
Using A List Box In A Dialog Window: listbox: 19.21.7
Using A Slider In A Dialog Window: slider: 19.21.9
Using A Bit Map In A Dialog Window: bitmap: 19.21.10
Deleting A Window: delwin: 19.22
Iconifying A Window: iconify: 19.23
Determining If A Window Is Iconified: isicon: 19.24
Hiding A Window Or Disabling A Control: hide: 19.25
Normalizing A Window Or Enabling A Control: show: 19.26
Setting the O-Matrix Application Caption: caption: 19.27
Graphical User Interface Size Parameters: guisize: 19.28
Determining The Size of Text In a Dialog Window: textsize: 19.28.1
Determining the Size of a Dialog's Border: bordersize: 19.28.2
Determining Width of Window Controls on Caption Bar: wincontrolwidth: 19.28.3
Determine the Extra Space Needed for a Text Field: textfieldspace: 19.28.4
Determine the Extra Space Needed for a Popup Menu: popupspace: 19.28.5
Vector And Matrix Norms: normfunction: 20.1
Source Code Search Path: path: 20.2
Determine if an Identifier is Defined in Current Environment: defined: 20.3
Listing Variables Defined in The Current Environment: variables: 20.4
Using the Standard O-Matrix Error Dialog: error: 20.5
Trapping O-Matrix Errors Under Program Control: errortrap: 20.6
Invoking Help From Within An O-Matrix Program: help: 20.7
Garbage Collection of System Allocated Memory: garbage: 20.9
Evaluating a Character Matrix: eval: 20.10
Delayed Execution of Commands in a Matrix: execmat: 20.11
Including A File During Program Execution: execfile: 20.12
Converting Values To Ascii Using C Language Formatting: sprintf: 20.13
Setting Response Time During Execution: interrupt: 20.14
Running All the Files in a Directory: runall: 20.15
Print the Differences Between Ascii Files: filediff: 20.16
Comparing And Updating Source Files: update: 20.17
O-Matrix Code Debugger: debugger: 21
Quitting Execution From Within The Debugger: quit: 21.1
Listing Included Files: dbinclude: 21.2
Listing Active Variables in The Current Environment: active: 21.3
Exiting The Debugger And Continuing Execution: continue: 21.4
Deleting All Break and Watch Points: dall: 21.5
Setting And Listing Debugger Break Points: debug_break: 21.6
Skipping Breakpoints: skip: 21.7
Deleting Breakpoints: dbreak: 21.8
Setting Debugger Listing and Environment File: dbfile: 21.9
Displaying The Environment Call Stack: env: 21.10
Setting The Current Debugger Environment: env1: 21.11
Changing Output Format From Within the Debugger: dbformat: 21.12
Creating Global Variables From Temporary Ones: dbglobal: 21.13
Listing Lines In The Current Debugger File: list: 21.14
Stepping Over Function Calls: next: 21.15
Determining What Files Are Open: open: 21.16
Print Values Inside the Debugger: dbprint: 21.17
Clearing the Debugger Window: dbhome: 21.18
Stepping Into Function Calls: step: 21.19
Line By Line Tracing Of Execution: dbtrace: 21.20
Listing The User Defined Functions: user: 21.21
Creating And Listing Watch Points: watch: 21.22
Listing And Deleting Watch Points: dwatch: 21.23
Determine What An Identifier Refers To: which: 21.24
Using O-Matrix as a COM Automation Client: comautomation: 22.1
Creating a Connection to a COM/Automation Server: cocreate: 22.1.1
Releasing a COM/Automation Server Connection: corelease: 22.1.2
Setting a COM object: cowith: 22.1.3
Releasing a COM object: coendwith: 22.1.4
Setting a Property in the Current COM object: copropput: 22.1.5
Getting a Property of the Current COM object: copropget: 22.1.6
Invoking a COM Server Method: coinvoke: 22.1.7
Setting Variable as Variant: covariant: 22.1.8
Saving a COM Server Dispatch Pointer: codispsave: 22.1.9
Setting the IDispatch Pointer of a COM Object: codispset: 22.1.10
Displaying the Status of a COM connection: costats: 22.1.11
The O-Matrix COM Server: COM: 22.2
Starting O-Matrix: comstart: 22.2.1
Create a Connection with an O-Matrix Server: comopen: 22.2.2
Evaluating an O-Matrix Expression: comeval: 22.2.3
Transfer a Data Array to O-Matrix: computdata: 22.2.4
Loading Data from the COM Server to an O-Matrix Variable: computmatrix: 22.2.5
Transferring Variant Data to O-Matrix: computvariant: 22.2.6
Determine the Number of Columns of a Transferred Matrix: comncols: 22.2.7
Determine the Number of Rows of a Transferred Matrix: comnrows: 22.2.8
Transfer O-Matrix Variables to the COM Server: comgetmatrix: 22.2.9
Transfer Data to an O-Matrix COM Server Client: comgetdata: 22.2.10
Transfer Data to an O-Matrix COM Server Client: comgetvariant: 22.2.11
Determining if O-Matrix is Busy: comisbusy: 22.2.12
Setting the O-Matrix Server Timeout Period: comtimeout: 22.2.13
Terminating a Connection with an O-Matrix Server: comclose: 22.2.14
Status Values Returned from the O-Matrix COM Server Functions: comstatus: 22.2.15
Creating O-Matrix DLL Functions: dllall: 22.3
Writing An O-Matrix DLL Function in C++: dll: 22.3.2
C Structure That Defines A Matrix: matrix: 22.3.3
A DLL That Computes The Maximum Of Each Column: mycolmax: 22.3.4
A DLL That Computes The Maximum Of Each Row: myrowmax: 22.3.5
Transferring Data To The System Clipboard: copy: 22.4
Transferring Data From The System Clipboard: paste: 22.5
Using DDE to Communicate with other Programs: omlink: 22.6
Creating an OMDDE Client: omclient: 22.7
Number of Bytes Per Matrix Element: omsize: 22.7.1
Initializing and Terminating OMDDE Communication: omddeini: 22.7.2
Connecting an OMDDE Client To a Server: omclicon: 22.7.3
Disconnecting an OMDDE Client From a Server: omclidis: 22.7.4
Transferring Commands From OMDDE Client to Server: omclicmd: 22.7.5
Transferring Data From OMDDE Client to Server: omcliput: 22.7.6
Getting Data Sent to an OMDDE Client: omcliget: 22.7.7
Creating an OMDDE Server: omserver: 22.8
Windows Main Program for Server Examples: winmain: 22.8.1
Setting the Name of an OMDDE Server: omserreg: 22.8.2
Receiving Commands From an OMDDE Client: omsercmd: 22.8.3
Outputting Data From an OMDDE Server: omserout: 22.8.4
Getting Data Sent to an OMDDE Server: omserinp: 22.8.5
The O-Matrix Development Kit: omrte: 23
Appendix: appendix: 24
AUTOEXEC.OMS - Automatically Executed Commands and Defined Constants: autoexec: 24.1
Using Multiple CPUs: multicpus: 24.2
ASCII CHART: ascii: 24.3
Reports On Allocated Memory Usage: memory: 24.4
Short Hand For Functions With String Arguments: stringarg: 24.5
Alphabetic Listing Of Keywords: keyword: 24.6
Tokens That Are Not Keywords Or Intrinsic Functions: token: 24.7
Formal Syntax: bnf: 24.8
The O-Matrix Virtual Machine: omvm: 24.9
Creating an O-Matrix Binary Pcode Distribution: ompcode: 24.10
The O-Matrix Virtual Machine Application Launcher: vmlauncher: 24.11
The O-Matrix License File: omlic: 24.12
Comparison of O-Matrix and Matlab Functions: om2matlab: 24.13
O-Matrix Light: omatrixlight: 24.15
Introduction to O-Matrix Light: lightintro: 24.15.1
O-Matrix Light Restrictions: lightrestrictions: 24.15.2
Executing Large Programs Using O-Matrix Light: lightexe: 24.15.2.1
Mlmode: MATLAB® Compatibility: mlmode: 25
Switching Between Mlmode And O-Matrix Mode: mlmode_mode: 25.1
Differences Between The Mlmode and O-Matrix Languages: mlmode_language: 25.2
Assignment Statements (Mlmode): mlmode_assignment: 25.2.1
Multiple Statements in Same Line: multiplestatement: 25.2.2
Different Syntax with Same Meaning in Mlmode and O-Matrix Mode: mlmode_same: 25.2.3
If Statement (Mlmode): mlmode_if: 25.2.4
For Statement (Mlmode): mlmode_for: 25.2.5
While Statement (Mlmode): mlmode_while: 25.2.6
The Colon Operator (Mlmode): mlmode_colon: 25.2.7
Precision of Input Numeric Values (Mlmode): mlmode_numbers: 25.2.8
Building Matrices (Mlmode): mlmode_building: 25.2.9
Binary Operators and Character Matrices (Mlmode): mlmode_character: 25.2.10
Single Quote Character (Mlmode): mlmode_quote: 25.2.11
The Right Matrix Divide Operator (Mlmode): mlmode_matrixdivision: 25.2.12
Logical Operators (Mlmode): mlmode_logicalop: 25.2.13
Numeric Operators (Mlmode): mlmode_numericop: 25.2.14
Complex Operations only using Real Part (Mlmode): mlmode_realpart: 25.2.15
Using a Matrix as an Index (Mlmode): mlmode_matrixindex: 25.2.16
Logical Indices (Mlmode): mlmode_logicalindex: 25.2.17
Automatic Growing of Matrices on Assignment (Mlmode): mlmode_grow: 25.2.18
Script Files (Mlmode): mlmode_script: 25.3
User Defined Functions (Mlmode): mlmode_function: 25.4
Automatically Executed Command File (Mlmode): mlmode_autoexec: 25.5
Keywords (Mlmode): mlmode_keyword: 25.6
Intrinsic Functions (Mlmode): mlmode_intrinsic: 25.7
Converting to a Character Matrix (Mlmode): mlmode_setstr: 25.7.1
Checking If Two Character Matrices are Equal (Mlmode): mlmode_strcmp: 25.7.2
Creating a Matrix of Ones (Mlmode): mlmode_ones: 25.7.3
Creating a Matrix of Zeros (Mlmode): mlmode_zeros: 25.7.4
Determining the Maximum Dimension (Mlmode): mlmode_length: 25.7.5
Square Root of Minus One (Mlmode): mlmode_ij: 25.7.6
Plus Infinity (Mlmode): mlmode_inf: 25.7.7
Some Predefined Constants (Mlmode): mlmode_nan: 25.7.8
Obtaining a Copy of the Identity Matrix (Mlmode): mlmode_eye: 25.7.9
Determine if an Identifier is Defined (Mlmode): mlmode_exist: 25.7.10
Double Precision Machine Epsilon (Mlmode): mlmode_eps: 25.7.11
Numeric Value for Date and Time (Mlmode): mlmode_clock: 25.7.12
Compute Type and Size Limitations: mlmode_computer: 25.7.13
Getting And Setting The Current Working Directory (Mlmode): mlmode_cd: 25.7.14
Determining The Date (Mlmode): mlmode_date: 25.7.15
Maximum of a Set of Elements (Mlmode): mlmode_max: 25.7.16
Minimum of a Set of Elements (Mlmode): mlmode_min: 25.7.17
M-File Functions (Mlmode): mlmode_mfile: 25.8
Computing The Mean (Mlmode): mlmode_mean: 25.8.1
Computing The Standard Deviation (Mlmode): mlmode_std: 25.8.2
Legendre's Complete Elliptic Integrals (Mlmode): mlmode_ellipke: 25.8.3
Displaying A Value (Mlmode): mlmode_disp: 25.8.4
Displaying A Warning (Mlmode): mlmode_warning: 25.8.5
Left Justify a Sequence of Strings in a Single Matrix (Mlmode): str2mat: 25.8.6
Converting to Integer Ascii Representation (Mlmode): int2str: 25.8.7
Contour Plots (Mlmode): mlmode_contour: 25.8.8
Mesh Plots (Mlmode): mlmode_mesh: 25.8.9
Combined Mesh and Contour Plots (Mlmode): mlmode_meshc: 25.8.10
Surface Plots (Mlmode): mlmode_surf: 25.8.11
Combined Surface and Contour Plots (Mlmode): mlmode_surfc: 25.8.12
X and Y Grids for Contour and Mesh Plots (Mlmode): mlmode_meshgrid: 25.8.13
Elapsed Time Corresponding to Clock Values (Mlmode): mlmode_etime: 25.8.14
Determines Which Elements are Finite (Mlmode): mlmode_finite: 25.8.15
Returns a Non-Sparse Version of a Matrix (Mlmode): mlmode_full: 25.8.16
Does This Computer Support IEEE Arithmetic (Mlmode): mlmode_isieee: 25.8.17
Returns True for Unix Systems (Mlmode): mlmode_isunix: 25.8.18
Is a Matrix Sparse (Mlmode): mlmode_issparse: 25.8.19
Is a Matrix of Type Character (Mlmode): mlmode_isstr: 25.8.20
O-Matrix Routine For Missing Mlmode Functions: mismatfun: 25.9
Differences Between MATLAB® and Mlmode Languages: mlmode_diff: 25.10
Glossary: glossary: 26
Alphabetic Listing of Cross Reference Tags: _reference: 27
Keyword Index: _index: 28
2: Getting Started
2.a: Contents
Readme File for O-Matrix Version 6.5: 2.1
Starting O-Matrix: 2.3
Example Navigator: 2.4
The O-Matrix User Interface: 2.5
The O-Matrix Help System: 2.6
Customizing the Initial State of O-Matrix: 2.7
Finding Text in Files: 2.8
Exiting O-Matrix: 2.9
O-Matrix Tutorial: 2.10
Interactive GUI Tools: 2.11
2.1: Readme File for O-Matrix Version 6.5
Harmonic Software Inc. March 23, 2009
2.1.a: Support
Company: Harmonic Software Inc.
e-mail:
support@omatrix.com
web:
http://www.omatrix.com
2.1.b: O-Matrix Install Directory
The default location for the O-Matrix install directory is c:\omwin . If you installed O-Matrix to a different directory, use that directory where ever
is referenced. The following is a list of the items contained in the O-Matrix installation directory:
Directory
Description
DEVKIT
Tools, documentation, and examples of building re-distributable O-Matrix applications. (Available with the O-Matrix Development Kit
DLL
O-Matrix DLL functions: 22.3.1
EXAMPLE Numerous in-depth examples. See the O-Matrix Example Navigator: 2.4 .
FUNCTION O-Matrix *.oms function files
HTM
Documentation directory in HTML format
IPACKS
Installation directory for the SigmaPlot Interface Toolbox (http://www.omatrix.com/splink.html) and other third party products.
LIB
LPSOLVE Documentation and examples of using the lpSolve (http://www.omatrix.com/lpsolve.html) linear programming tools with O-Matrix
MATHLIBS Architecture-specific run time support libraries for numerical functions.
OCTAVE
Supplemental mlmode: 25 *.m files that enable O-Matrix to provide additional Matlab compatibility. These files must be installed after
O-Matrix. The Matlab Compatibility Library is provided as a separate setup program with your order, or may be downloaded from the
OMDDE
Example of using Windows DDE for connecting with other processes
PROGRAMS Can be used for storing user programs. Also used to store samples installed by the O-Matrix Development Kit
(http://www.omatrix.com/omrte.html)
STSA
Installation directory for the O-Matrix Time Series Toolbox (http://www.omatrix.com/stsa.html)
TECPLOT Functions for communicating with, and creating plots in Tecplot: 10.6 .
TEST
System and O-Matrix diagnostic tools
TOOLBOX O-Matrix *.oms and mlmode: 25 *.m files
TOOLS
GUI Tools for common O-Matrix tasks
c:\omwin
File
Description
autoexec.m File included whenever mlmode: 25 is cleared
autoexec.oms Startup File: 24.1 that is run, or included whenever O-Matrix is started or cleared: 3.2
omwin.exe O-Matrix executable program
2.2.a: Overview
O-Matrix is a complete, analysis and visualization environment for scientists, engineers, numerical analysts, students, and anyone performing
numerical or visual oriented data analysis or modelling. Development in O-Matrix is a time and cost saving alternative to programming in compiled
languages such as C or FORTRAN. Analysis and development efforts can be performed in a fraction of the time required using traditional languages
or typical integrated mathematics tools.
2.2.b: The benefits you will find working with O-Matrix include:
O-Matrix is both an environment and a language for technical computing: With O-Matrix you can both interactively explore, view and analyze
data and develop sophisticated stand-alone applications.
The O-Matrix language reflects the language of mathematical analysis: The syntax of the matrix-based language in O-Matrix closely resembles
the mathematical notation you would use for prototyping algorithms. Solutions can be compactly represented in a a clear and easy-to-understand form.
High performance is built in: O-Matrix was designed from the ground up to provide high performance for solving large, numerically intensive
problems. Built in functions are written in optimized assembly and FORTRAN code to provide throughput that is often comparable to, or exceeds
traditional compiled languages. O-Matrix is threaded and will take advantage of multi core CPUs and machines with multiple CPUs. See the
Multiple CPUs: 24.2 chapter for details on configuring your environment for threading.
Visualization from understanding to presentation: The graphics capabilities in O-Matrix are easy-to-use for rapid data exploration but powerful and
flexible enough for generating graphics presentations or exporting to other report generation applications.
Building on foundation algorithms enables robust, accurate applications: O-Matrix includes a broad range of numerical and statistical analysis
routines based on algorithms from experts in numerical analysis. These functions have been implemented with extensive testing and validation which
frees O-Matrix users from programming details typically found when developing numerical algorithms from scratch.
Extensibility leverages solutions and applications:
O-Matrix can be extended by creating new functions as OMS script files: 3.8 .
Create compiled functions: 22.3 with languages such as C/C++ and FORTRAN which are made available to the O-Matrix environment as
Windows DLLs.
A Platform for Turnkey Solutions: Using the O-Matrix Development Kit: 23 and O-Matrix Virtual Machine, finished solutions can be easily
MATLAB® Language Support in O-Matrix The O-Matrix environment provides support for both the O-Matrix language and the MATLAB
language. This feature is described in the section Mlmode: MATLAB® Compatibility: 25.
2.3: Starting O-Matrix
Syntax c:\omwin\omwin.exe
c:\omwin\omwin.exe
StartupFile
c:\omwin\omwin.exe "StartupFile"
InstallDir
2.3.a: Description
The commands listed above start the O-Matrix program. They can be executed from the windows Start button, from the Target field of the Shortcut tab
of the Properties of a windows icon, or at the Microsoft DOS command line. The directory c:\omwin is the directory where O-Matrix is installed and
may be different for your machine.
2.3.b: O-Matrix Interface
The O-Matrix interface contains the following main regions:
The Command Line: 2.5.1
The O-Matrix Toolbar: 2.5.6
The Command Window: 2.5.2
The Debugger Window: 2.5.4
Graphics Windows: 2.5.3
Editor Windows: 2.5.7
The three windows entitled Command, Debugger, and Graphic 0 can not be closed, but any of them can be minimized, maximized, moved, or resized
by using the standard Windows techniques. (The Debugger and Graphic 0 windows are minimized in the picture above.) Although none appear when
O-Matrix is first executed, you can open and close Editor windows.
2.3.c: Example
If from the window Start button you select Run... and then enter
c:\omwin\omwin.exe
The O-Matrix interface will start up.
2.3.d: Command Line Arguments
StartupFile
is a specification for an O-Matrix source code file. If StartupFile includes a complete path, the current directory is set to the directory in StartupFile.
Then the file specified by StartupFile is executed by O-Matrix.
InstallDir
specifies an alternative directory where O-Matrix is installed. This is useful if you have multiple versions of O-Matrix installed because it enables you
to specify a different installation directory for each one. Note that if InstallDir is present, StartupFile must be enclosed in double quotes. You can
specify an installation directory without a start up file, by making the start up file name empty; i.e., by using the syntax
c:\omwin\omwin.exe " " InstallDir
2.3.d.a: Example
If the file c:\omwin\programs\temp.oms contains
print "Hello World"
and from the window Start button you select Run... and then enter
c:\omwin\omwin.exe c:\omwin\programs\temp.oms
O-Matrix will start up and then print
Hello World
2.4: Example Navigator
The Example Navigator is a dialog-based utility for navigating, running, and viewing O-Matrix examples. In O-Matrix Light the navigator will start
automatically, but can also be invoked from the "Tools" menu.
Each example in the navigator corresponds to an O-Matrix script file in the omwin\example directory. You can run individual examples from the
command line by entering
include example\<example directory>\<example name>
For example, if you enter
include example\demo\rosen.oms
at the command prompt, O-Matrix will run the Rosenbrock's example. Alternatively, examples can be run by selecting "File | Run" from the main
menu and browsing to the desired example.
The samples in the Example Navigator are designed to illustrate O-Matrix usage for typical applications and provide templates for specialized uses.
More simple and concise examples of O-Matrix functions are provided with the online documentation for individual functions and features. See the
O-Matrix Tutorial: 2.10 for a detailed walk though of O-Matrix concepts.
The Example Navigator is built using the O-Matrix GUI Building Tools: 19 . Source code for the GUI is available in the example\examples.oms file.
2.5: The O-Matrix User Interface
The O-Matrix interface provides many elements to help develop and run data analysis and visualization solutions. The following sections provide an
overview of the primary interface components.
2.5.a: Contents
cmdline: 2.5.1
The Command Line
commandio: 2.5.2 The Command Window
graphicio: 2.5.3 Graphics Windows
debugio: 2.5.4
The Debugger Window
omtoolbar: 2.5.6 The O-Matrix Toolbar
editorio: 2.5.7
Editor Windows
2.5.1: The Command Line
2.5.1.a: Description
Commands can be entered in O-Matrix by typing them directly in the box to the right of the prompt button, which is the right most button below the
menu at the top of the screen. If the prompt button displays the blue O>: 26.z prompt, commands entered will be echoed in the Command window:
2.5.2 . If the prompt button shows the red DEBUG>: 26.k prompt, commands will be echoed in the Debugger window: 2.5.4 . (Clicking the button
toggles it between the two prompts.)
2.5.1.b: Example
If at the O> prompt you enter
5. / 2.
O-Matrix will respond
2.5
in the Command window: 2.5.2 .
2.5.1.c: Editing Commands
O-Matrix keeps a list of the commands entered at the Command line during a session. The F2 function key, moves the cursor to the Command line.
When the cursor is at the Command line, commands can be recalled and edited with the following special keys:
Keyboard Entry Description
UP ARROW
recalls previous command in the list
DOWN ARROW
recalls next command in the list
END
moves cursor to end of current command
HOME
moves cursor to beginning current command
ESC
erases current command
LEFT ARROW
moves cursor left one character
RIGHT ARROW
moves cursor right one character
BACKSPACE
deletes character to the left of cursor
DELETE
deletes character to the right of cursor
2.5.1.d: Alternatives
Some commands can also be run by selecting them from the menu bar: 2.5.5 . In addition, the integrated O-Matrix editor: 2.5.7 can be used for
entering groups of commands and for recalling scripts from disk files.
2.5.2: The Command Window
2.5.2.a: Description
The Command window displays input commands and corresponding output, where every input command is preceded by the O>: 26.z prompt.
2.5.2.b: Example
If you enter
cos(pi)
at the O> prompt, O-Matrix will respond
-1
in the Command window as follows:
Note that input lines in the Command window are preceded by the O> prompt.
2.5.2.c: Saving Input Commands
The commands you have typed can be saved to an ASCII text file for later use. To do this, select File | Save As from the menu, chose the Save
Commands radio button, select the Select File Name button, and then choose a file name.
2.5.2.d: Saving Command Window
The current contents of the command window can also be saved to a file. To do this, select File | Save As from the menu, chose the Save Output radio
button, and select the Select File Name button, and the choose a file name. Text printed in this window can also be saved using the diary: 8.27
command.
2.5.3: Graphics Windows
2.5.3.a: Description
The graphics windows display the plots created by graphics commands. Initially, only one graphics window appears, Graphic 0, but unlike the
Command and Debugger windows, more graphics windows can be added by using the gaddwin: 10.1.11 command. Graphics windows can also be
divided into multiple areas, called viewports: 26.aq , which allows more than one plot to occupy a single graphics window.
2.5.3.b: Example
If at the O>: 26.z prompt you enter
ginit
x = 0. : .1 : 2 * pi
y = sin(x)
gplot(x, y)
O-Matrix will draw the following plot in the Graphic 0 window:
2.5.3.c: Printing
To print the contents of the current graphics window, select the File | Print menu item, choose the Print Current Graphic radio button and then select
Print.
2.5.4: The Debugger Window
2.5.4.a: Description
The debugger allows you to track code execution and variable values in an O-Matrix program. To enter the debugger, type
stop
at the O>: 26.z prompt or select Debug | Enter Debugger from the menu. The debugger commands are listed in the Debugger: 21 section.
2.5.4.b: Example
If you enter
at the
cos(pi)
stop
O> prompt, the Debugger
window will display both this input line and the resulting output:
Note that input lines in the Debugger window are preceded by "Debug>". To return control the to O> prompt, enter cont or select the Debug | Exit
2.5.4.c: Saving Debugger Window
The current contents of the Debugger window can be saved in an ASCII text file. To do this, select the File | Save As menu item, choose the Save
Debugger Output radio button, select the Select File Name button, and choose a file.
2.5.4.d: Printing Debugger Window
To print the current contents of the Debugger window, select the File | Print menu item, select the Print Debugger Output check box, and then select
the Print button.
2.5.4.e: Entering Debugger Upon Errors
When O-Matrix encounters certain errors, it will give you the choice to do one of four things:
Button Action
Continue return control to O> prompt
Debug transfer control to DEBUG> prompt
Edit
edit the file where the error occurred
Help
obtain help related to the error
If you select Debug, you will enter the debugger with the current environment set to the place where the error occurred.
2.5.5.a: Description
The menu bar offers rapid access to many O-Matrix commands which are controlled primarily through dialogs, secondary windows that contain one or
more controls for performing common operations.
2.5.5.b: File
The File menu can be used to clear the current workspace, create new editor: 2.5.7 windows, work with existing programs, manipulate files, print
output, halt execution, and exiting: 2.9 O-Matrix.
2.5.5.c: Edit
The Edit menu can be used for cutting, copying, and pasting of text and graphics, editing files, and finding text in files: 2.8 .
2.5.5.d: Command
The Command menu can be used for executing some common input and output commands such as, including programs for execution and setting
numeric output format. In addition, it can be used for profiling the execution speed of your O-Matrix programs.
2.5.5.e: Debug
The Debug menu can be used to access debugger: 2.5.4 commands.
2.5.5.f: Graphics
The Graphics menu can be used to access common graphics: 10.1 commands such as initializing graphics, creating new windows and viewports,
manipulating plots, and modifying text.
2.5.5.g: Options
The Options: 2.7 menu is used for setting preferences at start up and exit such as initial window layout, numeric output formats, and fonts.
2.5.5.h: Window
The Window menu can be used to access windows and control their layout within the O-Matrix workspace.
2.5.5.i: Tools
2.5.5.j: Help
The Help menu can be used to display the help that is distributed with O-Matrix and add on packages.
2.5.6: The O-Matrix Toolbar
2.5.6.a: Description
The toolbar at the top of the screen (just below the menu bar) provides access to the some of the frequently used menu items. If a tool bar icon is not
available, it is grayed out. For example, the hand icon is grayed in the second version of the toolbar above. It is possible, using the hide: 19.25
command, to gray out the entire toolbar. This should only be done by an O-Matrix program that does not wish to get input from the toolbar or
command line.
The first icon displays a blank sheet of paper. Selecting this icon is equivalent to the File | Edit New Program menu item. This creates a new editor
window with nothing in it.
The second icon in the toolbar displays an open file folder. Selecting this icon is equivalent to the File | Open Program menu item. This starts a
browser dialog in which you can select an existing file. Once you select a file, a new editor window containing the contents of the file is created.
The third icon displays a floppy disk. Selecting this icon is equivalent to the File | Save menu item. If the currently active window is an editor window,
it is saved to disk. If an editor window is not active, you can also use this icon to save the contents of the Command or Debugger window windows.
The fourth icon displays a lightning bolt. If the O>: 26.z prompt is currently displayed, selecting this icon is equivalent to the File | Run Program menu
item. If in addition, an editor window is currently active, the contents of the editor window will be run as an O-Matrix program. Otherwise, a browser
dialog is displayed in which you can select an existing file. Once you select a file, it is run as an O-Matrix program.
If the DEBUG>: 26.k prompt is currently displayed, selecting the icon is equivalent to the Debug | Next menu item which executes one source code line
in the current function.
The fifth icon displays a hand in red (when it is active). If the O-Matrix is currently running a program, selecting this icon is equivalent to the File |
Halt Execution menu item. (If O-Matrix is currently running a program the word "Processing" is displayed in the status line at the bottom right of the
main O-Matrix window.) In this case, selecting the icons halt program execution and returns control to the Command line: 2.5.1 .
If the DEBUG>: 26.k prompt is currently displayed, O-Matrix execution has been suspended. In this case, if an editor window is active, selecting this
icon sets a debugger break: 21.6 point at the current line in the current editor window and displays the current set of break points. The line number
corresponding to the break point is displayed in the status bar at the bottom right of the main O-Matrix window. If an editor is active, this line number
changes whenever the cursor moves over a new editor window. For this reason, the cursor must not move over another editor window between
selecting the line in the active editor and selecting the halt icon. If no editor window is active, selecting the halt icon will just display the current set of
break points.
The sixth icon is either the 0>: 26.z prompt or the DEBUG>: 26.k prompt.
If the O> prompt is displayed, selecting its icon is equivalent to the Debug | Enter Debugger menu item. When the O> prompt is displayed and the hand
icon is grayed out, O-Matrix is waiting for command input: 2.5.1 . When the O> prompt is displayed and the hand icon is red, O-Matrix is currently
running a program. In this case, selecting its icon will suspend program execution and enter the debugger: 21 where execution can later be resumed
using the Debug | Continue menu item.
If the DEBUG> prompt is displayed, selecting its icon is equivalent to the Debug | Exit Debugger menu item. When the DEBUG> prompt is displayed, OMatrix is in waiting for a debugger: 21 command.
2.5.7: Editor Windows
2.5.7.a: Description
Editor windows function similarly to the Notepad program that is part of Microsoft Windows. You can use them to create, edit, and save ASCII text
files. Because O-Matrix uses text files as its programs, you can use these editors to create such programs.
2.5.7.b: New Editor Windows
Many of the editor window functions reside under the File and Edit menu items. Selecting File | Edit New Program will bring up a window titled
"Untitled". (You can also use the blank page icon discussed in the toolbar: 2.5.6 section for this purpose.)
2.5.7.c: Entering Text
Once you have opened a new editor window, you can type commands directly into the file without the immediate interpretation you would receive
from the O>: 26.z prompt. For example, if you enter the following data into an editor window
O-Matrix will not execute the commands.
2.5.7.d: Executing Programs
You can execute the program with the File | Run Program menu item. If you continue the example above by selecting File | Run Program while the
editor window is active, O-Matrix will ask if you wish to save the file. If you select No, O-Matrix will respond:
in the Command window. (If the Command window is covered up, you can use the Windows menu item to bring it into view. You can also use the
lighting bolt icon discussed in the toolbar: 2.5.6 section to execute the current edit window.)
2.5.7.e: Saving Programs
To save this program select the File | Save As menu item, choose the Save Current Edit Window radio button, select the Select File Name button, and
then choose a file name C:TEMP.OMS in the PROGRAMS subdirectory. (You can also use the floppy disk icon discussed in the toolbar: 2.5.6 section to
save the current edit window.)
2.5.7.f: Editing Existing Files
You can open an existing ASCII text file by selecting the File | Open Program menu item. You can also use this option to edit any ASCII file. On the
other hand, only O-Matrix programs will work correctly if you then select the File | Run Program menu item. (You can also use the file folder icon
discussed in the toolbar: 2.5.6 section to open an existing file.)
2.5.7.g: Editing Functions
In any of the editor windows, the Cut, Copy, and Paste commands from the Edit window can be used, and work as they do in other Windows text
editors: "Cut" removes highlighted text from the editor and places it onto the Clipboard, from which it can be retrieved with the "Paste" command.
"Copy" also puts highlighted text into the Clipboard, but does not delete the text from the current editor window.
2.5.7.h: Printing
To print the contents of the current editor window, select the File | Print menu item, choose the Print Current Editor radio button, and then select Print.
2.6: The O-Matrix Help System
2.6.a: Description
O-Matrix includes a standard Windows help interface, which can be accessed through the Help menu or by entering help at the O>: 26.z prompt. All
of the documentation for O-Matrix is provided in HTML format in the C:\OMWIN\HTM directory.
2.6.b: Help | Contents
2.6.c: Help | Search
This menu item sets the current page in you browser to the alphabetically ordered index for the O-Matrix help system. You can use the by letter jump
table or the Edit | Find in Page menu item, to find the topic you are interested in.
2.6.d: Support
Whether you are a new O-Matrix customer, a veteran user, or have just downloaded O-Matrix Light: 24.15.1 , we are dedicated to providing you
directly by e-mail, phone, fax, or mail:
Web:
http://www.omatrix.com
E-mail: support@omatrix.com
PO Box 7365
Breckenridge, CO 80424
Attn: Product Support
2.7: Customizing the Initial State of O-Matrix
Some of the current settings can be saved and restored when O-Matrix starts up using the Options menu. When one of these options is chosen, the
corresponding setting is saved in the file named om50.ini in your windows system directory. (The file c:\omwin\om50.ini is a copy of the original
version of this file.) The following table lists these settings:
Option
Meaning
Save Window The current size and position of the Command: 2.5.2 , Debugger: 2.5.4 , and Graphic 0: 2.5.3 windows.
Layout
Save Numeric The current format: 8.17.1 used for printing values.
Format
Save Fonts
The current graphic: 10.2.19 fonts.
Editor font
Changes the current font used in editor windows.
Save Editors on If this option is checked when O-Matrix exits, all editor windows are inspected to see that the their edits have been saved. If a
Exit
windows edits have not been saved, a dialog is posted and you are given the option to save them.
Save Session on If this option is checked when O-Matrix exits, you are given the option of saving commands that you entered at the command line in
Exit
a file.
Activate Graph If this option is checked, every plotting command causes the current graphic window is moved in front of other windows.
2.7.b: Autoexec.oms
The settings mentioned above are not affected by the clear: 3.2 command. Setting that are affected by the clear command can be restored using the
autoexec.oms: 24.1 file. This file can be edited by selecting the File | Open Program menu item and selecting the file c:\omwin\autoexec.oms. You
may also customize O-Matrix by adding commands to this file. For example, if you add the command
print "Hello World"
to the end of the file autoexec.oms , O-Matrix will display
Hello World
when you start up and after each clear command.
2.8: Finding Text in Files
2.8.a: Description
The Edit | Find In Files menu item invokes a dialog which can be used to search for text in files. The dialog has the following fields:
Field
Meaning
find what
text that is searched for
file types
type of files included in search
timeout
time to search
selected folder if checked, search folder specified below
subfolder
search subfolders as well
included file search files included since previous clear: 3.2
include path search all folders in current path: 20.2
match case
text must match upper and lower case letters
The following is a sample of the dialog:
In this example, O-Matrix will search for the string kalman in files that have the *.oms extension. Files in the directory c:\omwin and all directories
below that directory will be searched. In addition, files that have been included since the previous clear: 3.2 command will also be searched. Matching
text must have the same case as kalman, for example, Kalman would not constitute matching text.
2.9: Exiting O-Matrix
2.9.a: Tutorial
To exit the O-Matrix program, enter
exit
at the O>: 26.z prompt, select the File | Exit menu item, or select the close control from the caption bar of the main O-Matrix window.
If the Options | Save Session on Exit menu item is checked, O-Matrix will display the following dialog:
Selecting "Yes" will cause O-Matrix to prompt you for a file name, selecting "No" will terminate O-Matrix without saving the current session, and
selecting "Cancel" will cancel the exit command.
If the Options | Save Editors on Exit menu item is checked, O-Matrix will ask a similar question for any open editor windows that contain changes
which have not been saved.
2.10: O-Matrix Tutorial
2.10.a: Description
The following tutorial provides a walk through of core O-Matrix concepts for many typical data analysis, modelling, and visualization tasks. Working
through this sequence typically takes a couple hours and will provide a fairly deep understanding of O-Matrix to enable you to solve a broad range of
problems.
The examples in omwin\example, and the Example Navigator: 2.4 provides more in-depth illustrations of a broad range of O-Matrix capabilities as
applied in typical analysis applications.
2.10.b: Executing Examples
Each of the sections in the table below contains examples. The easiest way to execute examples in these sections is to use the Windows Copy and
Paste functions. As an example, hold down the left mouse button and highlight the following blue text:
for i = 1 to 5 begin
print i
end
Then select the Edit | Copy menu item in you web browser. Then switch to the O-Matrix application, place the cursor in the command line: 2.5.1 , and
select the Edit | Paste menu item in O-Matrix. O-Matrix will reply
1
2
3
4
5
in the Command window.
2.10.c: Section Order
1: Starting O-Matrix: 2.3
2: Exiting O-Matrix: 2.9
3: The Command Line: 2.5.1
4: The Command Window: 2.5.2
5: Assigning Values To Variables: 3.1
6: Representing Matrix Elements In Program Input: 3.4
7: Building Matrices: 3.6
8: Printing A List Of Expressions: 3.12
10: Subtraction: 4.5
11: Element-By-Element Multiplication: 4.6
12: Matrix Multiplication: 4.11
13: Element-By-Element Division: 4.7
14: Element-By-Element Exponentiation: 4.13
15: Testing Numeric And Logical Equality: 4.8
16: Ordered Numeric And Logical Comparisons: 4.9
17: Order Of Operations: 4.19
18: If Statement: 5.1
19: Grouping A Sequence Of Statements As A Block: 5.2
20: For Statement: 5.3
21: Elements Of A Vector: 7.1
22: Elements Of A Matrix: 7.2
23: Vector Indices: 7.8
24: Setting Floating Point Output Formats: 8.17.3
25: Writing a Matrix to the Screen or a File: 8.10
26: Reading The Next Row From A File: 8.3
27: Drawing Line Plots: 10.1.1
28: Using Multiple CPUs: 24.2
2.11: Interactive GUI Tools
The following utilities provide stand-alone point-and-shoot utilities for performing common analysis and visualization tasks in O-Matrix. The
complete source code of these programs are also presented as examples for building GUI based applications in O-Matrix.
2.11.a: Contents
fileplotdlg: 2.11.1 A Dialog for Plotting Files
linlsqdlg: 2.11.2 A Linear Least Squares Fitting Dialog
polfitdlg: 2.11.3 A Dialog for Fitting Polynomials
digfilter: 2.11.4 Theoretical and Estimated Response for a Digital Filter
2.11.1: A Dialog for Plotting Files
Syntax fileplotdlg
2.11.1.a: Description
Displays a dialog that controls the plotting of selected columns of a file. The file contains double precision values and its columns are separated by
white space. The user will be given the choice of one column for the x-axis and multiple columns for the y-axis. The plot will be displayed and stay in
the Graphic 0 window.
Button Description
Clear Clear the plot
Plot
Add curve corresponding to current field settings
File
Select a new file
Exit
Dismiss the plot dialog
Help Display help for fileplotdlg
2.11.1.b: Examples
1
2
3
4
5
1
1
4
8
9 27
16 64
25 125
If you enter
clear
fileplotdlg
O-Matrix will display the File Plot dialog. If you then select the File button and choose the file tools\quadratic.dat, O-Matrix will display a
dialog that looks like this:
If you then chose 1 for the x index and 2 for the y index, O-Matrix will plot a quadratic function in the graphics window.
2.11.2: A Linear Least Squares Fitting Dialog
Syntax linlsqdlg
2.11.2.a: Description
Displays a dialog that controls the linear least squares fitting of an arbitrary set of functions to two selected columns of and ascii data in a file. The file
contains double precision values and its columns are separated by white space. The user will be given the choice of one column for the independent
variable, x, and another column for the dependent variable, y. In addition, the user will define an expression for each of the fitting functions.
2.11.2.b: The Fit Button
If the Fit button is selected, the following objective function is minimized with respect to the amplitude vector a:
n
5
2
--- [
--]
>
[ y
- >
a * f (x ) ]
--- [ i
--- j
j i ]
i=1
j=1
where n is the number of rows in the data file. The resulting
new value for the vector a is displayed in the dialog.
2.11.2.c: Fitting Functions
If a fitting function is blank, it is not included in the fit. Otherwise each fitting function must be defined as an element-by-element: 26.n expression: 4
in terms of a column vector x. (Thus the fitting function evaluates to a column vector with the same length as x.) For example, the expression sin(x):
6.2.9 defines the element-by-element sine function of the column vector argument x. There is one exception to this rule: if the character x is not
present in the fitting function definition, it is assumed to evaluate to a scalar: 26.ai (for example if the fitting function definition is 1.) In this case, it
represents a constant and is the same value independent of the value of x.
2.11.2.d: The Plot Button
If the Plot button is selected, a plot corresponding to the current dialog settings is displayed in the Graphic 0 window. (Note that you can change the
amplitude vector a either directly in the dialog or by choosing the Fit button.) The lower plot contains the residuals plotted as circles. The upper plot
contains the data and fitted function values. The data is plotted as circles and the fitted function is plotted as a curve.
2.11.2.e: Other Buttons
The File button is used to choose a new data file. The Exit button dismisses the Linear Least Squares dialog. The Help button displays the help for
linlsqdlg.
2.11.2.f: Example
If the file temp.dat contains
1
2
3
4
5
1
1
4
8
9 27
16 64
25 125
and you enter
clear
linlsqdlg
O-Matrix will display the following dialog
If you then use the File button to select the file temp.dat, O-Matrix will display the name of the file in the dialog. If you then choose the following
setting
x column index 1
y column index 2
f1(x)
1
f2(x)
x
f3(x)
x^2
f4(x)
f5(x)
and then select the Fit button, O-Matrix will fit a quadratic function to the data and display the resulting amplitude values in the dialog. If you then
select the Plot button, O-Matrix will plot the result in the Graphic 0 window. You can use the Exit button to dismiss the dialog.
2.11.3: A Dialog for Fitting Polynomials
Syntax polfitdlg
2.11.3.a: Description
Displays a dialog that controls the linear least squares fitting of a polynomial to two selected columns of an ascii data file. The file contains double
precision values and its columns are separated by white space. The user will be given the choice of one column for the independent variable, x, and
another column for the dependent variable, y. In addition, the user will be given a choice for the degree of the polynomial used in the fit.
2.11.3.b: The Fit Button
If the Fit button is selected, the following objective function is minimized with respect to the amplitude vector a:
n
2
--- [
2
m ]
>
[ y
- a + a x + ... + a
x ]
--- [ i
1
2
m+1
]
i=1
where n is the number of rows in the data file and m is the degree
of the polynomial. The resulting new value for the vector a is displayed in the dialog.
2.11.3.c: The Plot Button
If the Plot button is selected, a plot corresponding to the current dialog settings is displayed in the Graphic 0 window. (Note that you can change the
amplitude vector a either directly in the dialog or by choosing the Fit button.) The lower plot contains the residuals plotted as circles. The upper plot
contains the data and fitted function values. The data is plotted as circles and the fitted function is plotted as a curve.
2.11.3.d: Other Buttons
The File button is used to choose a new data file. The Exit button dismisses the Polynomial Fitting dialog. The Help button displays the help for
polfitdlg.
2.11.3.e: Example
If the file temp.dat contains
1
2
3
4
5
1
1
4
8
9 27
16 64
25 125
and you enter
clear
polfitdlg
O-Matrix will display the following dialog
If you then use the File button to select the file temp.dat, O-Matrix will display the name of the file in the dialog. If you then choose the following
setting
x column index
1
y column index
2
polynomial degree 2
and then select the Fit button, O-Matrix will fit a quadratic function to the data and display the resulting amplitude values in the dialog. If you then
select the Plot button, O-Matrix will plot the result in the Graphic 0 window. You can use the Exit button to dismiss the dialog.
2.11.4: Theoretical and Estimated Response for a Digital Filter
Syntax digfilter
2.11.4.a: Description
Plots the theoretical and sample response of a band pass or low pass digital filter. The user is given a choice of design parameters for the filter. The
plot is displayed in the Graphic 0 window.
2.11.4.b: Example
You if you enter
clear
digfilter
O-Matrix will display the following dialog:
If you then press the Plot button, O-Matrix will plot the response of the digital filter corresponding to the default settings of the dialog.
3: Basic Concepts
3.a: Contents
Assigning Values To Variables: 3.1
Starting A New Program: 3.2
Assigning Values To Constants: 3.3
Representing Matrix Elements In Program Input: 3.4
The Mathematical constant Pi: 3.5
Building Matrices: 3.6
Terminating An O-Matrix Session: 3.7
Explicit Inclusion of Commands or Functions from a File: 3.8
Implicit Inclusion of Commands or Functions from a File: 3.9
Default Printing Of An Expression: 3.11
Printing A List Of Expressions: 3.12
Suspending Program Execution And Entering Debugger: 3.13
Determining The Column Dimension Of A Matrix: 3.14
Determining The Row Dimension Of A Matrix: 3.15
Determining the Dimensions of a Matrix: 3.16
Changing Matrix Dimensions: 3.17
Copying and Changing the Dimensions of a Matrix: 3.18
3.1: Assigning Values To Variables
Syntax variable = value
See Also multiple assignment: 11.11 , functions as variables: 11.13 , constants: 3.3
3.1.a: Description
Assigns a value to the specified variable.
3.1.b: Tutorial
The assignment statement sets a variable equal to a value. The variable takes the type and dimension of the value assigned to it.
3.1.b.a: Scalars
If you enter
x = 42
print x
O-Matrix will respond
42
3.1.b.b: Row Vectors
If you enter
x = [2, 3, .2]
x
O-Matrix responds
[ 2 , 3 , 0.2 ]
3.1.b.c: Column Vectors
If you enter
x = {2, 3, .2}
x
O-Matrix responds
{
2
3
0.2
}
3.1.b.d: Matrices
Entering
x = {[1, 2], [0, 1]}
x
yields
{
[ 1 , 2 ]
[ 0 , 1 ]
}
3.2: Starting A New Program
Syntax
clear
clear function: 11.3 , autoexec: 24.1
3.2.a: Description
Erases all variables, constants, user-defined functions, and labels.
3.2.b: Example
If you enter
x = 5
print x
O-Matrix will respond
5
If you now enter
clear
print x
O-Matrix will respond with an error message because x is no longer defined.
3.2.c: Reference
The clear command does not erase debugger breakpoints: 21.8 or watchpoints: 21.22 . The dall: 21.5 command can be used to do this.
3.3: Assigning Values To Constants
Syntax const constant = value
3.3.a: Description
Assigns a value to the specified constant.
3.3.b: Tutorial
The constant directive sets a constant equal to a value. Once a constant is defined, it cannot be reassigned. The name used for the constant must not be
previously defined.
For example, if you enter
clear
const I = 1i0
print I
O-Matrix will respond
(0,1)
If you then try to reassign I by entering
I = 2i0
O-Matrix will respond with an error message.
3.3.c: Using With Functions
Constants defined outside of any function have global scope: 26.aj and are automatically visible with in all functions (see the discussion on constants
in the Using Variables And Constants With Functions: 11.7 section).
3.4: Representing Matrix Elements In Program Input
3.4.a: Integers
An integer is a sequence of digits without a decimal point. If you enter
1234
O-Matrix will respond
1234
3.4.b: Real Numbers
A real number (single precision) is a sequence of digits with a decimal point, or a number expressed in scientific notation with "e" (or "E") separating
the mantissa and exponent. For example,
5.25
will result in
5.25
An exponent is an integer that may be preceded by a plus or minus sign. A mantissa is an integer or real number. For example, in the expression
-2
5.25 x 10
5.25 is the mantissa and -2 is the exponent. Entering
5.25e-2
O-Matrix will respond
0.0525
3.4.c: Double-Precision Numbers
A double-precision number is a number expressed in scientific notation using "d" (or "D") to separate the mantissa and exponent. A double-precision
number has fifteen digits of precision, whereas a real number has seven.
If you enter
5.25d-2
O-Matrix will respond
0.0525
3.4.d: Complex Numbers
A complex number is a number expressed in scientific notation using "r" ("R") or "i" ("I") to separate the mantissa and exponent. The "r" signifies a
purely real number while the "i" signifies a purely imaginary number. Each component of a complex number carries the same number of digits as
double-precision numbers.
For example, to express the number 1, which is equal to
0
1 x 10
as a complex number, enter
1r0
to which O-Matrix will respond
(1,0)
To express 20 i, which is equal to
1
2 i x 10
enter
2i1
to which O-Matrix will respond
(0,20)
3.4.e: Strings
A string is a character row vector: 26.ah . It can be input as a sequence of characters enclosed in double quotes. The sequences of characters may not
contain any carriage returns. If you enter
"Hello World"
O-Matrix will respond
Hello World
3.4.f: Logical Values
The logical values true and false can be input directly. If you enter
print true, false
O-Matrix will respond
T F
3.5: The Mathematical constant Pi
Syntax pi
3.5.a: Description
Returns the ratio of the circumference over the diameter of a circle as a real scalar in O-Matrix mode and as a double-precision scalar in Mlmode: 25 .
The constant PI: 24.1 is always a double-precision representation of the same value.
3.5.b: Example
If you enter
pi
O-Matrix will respond
3.14159
3.6: Building Matrices
Syntax [ list of values ]
{ list of values }
3.6.a: Description
Builds a matrix from other matrices.
3.6.b: Brackets
Brackets ([ ]) combine matrices that have the same row dimension. The column dimension of the resulting matrix is the sum of the widths of the
combined matrices.
3.6.b.a: Tutorial
If you enter
x = [1, 2, 3]
y = [4, 5]
print [x, y]
O-Matrix will respond
[ 1 , 2 , 3 , 4 , 5 ]
If you enter
x = {[1, 2], [6, 7]}
y = {[3, 4, 5], [8, 9, 10]}
[x, y]
O-Matrix will respond
{
[ 1 , 2 , 3 , 4 , 5 ]
[ 6 , 7 , 8 , 9 , 10 ]
}
3.6.c: Braces
Braces ({ }) combine matrices that have the same column dimension. The row dimension of the resulting matrix is the sum of the heights of the
combined matrices. If the values are character matrices, they need not have the same column dimension. The resulting matrix takes on the same width
as the widest row. (Spaces are used to fill in the shorter rows).
3.6.c.a: Tutorial
If you enter
x = {1, 2}
y = 3
{x, y}
O-Matrix will respond
{
1
2
3
}
If you enter
x = {[1, 2], [3, 4]}
y = [5, 6]
{x, y}
O-Matrix will respond
{
[ 1 , 2 ]
[ 3 , 4 ]
[ 5 , 6 ]
}
If you enter
x = {"red", "blue"}
print x
O-Matrix will respond
red
blue
Note that the column dimension of x is 4.
3.6.d: Empty Matrices
If there are no expressions within the brackets or braces, the result is a logical empty matrix: 26.o with both its row and column dimension equal to
zero. If you enter
x = { }
print type(x), rowdim(x), "by", coldim(x), "matrix"
O-Matrix will respond
logical 0 by 0 matrix
If you want to clear the memory reserved for a variable and guard against its value being used by mistake, you should use novalue: 6.3.16 instead of an
empty matrix.
When using the brackets and braces to combine matrices, it is admissible for some of the matrices to be 0 by 0 matrices. Such matrices do not add any
elements during the combine operation. If you enter
x = []
y = {1, x, 2}
O-Matrix will respond
{
1
2
}
3.6.e: Reference
If the value types do not agree, O-Matrix will coerce the values as detailed in the coercion: 4.4 section.
3.7: Terminating An O-Matrix Session
Syntax
exit
halt: 5.7 , stop: 3.13 , quit: 21.1
3.7.a: Description
Exits an O-Matrix session.
3.7.b: Tutorial
If you enter
exit
O-Matrix will prompt you to save your session or editor window (provided that you have selected this feature in the "Options" menu) and will return
you to the Windows Program Manager.
3.8: Explicit Inclusion of Commands or Functions from a File
Syntax
include file_name
auto_include: 3.9 , debugger include: 21.2
Menu Command Command | Include . . .
3.8.a: Description
Reads commands from the file specified by file_name: 26.p .
3.8.b: Including From the Command Line
The include directive executes a set of previously written O-Matrix instructions. If the file temp.oms contains
I = {[1, 0], [0, 1]}
print I
and, in the Command window, you enter
include temp.oms
O-Matrix will respond
(If
{
[ 1 , 0 ]
[ 0 , 1 ]
}
temp.oms does
not exist, this example will result in an error message.)
3.8.c: Including From a File
An included file can execute other files using the include directive. For example, if the text file TEMP2.OMS contains
clear
print "Hello World!"
include temp.oms
print "Goodbye World!"
and, in the Command window, you enter
include temp2.oms
O-Matrix will respond
Hello World!
{
[ 1 , 0 ]
[ 0 , 1 ]
}
Goodbye World!
O-Matrix will ignore any attempt by an included file to execute a file that has already been included (unless a clear was entered after the previous
include). A previously included file, however, can be included at the O> prompt.
3.8.d: Searching For The File
If file_name begins with a disk drive specification; i.e., if its second character is a :, no path is added to the file specification when searching for it.
If file_name begins with the root directory, i.e., if its first character is a \, the root directory on the current disk is searched for the specified file. (The
current disk corresponds to the first letter returned by the cwd: 6.5.5 function.)
If the first character in file_name is not a \ and the second character is not a :, the directories specified by the current O-Matrix path: 20.2 setting will
be searched in order for an occurrence of the specified file. The current directory: 6.5.5 is searched after the search path for the specified file. If the file
does not exist in any of the specified locations, and error message occurs.
3.8.e: Reference
Files can be automatically included: 3.9 .
The include command is not available in Mlmode: 25 .
A list of all the currently included files can be obtained using the Debugger include: 21.2 command.
The syntax mlmode file_name can be used to execute a file that is written using the Mlmode: 25 language.
Automatic includes: 3.9 differ from the include: 3.8 command in that the current directory is searched before the search path for automatic includes.
Thus the include command should be used by library files that want to reference another file in the library and not in the current working directory.
3.9: Implicit Inclusion of Commands or Functions from a File
Syntax name
3.9.a: Description
If there is no variable or function currently in scope: 26.aj that corresponds to the identifier: 26.t specified by name, O-Matrix will search the
current directory: 6.5.5 for a file with the corresponding file name: 3.9.b . If such a file is found, it is put at the top of the current input stream and the
first statement of the file is then executed. This statement is expected to define the value for name where it is used. If the statement does not define
such a value, novalue: 6.3.16 is used for name.
3.9.b: File Name
In O-Matrix mode, the file name.oms is searched for. In Mlmode: 25 , the file name.m is searched for.
3.9.c: Example
In the following example, we ensure that the entire file is executed immediately because it consists of a single block: 5.2 statement. If the file
consists of the following text
temp.oms in the current directory
begin
x
= seq(3)
temp = x * x'
end
and you enter
clear
print temp
O-Matrix will respond
{
[ 1 , 2 , 3 ]
[ 2 , 4 , 6 ]
[ 3 , 6 , 9 ]
}
In addition, a message informing you of the automatic include of the file temp.oms is printed in the Debugger window.
3.9.d: Path
If the corresponding file name: 3.9.b is not found in the current directory, the directories in the current path: 20.2 are searched in order for an
occurrence of the file. (Note that the search path is different in Mlmode: 20.2.e .)
3.9.e: Mlmode
In Mlmode, the syntax omatrix file name can be used to execute the corresponding file in O-Matrix mode. This syntax is described in more detail in
the File Name: 25.1.d heading of the Switching Between Mlmode And O-Matrix Mode: 25.1 section.
3.9.f: Reference
The include: 3.8 command differs from the automatic includes described here in that the search path is searched before the current directory for
include: 3.8 commands. Thus the include command should be used by library files that want to reference another file in the library and not in the
current working directory.
Syntax
# text
... text
#begin##
text #end##
3.10.a: Description
All of the characters in text are comments and are ignored by O-Matrix. In the case of the # character, text is all the characters following the #
character up to but not including the next end of line. In the case of the ... characters, text is all the characters following the # character up to and
including the next end of line. In the case of the #begin## and #end##, text is all the characters after the #begin## and before the next #end## and
may include any number of end of line characters.
Note that, from the description above, ... can be used to continue a statement on the next input line.
3.10.b: Example
If you enter
print
1 + 2
# a simple calculation
O-Matrix will respond
3
If you enter
print ...
1 + 2
a simple calculation
O-Matrix will respond
3
Multiple line comments cannot be entered at the command line. If the file temp.oms contains
#begin##
a simple calculation
#end##
print 1 + 2
and at the command line you enter
include temp.oms
O-Matrix will respond
3
3.10.c: Mlmode
In Mlmode: 25 , the % character is used in place of the # character in comments. If the file temp.m contains
%begin%%
a simple calculation
%end%%
1 + 2
and in Mlmode you enter
clear
temp
O-Matrix will respond
3
3.11: Default Printing Of An Expression
Syntax expression
expression;
3.11.a: Description
If the ; is not present, displays the value of the expression.
3.11.b: Tutorial
3.11.b.a: Scalars
You can print a scalar by entering
2.3e-3
results in
0.0023
3.11.b.b: Vectors
You can display the row vector
( i , 1 , 2 + 3 i)
by entering
[1i0, 1, 2 + 3i0]
to which O-Matrix will respond
[ (0,1) , (1,0) , (2,3) ]
If you print a row vector containing characters, O-Matrix will not display the brackets or commas. For example,
["a", "b", "c"]
results in
abc
3.11.b.c: Matrices
You can display the matrix
/ 1
\ 4
2
5
3 \
6 /
by entering
{[1, 2, 3], [4, 5, 6]}
O-Matrix will respond
{
[ 1 , 2 , 3 ]
[ 4 , 5 , 6 ]
}
Note that O-Matrix displays each row on a separate line. If the expression is followed by a semicolon or has no value, it is not printed. If you enter
novalue
or
{[1, 2, 3], [4, 5, 6]};
O-Matrix will not display output in the Command window.
3.12: Printing A List Of Expressions
Syntax print list of values
3.12.a: Description
Displays a list of values: 26.w on the screen.
3.12.b: Tutorial
The print expression: 3.11 section contains examples of how a single value is displayed. You can use the print statement to display several values at
once by separating them with commas. If you enter
print 1, 2.1, 1i0
O-Matrix will respond
1
2.1
(0,1)
Unlike when expression are printed: 3.11 by default, if a matrix is defined but has no value, O-Matrix displays its value as novalue. If you enter
x = novalue
print x
O-Matrix will respond
novalue
3.12.c: Reference
Extra separating characters are displayed around a matrices values. These depend on the dimensions of the matrix and are defined below.
3.12.c.a: Scalars
A space is printed after a scalar.
3.12.c.b: Character Row Vectors
A space is printed after a character row vector.
3.12.c.c: Other Row Vectors
A left bracket and space are printed before the vector. The elements of the vector are separated by a space, comma, and another space. A space, right
square bracket, and another space are printed after the vector.
3.12.c.d: Character Matrix
A carriage return is printed before the matrix and after each row.
3.12.c.e: Other Matrices
A left brace and carriage return are printed before the matrix. Each row is then printed according to the rules for row vectors followed by a carriage
return. A right brace and carriage return are printed after the matrix.
3.13: Suspending Program Execution And Entering Debugger
Syntax
stop list
halt: 5.7 , continue: 21.4 , quit: 21.1
Menu Command Debug | Enter Debugger
3.13.a: Description
Enters the debugger and displays the specified list of values, if list is present.
3.13.b: Tutorial
If you enter
stop
O-Matrix will activate the Debugger window and the DEBUG>: 26.k prompt. (To exit the debugger, enter quit: 21.1 at the prompt.)
If you enter
stop "Entering debugger"
O-Matrix will print
Entering debugger
in the Command window and then and will activate the debugger window.
You can also activate the Debugger window by clicking on the O>: 26.z prompt. See the debugger: 21 section for a list of the commands available in
the debugger.
3.14: Determining The Column Dimension Of A Matrix
Syntax coldim(matrix)
3.14.a: Description
Returns the number of columns in a matrix.
3.14.b: Example
x = {[1, 2, 3], [4, 5,
coldim(x)
6]}
returns
3
3.15: Determining The Row Dimension Of A Matrix
3.15.a: Syntax
rowdim(matrix)
3.15.b: Description
Returns the number of rows in a matrix.
3.15.c: Example
x = {[1, 2, 3], [4, 5, 6]}
rowdim(x)
returns
2
3.16: Determining the Dimensions of a Matrix
Syntax size(x)
[m, n] = size(x)
size(x, d)
3.16.a: Description
Returns the number of rows and columns in the matrix x.
size(x)
returns a two element integer row vector with the first element equal to the number of rows in x and the second element equal to the number of
columns in x.
[m, n] = size(x)
sets the integer scalar m equal to the number of rows in x and the integer scalar n equal to the number of columns in x.
size(x, d)
If d is equal to one, returns an integer scalar equal to the number of rows in x. If d is equal to two, returns an integer scalar equal to the number of
columns in x. The argument d must be an integer, real or double-precision scalar equal to one or two.
3.16.b: Example
If you enter
size( rand(2, 3) )
[ 2 , 3 ]
3.17: Changing Matrix Dimensions
Syntax dim variable(rows, columns)
3.17.a: Description
Changes the number of rows and columns in a matrix, where rows and columns are non-negative integer scalars.
3.17.b: Tutorial
You can use the dim statement to change the dimensions of an existing matrix. If you enter
y = seq(12)
dim y(3, 4)
print y
the dim statement places the first three elements
of y, and so on. O-Matrix will respond
{
[ 1 , 4 , 7 , 10 ]
[ 2 , 5 , 8 , 11 ]
[ 3 , 6 , 9 , 12 ]
}
of the sequence in the first column of y, the next three elements of the sequence in the second column
If you continue the example above by entering
dim y(2, 6)
print y
O-Matrix first converts y to a vector in column major order: 26.c . O-Matrix then converts the vector into a matrix with the specified dimensions.
O-Matrix will respond
[ 1 , 3 , 5 , 7 , 9 , 11 ]
[ 2 , 4 , 6 , 8 , 10 , 12 ]
3.18: Copying and Changing the Dimensions of a Matrix
Syntax y = reshape(x, m, n)
y = reshape(x, [m, n])
3.18.a: Description
Returns a copy of the matrix x with m rows and n columns. The column major ordering: 26.c of both x and y correspond to same vector. The
arguments m and n are scalars, equal to non-negative integers, and their product must equal the product of the row: 3.15 and column: 3.14 dimensions
of x.
3.18.b: Example
If you enter
x = [{1, 2, 3}, {4, 5, 6}]
reshape(x, 2, 3)
{
[ 1 , 3 , 5 ]
[ 2 , 4 , 6 ]
}
--------------------------------------------------------------------------
Syntax matrix(:)
3.19.a: Description
Treats a matrix as if it were a column vector in column major order; i.e., its first column followed by its second and so on.
3.19.b: Tutorial
If you enter
x = {[ 1 , 2 ], [ 3 , 4 ]}
print x(:)
O-Matrix will respond
{
1
3
2
4
}
Using the colon notation, you can store one matrices elements in another matrix so long as they have the same number of elements. If you continue by
entering
x(:) = { 1, 2, 3, 4 }
print x
O-Matrix will respond
{
[ 1 , 3 ]
[ 2 , 4 ]
}
4: Expressions
4.a: Contents
Positive Sign: 4.1
Negative Sign: 4.2
Automatic Conversion To A Higher Type: 4.4
Subtraction: 4.5
Element-By-Element Multiplication: 4.6
Element-By-Element Division: 4.7
Testing Numeric And Logical Equality: 4.8
Ordered Numeric And Logical Comparisons: 4.9
Logical Operators: 4.10
Matrix Multiplication: 4.11
Linear Equations and Least Squares: 4.12
Element-By-Element Exponentiation: 4.13
Matrix Transpose: 4.14
The Norm Operator: 4.15
Testing String Equality: 4.16
Ordered String Comparisons: 4.17
Sequence Operator: 4.18
Order Of Operations: 4.19
4.1: Positive Sign
Syntax +value
4.1.a: Description
Has no effect; can be used as a place holder.
4.1.b: Tutorial
If you type
+5
O-Matrix will respond
5
4.2: Negative Sign
Syntax -value
4.2.a: Description
Negates value, where value is an integer, real, double-precision or complex matrix.
4.2.b: Tutorial
If you type
-5
O-Matrix will respond
-5
Syntax left value + right value
4.3.a: Description
Element-by-element: 26.n addition of two values that are integer, real, double-precision, or complex. (One, but not both, of the values may be logical.)
4.3.b: Tutorial
If you enter
1 + 2
O-Matrix will respond
3
If you enter
x = {[1, 2, 3], [4, 5, 6]}
y = {[1, 1, 1], [1, 1, 1]}
x + y
O-Matrix will print
{
[ 2 , 3 , 4 ]
[ 5 , 6 , 7 ]
}
If one value is a scalar and the other is a matrix, O-Matrix will add the scalar to each element of the matrix. Entering
x = {[1, 2, 3], [4, 5, 6]}
x + 1
will result in
{
[ 2 , 3 , 4 ]
[ 5 , 6 , 7 ]
}
4.3.d: Reference
If the value types do not agree, O-Matrix will coerce the values as detailed in the coercion: 4.4 table.
4.4: Automatic Conversion To A Higher Type
4.4.a: Description
The numeric types in O-Matrix, together with the logical type, have the following order from lowest to highest
Coercion Order
logical -> char -> int -> real -> double -> complex
Many operators or function that allow arguments of different types provided that all the types are in the set listed above. All of the arguments are
converted to the same type, and then operation is performed. The type chosen is the highest type of any of the arguments.
4.4.b: Example
If you enter
x = 3.1
y = 1i0
print x + y
O-Matrix will respond
(3.1,1)
In the print statement above, O-Matrix converted the left operand to a complex number before adding. The value of x, however, is still real.
The rules for converting values to each of the possible types, are described in the int: 6.4.2 , char: 6.4.6 , real: 6.4.3 , double: 6.4.4 , and complex: 6.4.5
sections.
4.5: Subtraction
Syntax left value - right value
4.5.a: Description
Element-by-element: 26.n subtraction of the right value from the left where the values that are integer, real, double-precision, or complex. (One, but
not both, of the values may be logical.)
4.5.b: Tutorial
4.5.b.a: Subtracting Scalars
If you enter
1 - 2
O-Matrix will respond
-1
4.5.b.b: Subtracting Matrices
If you enter
x = {[1, 2, 3], [4, 5, 6]}
y = {[1, 1, 1], [1, 1, 1]}
x - y
O-Matrix will print
{
[ 0 , 1 , 2 ]
[ 3 , 4 , 5 ]
}
4.5.c: Subtracting Scalars from Matrices
If the left value is a matrix and the right value is a scalar, O-Matrix will subtract the scalar from each element of the matrix. Entering
x = {[1, 2, 3], [4, 5, 6]}
x - 1
will result in
{
[ 0 , 1 , 2 ]
[ 3 , 4 , 5 ]
}
4.5.d: Subtracting Matrices from Scalars
If the left value is a scalar and the right value is a matrix, O-Matrix will subtract each element of the matrix from the scalar. Entering
x = {[1, 2, 3], [4, 5, 6]}
1 - x
will result in
{
[ 0 , -1 , -2 ]
[ -3 , -4 , -5 ]
}
4.5.e: Reference
If the value types do not agree, O-Matrix will coerce the values as detailed in the coercion: 4.4 table.
4.6: Element-By-Element Multiplication
Syntax left value % right value
4.6.a: Description
Element-by-element: 26.n multiplication of two values that are integer, real, double-precision, or complex. (One, but not both, of the values may be
logical.)
4.6.b: Tutorial
4.6.b.a: Multiplying Scalars
If you enter
6 % 2
O-Matrix will respond
12
4.6.b.b: Multiplying Matrices
If you enter
x = {[1, 2, 3], [4, 5, 6]}
y = {[2, 2, 2], [2, 2, 2]}
x % y
O-Matrix will print
{
[ 2 , 4 , 6 ]
[ 8 , 10 , 12 ]
}
4.6.b.c: Multiplying Scalars by Matrices
If one value is a scalar and the other is a matrix, O-Matrix will multiply the scalar by each element of the matrix. Entering
x = {[1, 2, 3], [4, 5, 6]}
x % 2
will result in
{
[ 2 , 4 , 6 ]
[ 8 , 10 , 12 ]
}
4.6.c: Reference
If the value types do not agree, O-Matrix will coerce the values as detailed in the coercion: 4.4 table.
4.7: Element-By-Element Division
Syntax left value / right value
4.7.a: Description
Element-by-element: 26.n division of the left value by the right where the two values that are integer, real, double-precision, or complex. (One, but not
both, of the values may be logical.)
4.7.b: Tutorial
4.7.b.a: Integer Division
If both values are integers, O-Matrix will drop the fractional parts of the resulting matrix. If you enter
5 / 2
O-Matrix will respond
2
If you enter
-5 / 2
O-Matrix will respond
-2
4.7.b.b: Floating Point Division
If one of the values is real, double-precision or complex, the result will contain the fractional part. If you enter
5 / 2.
O-Matrix will respond
2.5
4.7.b.c: Dividing Matrices
If you enter
x = {[2, 4, 6], [8, 10, 12]}
y = {[2, 2, 2], [2, 2, 2]}
x / y
O-Matrix will print
{
[ 1 , 2 , 3 ]
[ 4 , 5 , 6 ]
}
4.7.b.d: Dividing Scalars by Matrices
If the left value is a scalar and the right value is a matrix, O-Matrix will divide the scalar by each element of the matrix. Entering
x = {[1, 2, 3], [4, 5, 6]}
60 / x
will result in
{
[ 60 , 30 , 20 ]
[ 15 , 12 , 10 ]
}
4.7.c: Dividing Matrices by Scalars
If the left value is a matrix and the right value is a scalar, O-Matrix will divide each element of the matrix by the scalar. Entering
x = {[2, 4, 6], [8, 10, 12]}
x / 2
will result in
{
[ 1 , 2 , 3 ]
[ 4 , 5 , 6 ]
}
4.7.d: Reference
If the value types do not agree, O-Matrix will coerce the values as detailed in the coercion: 4.4 table.
4.8: Testing Numeric And Logical Equality
Syntax left value == right value
(equal)
(not equal)
left value <> right value
See Also ordered: 4.9 , equal: 6.6.6 , all: 6.6.1 , any: 6.6.3 , and string ==: 4.16
4.8.a: Description
Tests the equality of two logical, integer, real, double-precision or complex values.
Comparisons using the equal (==) and not equal (<>) operators return logical matrices with dimensions equal to the matrices being compared. An
element of the result is true (which O-Matrix prints as T) if the condition is true for the corresponding elements of the two matrices, or false (which OMatrix prints as F) if it is not. If a matrix is compared with a scalar, O-Matrix compares the scalar value with the value of each individual element of
the matrix.
4.8.b: Tutorial
4.8.b.a: Comparing Scalars
If you enter
x = 4
y = 8
print y == x
O-Matrix will respond
F
O-Matrix does not consider matrix type when testing equality (because it performs coercion: 4.4 before making the test). If you enter
x = 1
y = 1.
print y == x
O-Matrix will respond
T
even though x is an integer and y is a real number.
4.8.b.b: Assigning Logical Values
Variables can be set equal to logical values. If you enter
z = 2 <> 3
z
O-Matrix will respond
T
Variables can also be directly assigned the logical values true or false. Entering
x = true
x
results in
T
4.8.b.c: Comparing Matrices
When testing the equality of two non-scalars, O-Matrix returns a matrix of the same dimension as the matrices being compared. For example, if you
enter
u = { 4, 3, 2, 1, 9 }
v = { 9, 2, 2, 2, 9 }
u == v
O-Matrix will respond
{
F
F
T
F
T
}
If you enter
x = {[1, 2], [2, 1]}
y = {[2, 1], [2, 1]}
x == y
O-Matrix will respond
{
[ F , F ]
[ T , T ]
}
4.8.b.d: Comparing Matrices with Scalars
When comparing a matrix with a scalar, the result has the same dimension as the matrix. Each element of the result corresponds to comparing an
element of the matrix with the scalar. For example, if you enter
x = {[1, 2], [3, 4]}
x == 2
O-Matrix will respond
{
[ F , T ]
[ F , F ]
}
4.8.c: Reference
If the value types do not agree, O-Matrix will coerce the values as detailed in the coercion: 4.4 section.
4.9: Ordered Numeric And Logical Comparisons
Syntax left value < right value
(less than)
(greater than)
left value > right value
(less than or equal to)
left value <= right value
(greater than or equal to)
left value >= right value
See Also logical operators: 4.10 , equality: 4.8 , any: 6.6.3 , all: 6.6.1 and string order: 4.17
4.9.a: Description
Compares two values that are integer, real, or double-precision. (One, but not both, of the values may be logical.)
You can compare a matrix with another matrix of the same dimension or with a scalar. The result is a logical matrix with the same dimension as the
original matrix.
4.9.b: Tutorial
4.9.b.a: Comparing Scalars
If you enter
x = 4
y = 8
print y > x
O-Matrix will respond
T
4.9.b.b: Comparing Matrices
O-Matrix compares each element of the two matrices individually, and generates a logical matrix of the same dimension as the matrices being
compared. For example, if you enter
x = [1, 2, 3, 4, 8]
y = [1, 2, 3, 5, 6]
x < y
O-Matrix will respond
[ F , F , F , T , F ]
because the first three elements of x and y are equal, the fourth element of x is less than the corresponding element of y, and the fifth element of x is
greater than the fifth element of y.
4.9.b.c: Comparing Matrices With Scalars
When comparing a matrix with a scalar, the result has the same dimension as the matrix. Each element of the result corresponds to comparing an
element of the matrix with the scalar. For example, if you enter
x = {[1, 2], [3, 4]}
x <= 2
O-Matrix will respond
{
[ T , T ]
[ F , F ]
}
4.9.c: Reference
If the matrix types do not agree, O-Matrix will coerce the values as detailed in the coercion: 4.4 section.
4.10: Logical Operators
Syntax left and right
left or right
not value
See Also xor: 6.7 , ordered: 4.9 , any: 6.6.3 , all: 6.6.1
4.10.a: Description
Computes the element-by-element: 26.n result for expressions that use the and, or and not operators. The values left, right, and value are logical
operands.
The and, and or operators combine two logical values, whereas the not operator negates a single logical value.
4.10.a.a: Combining Logical Expressions
If both values joined by the and operator are true, the combined expression is true. If you enter
x = 1 < 2
y = 3 > 4
print x and y
O-Matrix will respond
F
because, although x is true, y is false.
If at least one of the values joined by the or operator is true, the combined expression is true. If you enter
x = 1 < 2
y = 3 > 4
x or y
O-Matrix will respond
T
because, although y is false, x is true.
4.10.a.b: Negating Logical Expressions
The not operator negates the logical value it precedes. If you enter
x =
y =
z =
not
[1, 2]
[4, 2]
x == y
z
O-Matrix will respond
[ T , F ]
because the first element of z is false and the second element of z is true.
4.10.a.c: Combining Logical Matrices
Logical operators act on matrices in an element-by-element: 26.n manner. If you enter
x = {[true, false], [true, false]}
y = {[true, true], [false, false]}
x and y
O-Matrix will respond
{
[ T , F ]
[ F , F ]
}
If you continue by entering
x and true
O-Matrix will respond
{
[ T , F ]
[ T , F ]
}
4.11: Matrix Multiplication
Syntax left value * right value
4.11.a: Description
Matrix multiplication of two values that are integer, real, double-precision, or complex. (One, but not both, of the values may be logical.)
4.11.b: Tutorial
4.11.b.a: Multiplying Scalars
If you enter
6 * 2
O-Matrix will respond
12
4.11.b.b: Multiplying Matrices
If you enter
x = {[1, 2, 3], [4, 5, 6]}
y = {[2, 4], [2, 4], [2, 4]}
x * y
O-Matrix will print
{
[ 12 , 24 ]
[ 30 , 60 ]
}
4.11.b.c: Multiplying Scalars by Matrices
If one value is a scalar and the other is a matrix, O-Matrix will multiply the scalar by each element of the matrix. Entering
x = {[1, 2, 3], [4, 5, 6]}
x * 2
will result in
{
[ 2 , 4 , 6 ]
[ 8 , 10 , 12 ]
}
4.11.c: Reference
If the value types do not agree, O-Matrix will coerce the values as detailed in the coercion: 4.4 table.
If one value is a scalar, the result has the same dimension as the other value. If neither value is a scalar, the column dimension of the left value must
match the row dimension of the right value. In this case, the result has the same number of rows as the left value and the same number of columns as
the right value.
If the column dimension of the left value is zero, the resulting matrix has all of its elements equal to zero. If you enter
x = fill(1, 2, 0)
y = fill(1, 0, 3)
x * y
O-Matrix will respond
{
[ 0 , 0 , 0 ]
[ 0 , 0 , 0 ]
[ 0 , 0 , 0 ]
}
4.12: Linear Equations and Least Squares
Syntax left value \ right value
See Also matrix multiplication: 4.11 , element-by-element division: 4.7 , inv: 12.2
4.12.a: Description
Solves for the matrix that yields the right value when multiplied by the left value, where the values are real, double-precision, or complex. If the left
value is not a square matrix, the result is the least-squares solution.
4.12.b: Tutorial
4.12.b.a: Scalars
If the left value is a scalar, the result is the element-by-element division of the left value into the right value. If you enter
print 5 \ [ 2.0 , 3.0 ]
O-Matrix will respond
[ 0.4 , 0.6 ]
4.12.b.b: Dividing by Square Matrices
You can solve the linear equation A x = b using the matrix divide operator (\). For example, to solve the system of equations
2 x + 3 y = 4
3 x + 5 y = 2
which can be represented as
/ 2
|
\ 3
3 \ / x \
| |
|
5 / \ y /
/ 4 \
= |
|
\ 2 /
enter
A = {[2., 3.], [3., 5.]}
b = {4., 2.}
A \ b
O-Matrix will then respond
{
14
-8
}
4.12.b.c: Solving Linear Least Squares Equations
You can also solve linear least squares equations using the matrix divide operator. To find the least squares solution of the equations
4 x = 2
3 x = 2
enter
A = {4., 3.}
b = {2., 2.}
A \ b
to which O-Matrix will respond
0.56
This is the solution to the problem
2
minimize (4 x - 2)
2
+
(3 x - 2)
with respect to x
4.12.c: Algorithm
If the left value is a square matrix: 26.ak an LU factorization is used to solve the linear equations. Otherwise, a QR factorization is used to solve the
linear least square problem.
4.12.d: Reference
If the value types do not agree, O-Matrix will coerce the values as detailed in the coercion: 4.4 table (unless the result would be an integer, in which
case the result is double-precision).
If the left value is not a scalar, the row dimensions of the left and right values must be equal. In this case, the row dimension of the result is equal to
the column dimension of the left value. The column dimension of the result is equal to the column dimension of the right value.
4.13: Element-By-Element Exponentiation
Syntax base ^ exponent
4.13.a: Description
Element-by-element: 26.n exponentiation of base to exponent, where base and exponent are integer, real, double-precision, or complex. (One, but not
both, of the values may be logical.)
4.13.b: Tutorial
4.13.b.a: Scalar Exponentiation
If you enter
6^2
O-Matrix will respond
36
4.13.b.b: Exponentiation by a Matrices
If you enter
x = {[1, 2, 3], [4, 5, 6]}
y = {[2, 2, 2], [2, 2, 2]}
x^y
O-Matrix will print
{
[ 1 , 4 , 9 ]
[ 16 , 25 , 36 ]
}
4.13.b.c: Exponentiation by a Scalar
If you enter
x = {[1, 2, 3], [4, 5, 6]}
x^2
O-Matrix will respond
{
[ 1 , 4 , 9 ]
[ 16 , 25 , 36 ]
}
4.13.b.d: Exponentiation of a Scalar
If you enter
x = {[1, 2, 3], [4, 5, 6]}
2^x
O-Matrix will respond
{
[ 2 , 4 , 8 ]
[ 16 , 32 , 64]
}
4.13.c: Reference
If the value types do not agree, O-Matrix will coerce the values as detailed in the coercion: 4.4 table.
Exponentiation to a fractional power can be ambiguous. For example, both i and -i are square roots of -1. O-Matrix uses a polar representation of the
base when performing complex exponentiation.
Suppose that z is a complex base and w is a real exponent. O-Matrix expresses z as
i theta
z = r e
where r is real and -pi < theta < pi. The result is defined by
w
z
w
= r
i theta w
e
4.14: Matrix Transpose
Syntax value'
4.14.a: Description
Transposes the rows and columns of value, where value is an logical, character, integer, real double-precision or complex matrix.
4.14.b: Tutorial
If you enter
x = {[1, 2], [3, 4]}
print x'
O-Matrix will respond
{
[ 1 , 3 ]
[ 2 , 4 ]
}
The transpose operator interchanges the row and column dimensions. For example,
x = {[1, 2], [3, 4], [5, 6]}
print x'
will result in
{
[ 1 , 3 , 5 ]
[ 2 , 4 , 6 ]
}
4.15: The Norm Operator
Syntax | value |
4.15.a: Description
Returns the norm of an integer, real, double-precision, or complex value. An integer or real value returns a real scalar, and a double-precision or
complex value returns a double-precision scalar.
If the value is not complex, the norm is the square root of the sum of the squares of its elements. If the value is complex, the norm is the square root of
the sum of the squares of the real and imaginary parts of its elements.
4.15.b: Tutorial
4.15.b.a: Scalar Norm
If the value is a scalar, the result is its absolute value.
print |-1|
O-Matrix will respond
1
4.15.b.b: Vector Norm
If the value is a vector, the result is the corresponding distance. For example
print |[3, 4]|
will result in
5
4.16: Testing String Equality
Syntax left value == right value (equal)
left value <> right value (not equal)
4.16.a: Description
Tests the row by row equality of two character matrices. If neither left value or right value is a row vector, they must have the same row dimension.
Comparisons of character matrices using the equal (==) and not equal (<>) operators return a logical column vector. The i-th element of the return
value corresponds to the comparison between the i-th row of the left and right values. O-Matrix considers two rows to be equal if they contain the
same characters in the same order not counting trailing spaces.
4.16.b: Tutorial
4.16.b.a: Comparing Strings
If you enter
x = "string 1"
y = "string 2"
print x == y
O-Matrix will respond
F
4.16.b.b: Comparing Matrices
If you enter
v = {"one ", "two"}
w = {"one",
"one"}
v == w
O-Matrix will respond
{
T
F
}
Note that the string "one " is equal to the string "one" because the trailing space in "one " is ignored.
4.16.b.c: Comparing Matrices with Strings
If one of the operand is a row vector, each row of the other operand is compared to the row vector. If you enter
v = {"one ", "two"}
v == "one"
O-Matrix will respond
{
T
F
}
4.17: Ordered String Comparisons
Syntax left value < right value
(less than)
(greater than)
left value > right value
(less than or equal to)
left value <= right value
(greater than or equal to)
left value >= right value
4.17.a: Description
Tests the row by row ordering of two character matrices. If neither left value nor right value is a row vector, they must have the same row dimension.
Ordered comparisons of character matrices return a logical column vector. The i-th element of the return value corresponds to the comparison between
the i-th row of the left and right values.
If the left and right values are character row vectors the first element of the left value that is not equal to the corresponding element of the right value
determines the result of the ordered comparison. Trailing spaces in the values are ignored.
4.17.b: Tutorial
4.17.b.a: Comparing Strings
If you enter
x = "abc"
y = "aaz"
print x > y
O-Matrix will respond
T
because the ASCII value of the second element of x is greater than the ASCII value of the second element of y.
If all of the elements of a string are equal to the corresponding elements of a longer string, the longer string is considered to be "greater." Thus, if you
enter
x = "abc"
y = "abcd"
print x < y
O-Matrix will respond
T
because y is longer, and thus "greater", than x.
4.17.b.b: Comparing Matrices
O-Matrix compares each row of two matrices individually, and generates a logical column vector with the same row dimension as the matrices being
compared. If you enter
v = {"one ", "one A"}
w = {"one", "one"}
v > w
O-Matrix will respond
{
F
T
}
because the vectors "one " and "one" are considered equal while the vector "one A" is considered greater than the vector "one".
4.17.b.c: Comparing Matrices With Strings
If one of the values is a row vector, each row of the other value is compared to the row vector. If you enter
v = {"one
v > "one"
", "one A"}
O-Matrix will respond
{
F
T
}
4.18: Sequence Operator
Syntax start : : finish
start : step : finish
4.18.a: Description
Creates a column vector in which the initial value is start, each successive element changes by a value of step, and the final value is finish, where start,
step, and finish are integer, real, or double-precision scalars. If step is not specified, the value 1 is used in its place.
4.18.b: Tutorial
If you enter
2 :: 4
O-Matrix will respond
{
2
3
4
}
If you enter
2 : 2 : 6
O-Matrix will respond
{
2
4
6
}
The value step can also be negative. If you enter
6 : -2 : 2
O-Matrix will respond
{
6
4
2
}
The values can be integer, real, or double-precision. If you enter
0 : .5 : 1.
O-Matrix will respond
{
0
.5
1.
}
4.18.c: Reference
It is an error for step to be 0.
If step is less than 0 and start is greater than finish, the result is an empty matrix. In addition, if step is greater than 0 if start is less than finish, the
result is an empty matrix. For example, if you enter
1 : 1 : 0
O-Matrix will respond
{ }
which signifies a matrix with no rows.
If start, step, and finish are not of the same type, O-Matrix will coerce the values as detailed in the coercion: 4.4 section.
4.19: Order Of Operations
4.19.a: Description
O-Matrix performs operations in a set order. The following table lists the O-Matrix operators. If an operator is above another in the table, it is
performed first. If two operators appear on the same line of the table, the expression is evaluated from left to right.
operator
description
'
transposition
^
exponentiation
* % /
multiplication and division
:
sequencing
== <> < > <= >= comparison
and or not
logical comparison
If you enter
5 + 3 * 10^2
O-Matrix will perform the exponentiation first, then the multiplication, and finally the addition. It will then respond
305
If you enter
12 / 2 * 3
O-Matrix will divide 12 by 2, and then multiply the result by 3. It will then respond
18
You can enclose an operation in parentheses to force O-Matrix to evaluate it first. If you enter
12 / (2 * 3)
O-Matrix will multiply 2 by 3, and then divide 12 by the result. It will then respond
2
5: Controlling Program Flow
5.a: Contents
If Statement: 5.1
Grouping A Sequence Of Statements As A Block: 5.2
For Statement: 5.3
While Statement: 5.4
Breaking Out Of For And While Loops: 5.5
Transferring Control Using The Goto Statement: 5.6
Halting Program Execution: 5.7
5.1: If Statement
Syntax if logical value then first statement
if logical value then first statement else second statement
See Also equality: 4.8 , ordered: 4.9 , block: 5.2 , goto: 5.6
5.1.a: Description
Executes the first statement if the logical value is true, where logical value is a scalar. If the second statement is present and the logical value is false,
the second statement is executed.
5.1.b: Tutorial
Because O-Matrix cannot process a line containing a partial statement the following examples cannot be typed at the O>: 26.z prompt. It can be copied
from the help file and pasted to the O>: 26.z prompt or run from an editor window.
If you enter
x = 8
y = 4
if x / y == 2 then print x, "/", y, "=", x / y
O-Matrix will respond
8 / 4 = 2
The statement following an else clause is executed if logical value is false. If you run the program
x = 4
y = 5
if x > y then z = 0
else z = 6
print z
O-Matrix will respond
6
More advanced examples that use the if statement can be found in the Block: 5.2 section of this chapter.
5.1.c: Reference
Directives: 26.m cannot be used in if statements unless as part of a block. (See the Block: 5.2 section of this chapter for more information.)
For example, if you enter
if 2 > 1 then const x = 1
O-Matrix will respond with an error message.
An else clause is grouped with the first preceding if clause that does not yet have an else clause grouped with it. If, from an editor window, you run
the program
if 2 > 1 then if 1 > 2 then z = 1
else z = 2
print z
O-Matrix will respond
2
The z = 2 statement was executed because 1 > 2 is false.
5.2: Grouping A Sequence Of Statements As A Block
Syntax begin statement list end
5.2.a: Description
Groups a list of program statements so they function as one.
5.2.b: Tutorial
A block is a list of statements that function as a single unit. You can use a block anywhere that O-Matrix allows a statement.
If you enter
if 2 >
x
y
x
end
1
=
=
+
then begin
1
2
y
O-Matrix will respond
3
Entering
x = -1
if x < 0 then begin
x
"negative"
end else begin
x
"positive"
end
will result in
-1
negative
Blocks can be used to create an arbitrary number of branches, or multi-way if-then-else. For example, if in an editor window you enter.
x = 0
if x < 0 then begin
"negative"
end else if x > 0 then begin
"positive"
end else begin
"zero"
end
and select 'File | Run' from the menu, O-Matrix will respond
zero
5.3: For Statement
Syntax for variable = start to finish block
5.3.a: Description
Executes block: 5.2 the specified number of times where start and finish are integer scalars.
The variable is initialized with the value start and is incremented by one each time the block is executed. It has the value finish the last time the block
is executed.
5.3.b: Tutorial
If you enter
for i = 1 to 3 begin
print i
end
O-Matrix will respond
1
2
3
A variable defined before the for statement can be used to accumulate a result. For example, to calculate 5!, which is 5 x 4 x 3 x 2 x 1, enter
fact = 1
for i = 1 to 5 begin
fact = fact * i
end
print fact
which will result in
120
You can nest a for statement within another loop. For example,
for i = 1 to 2 begin
for j = 2 to 5 begin
print "i =", i, " j =", j
end
end
will result in
i
i
i
i
i
i
i
i
=
=
=
=
=
=
=
=
1
1
1
1
2
2
2
2
j
j
j
j
j
j
j
j
=
=
=
=
=
=
=
=
2
3
4
5
2
3
4
5
5.3.c: Reference
The limits of the for loop are evaluated only before the first execution of the block. If you enter
n = 3
for i = 1 to n begin
n = 2
print i
end
O-Matrix will respond
1
2
3
5.4: While Statement
Syntax whilevalue block
See Also block: 5.2 , for: 5.3 , goto: 5.6 , if: 5.1
5.4.a: Description
Repeats execution of block: 5.2 while value is true, where value is a logical scalar.
5.4.b: Tutorial
If you enter
x = 1
while x < 4 begin
print x
x = x + 1
end
O-Matrix will respond
1
2
3
A variable defined before the while statement can be used to accumulate a result. For example, to calculate 5! enter
fact = 1
i
= 1
while i <= 5 begin
fact = fact * i
i
= i + 1
end
print fact
which would result in
120
You can nest a while statement within another loop. For example,
i = 2
while i > 0 begin
j = 5
while j < 10 begin
print "i =", i, "; j =", j
j = j + 3
end
i = i - 1
end
will result in,
i = 2 ; j = 5
i = 2 ; j = 8
i = 1 ; j = 5
i = 1 ; j = 8
5.5: Breaking Out Of For And While Loops
Syntax break
See Also while: 5.4 , for: 5.3 , goto: 5.6 , halt: 5.7
5.5.a: Description
Transfers execution just past the end of the currently enclosing while: 5.4 of for: 5.3 loop.
5.5.b: Tutorial
If you enter
x = 0
while x < 4 begin
x = x + 1
if x == 3 then break
print x
end
O-Matrix will respond
1
2
If you enter
for x = 1 to 4 begin
if x == 3 then break
print x
end
O-Matrix will respond
The
1
2
break statement aborts the inner
j = 0
for i = 1 to 2 begin
while true begin
j = j + 1
break
end
end
print j
most active while or for loop. If you enter
O-Matrix will respond
2
because the inner while loop is executed twice.
5.6: Transferring Control Using The Goto Statement
Syntax label label name
goto label name
5.6.a: Description
The goto statement transfers execution to the point specified by label name.
The goto and label statements must be within a block: 5.2 (a begin/end pair).
5.6.b: Tutorial
The goto statement can be used to calculate a factorial, as was done in the examples of for and while statements. For example, to calculate 5!, you
would enter
fact = 1
i
= 1
begin
label loop
fact = fact * i
i
= i + 1
if i <= 5 then goto loop
end
print fact
to which O-Matrix will respond
120
You can use the goto statement to jump out of a for or while loop. If you enter
begin
for i = 1 to 5 begin
if i > 3 then goto done
print i
end
label done
end
O-Matrix will respond
1
2
3
5.7: Halting Program Execution
Syntax
halt
quit: 21.1 , exit: 3.7
5.7.a: Description
Halts O-Matrix execution and returns control of the program to the O>: 26.z prompt.
5.7.b: Tutorial
If you enter
function f(x) begin
if x == 0 then begin
print "x cannot equal 0"
halt
end
return 1/x
end
print f(0)
O-Matrix will respond
x cannot equal 0
6: Elementary Functions
6.a: Groups of Functions
Algebraic Functions: 6.1
Transcendental Functions: 6.2
Special Matrices: 6.3
Special Functions: 16
Matrix Type Functions: 6.4
System Functions: 6.5
Checking For Certain Conditions: 6.6
6.b: Individual Functions
xor: 6.7
The Binary Logical Exclusive Or Operation
nextpow2: 6.8 Smallest Power of Two Greater or Equal a Specified Value
logspace: 6.10 Create a Grid With Evenly Spaced Logarithms
linspace: 6.9 Evenly Spaced Grid With a Specified Number of Points
coldiff: 6.11 Difference Between Successive Elements In Each Column
diff: 6.12
Finite Differences of Arbitrary Order
nozero: 6.13 Replaces Zero By a Small Value
6.1: Algebraic Functions
6.1.a: Contents
abs: 6.1.1
Absolute Value Function
sqrt: 6.1.2
The Square Root Function
max: 6.1.3
Determining The Maximum Element of a Matrix
pmax: 6.1.4
Determining The Indices Of The Maximum Element
maxs: 6.1.5
Computing The Maximum Element From Multiple Matrices
mins: 6.1.6
Computing The Minimum Element From Multiple Matrices
conj: 6.1.7
The Complex Conjugate Function
imag: 6.1.8
The Imaginary Part Function
sign: 6.1.9
The Sign Function
floor: 6.1.10
Largest Integer Less Than or Equal a Specified Value
ceil: 6.1.11
Smallest Integer Greater Than or Equal a Specified Value
round: 6.1.12
Rounding of to the Nearest Integer Value
roundoff: 6.1.13 Rounding Numbers To The Nearest Integer
mod: 6.1.14
Modulo Function
rem: 6.1.15
Remainder Function
colunmod: 6.1.16 Undo The Modulo Function
unwrap: 6.1.17 Unwrap Angles To Absolute Angles Above Two Pie
factorl: 6.1.18
The Factorial Function
primes: 6.1.19
Computing Prime Numbers
6.1.1: Absolute Value Function
Syntax abs(value)
6.1.1.a: Description
Returns the element-by-element: 26.n absolute value of value, where value is an integer, real, double-precision, complex, or character matrix.
6.1.1.b: Example
abs([-3, 4])
returns
[ 3 , 4 ]
6.1.1.c: Complex Case
If value is a complex matrix, the return value is a double-precision matrix. Each element of the return value is the square root of the sum of the square
of the real and imaginary parts of the corresponding element of value.
abs([1. + 1i0, 1. - 1i0])
returns
[ 1.41421 ,
1.41421 ]
6.1.1.d: Character Case
If value is a character matrix, the return value is an integer matrix. Each element of the return value is the numeric value of the ASCII characters in the
matrix.
abs("3 + 4i")
returns
[ 51 , 32 , 43 , 32 , 52 , 105 ]
6.1.2: The Square Root Function
Syntax sqrt(x)
6.1.2.a: Description
Returns the element-by-element: 26.n square root of x, where the elements of x are complex or non-negative real or double-precision numbers.
6.1.2.b: Example
a = 3.0
b = 4.0
sqrt(a^2 + b^2)
returns
5
6.1.2.c: Negative Arguments
Normally the return type for an element-by-element function is the same as its argument. This is the case for the sqrt function unless one of the
elements of x is less than zero in which case the return value is complex.
If you enter
sqrt([1., -1.])
O-Matrix will respond
[ (1,0), (0,1) ]
6.1.3: Determining The Maximum Element of a Matrix
Syntax max(matrix)
See Also pmax: 6.1.4 , maxs: 6.1.5 , mins: 6.1.6 , colmax: 15.42 , colrange: 15.13
6.1.3.a: Description
Returns the maximal element in matrix where matrix is an integer, real or double-precision matrix. The return value is a scalar with the same type as
matrix.
6.1.3.b: Example
max({[1, 2], [8, 3]})
returns
8
6.1.4: Determining The Indices Of The Maximum Element
Syntax pmax(matrix)
6.1.4.a: Description
Returns a two-element integer row vector containing the row and column indices of the maximal element of matrix, where matrix is an integer, real or
double-precision matrix.
6.1.4.b: Example
pmax({[1, 2], [8, 3]})
returns
[ 2 , 1 ]
because the maximal element of the matrix, 8, is in the second row and the first column of the matrix.
6.1.5: Computing The Maximum Element From Multiple Matrices
Syntax maxs(A1, A2, . . . , An)
6.1.5.a: Description
Returns the largest element out of all of the matrices listed as parameters. For each i, Ai is a character, integer, real, or double-precision matrix. If one
of the Ai is a character matrix, all of the Ai must be character matrices.
The return value is a scalar with the same type as the matrix containing the largest element.
6.1.5.b: Example
maxs([1, 2], 3, -5.12)
returns
3
6.1.6: Computing The Minimum Element From Multiple Matrices
Syntax mins(A1, A2, . . . , An)
6.1.6.a: Description
Returns the smallest element out of all of the matrices listed as parameters. For each i, Ai is a character, integer, real, or double-precision matrix. If one
of the Ai is a character matrix, all of the Ai must be character matrices.
The return value is a scalar with the same type as the matrix containing the largest element.
6.1.6.b: Example
mins([1, 2], 3, -5.12)
returns
-5.12
6.1.7: The Complex Conjugate Function
Syntax conj(z)
6.1.7.a: Description
Returns the element-by-element: 26.n complex conjugate of z, where z is an integer, real, double-precision, or complex matrix.
6.1.7.b: Example
z = 1 + 1i0
conj(z)
returns
(1,-1)
6.1.8: The Imaginary Part Function
Syntax imag(z)
See Also isreal: 6.6.10 , conj: 6.1.7 , double: 6.4.4 , real: 6.4.3 , complex: 6.4.5
6.1.8.a: Description
Returns the element-by-element: 26.n imaginary part of z, where z is a complex, double-precision, real, or integer matrix. The return value is doubleprecision.
6.1.8.b: Example
z = 1 - 1i0
imag(z)
returns
-1
6.1.9: The Sign Function
Syntax sign(x)
6.1.9.a: Description
Returns the element-by-element: 26.n value 1 for each non-negative element and -1 for each negative element of x, where x is an integer, real, or
double-precision matrix.
6.1.9.b: Example
sign([-3, 4, 0])
returns
[ -1 , 1 , 1 ]
6.1.9.c: Mlmode
In Mlmode: 25 , the sign function accepts complex arguments and returns x ./ abs(x) in this case. In addition, it returns zero if the argument if the
argument is equal to zero. If in Mlmode you enter
sign( [ 0*i , 1*i , 2*i ] )
O-Matrix will respond
[ (0,0) , (0,1) , (0,1) ]
6.1.10: Largest Integer Less Than or Equal a Specified Value
Syntax floor( x)
See Also ceil: 6.1.11 , roundoff: 6.1.13 , int: 6.4.2 , mod: 6.1.14
6.1.10.a: Description
Returns the element-by-element: 26.n largest integer that is less than or equal the corresponding element of x where x is an integer, real, or doubleprecision matrix.
6.1.10.b: Example
y = [ -1.4, -.6, 1.4, 2.]
floor(y)
returns
[-2 , -1 , 1 , 2]
6.1.10.c: Reference
Note that the elements of the return value are integers but the return value has the same type as x.
6.1.10.d: Mlmode
In Mlmode: 25 , x can also be a logical, character or complex matrix. In the complex case, the floor function applies to the real and imaginary parts
separately.
6.1.11: Smallest Integer Greater Than or Equal a Specified Value
Syntax ceil(x)
See Also floor: 6.1.10 , roundoff: 6.1.13 , int: 6.4.2 , mod: 6.1.14
6.1.11.a: Description
Returns the element-by-element: 26.n largest integer that is less than or equal the corresponding element of x where x is an integer, real, or doubleprecision matrix.
6.1.11.b: Example
y = [ -1.4, -.6, 1.4, 2.]
ceil(y)
returns
[-1 , 0 , 2 , 2]
6.1.11.c: Reference
Note that the elements of the return value are integers but the return value has the same type as x.
6.1.11.d: Mlmode
In Mlmode: 25 , x can also be a logical, character or complex matrix. In the complex case, the floor function applies to the real and imaginary parts
separately.
6.1.12: Rounding of to the Nearest Integer Value
Syntax round( x)
See Also roundoff: 6.1.13 , ceil: 6.1.11 , floor: 6.1.10 , int: 6.4.2 , mod: 6.1.14
6.1.12.a: Description
Returns the element-by-element: 26.n closest integer value to x where x is an integer, real, double-precision, or complex matrix. In the complex case,
the round function applies to the real and imaginary parts separately.
6.1.12.b: Example
y = [ -1.4, -.6, 1.4, 2.]
round(y)
returns
[-1 , -1 , 1 , 2]
6.1.12.c: Reference
Note that round returns a matrix the elements of which are equal to integers, but the return value has the same type as x. The function roundoff: 6.1.13
returns a matrix that has the integer type.
6.1.12.d: Mlmode
In Mlmode: 25 , x can also be a logical, or character matrix.
6.1.13: Rounding Numbers To The Nearest Integer
Syntax roundoff(x)
See Also round: 6.1.12 , int: 6.4.2 , floor: 6.1.10 , mod: 6.1.14
6.1.13.a: Description
Returns the element-by-element: 26.n integer matrix that is closest to x, where x is an integer, real, double-precision matrix.
6.1.13.b: Example
y = [-1.4, -.6, .6, 1.4, 1.6]
print roundoff(y)
returns
[-1 , -1 , 1 , 1 , 2]
6.1.13.c: Reference
The return value of roundoff is an integer matrix while the return value of round(x): 6.1.12 has the same type as x
6.1.14: Modulo Function
Syntax z = mod(x, y)
See Also rem: 6.1.15 , colunmod: 6.1.16 , floor: 6.1.10 , roundoff: 6.1.13 , int: 6.4.2
6.1.14.a: Description
Returns the element-by-element: 26.n modulo function where z has the same sign as y, |z| < |y|, and x - z is divisible by y. The matrices x and y
are integer, real, or double-precision matrix.
6.1.14.b: Example
x = [1., 1.5, 2., 2.75]
y = 2.5
mod(x, y)
returns
[1. , 1.5 , 2 , 0.25]
6.1.15: Remainder Function
Syntax z = rem(x, y)
See Also mod: 6.1.14 , floor: 6.1.10 , roundoff: 6.1.13 , int: 6.4.2
6.1.15.a: Description
Returns the element-by-element: 26.n value z where z has the same sign as x, |z| < |y|, and x - z is divisible by y. The matrices x and y are integer,
real, or double-precision matrix.
6.1.15.b: Example
x = [1., 1.5, 2., 2.75]
y = 2.5
rem(-x, y)
returns
[-1. , -1.5 , -2 , -0.25]
6.1.16: Undo The Modulo Function
Syntax r = colunmod(x, y)
r = colunmod(x, y, b)
6.1.16.a: Description
Returns a matrix r with the same dimensions as x that satisfies the following properties:
( r
- x
i,j
) / y
i,j
is equal to an integer and
| r
-
r
i+1,j
|
< y
i,j
furthermore
if x
-
x
i+1,j
> +b
then r
i+1,j
-
r
i,j
< 0
< -b
then r
-
r
> 0
i,j
if x
-
x
i+1,j
i,j
i+1,j
i,j
The arguments y and b are scalars and both greater than zero. The arguments x, y and b are integer, real, or double-precision. The return value r has the
type that results from coercion: 4.4 between the types of the arguments x and y.
If the argument b is not present, the value y / 2 is used in its place. If y is an integer, and it is not even, the corresponding type of b is real. Otherwise
the corresponding type for b is the same as the type of y.
6.1.16.b: Example
If you enter
x = 2 * seq(5)
y = 2 * PI
x = mod(x, y)
x = colunmod(x, y)
print x
O-Matrix will respond
{
2
4
6
8
10
}
6.1.17: Unwrap Angles To Absolute Angles Above Two Pie
Syntax r = unwrap(a)
r = unwrap(a, b)
r = unwrap(a, b, d)
6.1.17.a: Description
Returns a double-precision matrix r with the same dimensions as x that unwraps to equivalent angles with absolute value greater than 2 pi.
If the argument b is not present or if it is an empty matrix, the value pi is used in its place. If the argument b is present, it must be an integer, real or
double-precision scalar greater than zero. The return value r satisfies the following properties:
( R
- X
k
) / (2 pi)
k
is equal to an integer and
| R
-
R
k+1
|
< 2 pi
k
furthermore
if X
-
X
k+1
if X
k+1
> +b
then R
k
X
< -b
k
-
R
k+1
then R
< 0
k
k+1
where X and R depend on x and d as follows
d
x
X
R
not
a row
equal equal r not not a row
present vector
x
present
vector
R
> 0
k
any column any column of r any
of x
equal 1
value
any column any column of r any
of x
equal 2
value
any row any row
of x
of r
6.1.17.b: Example
If you enter
x = 2 * seq(5)
y = 2 * PI
x = mod(x, y)
print x
O-Matrix will respond
{
2
4
6
1.71681
3.71681
}
If you continue by entering
x = unwrap(x)
print x
O-Matrix will respond
{
2
4
6
8
10
}
6.1.18: The Factorial Function
Syntax factorl( n)
6.1.18.a: Description
Computes the element-by-element: 26.n factorial of n, where n is an integer matrix.
6.1.18.b: Example
If you enter
n = [1, 2, 3, 4]
factorl(n)
O-Matrix will respond
[ 1 , 2 , 6 , 24 ]
6.1.18.c: Reference
The result is returned as an integer and hence should not be larger than INT_MAX: 24.1 . If you need to compute the factorial for a large value of n you
should use gamma(n + 1).
6.1.19: Computing Prime Numbers
Syntax primes(N)
6.1.19.a: Description
Returns an integer row vector containing the primes less than or equal to N, where N is an integer scalar.
6.1.19.b: Example
primes(20)
returns
[ 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19]
6.2: Transcendental Functions
6.2.a: Contents
acos: 6.2.1 Inverse Cosine Function
asin: 6.2.2 Inverse Sine Function
atan: 6.2.3 Inverse Tangent Function
cos: 6.2.4
Cosine Function
cosh: 6.2.5 Hyperbolic Cosine Function
exp: 6.2.6
Exponential Function
log: 6.2.7
Natural Logarithm Function
log10: 6.2.8 Base Ten Logarithm Function
sin: 6.2.9
Sine Function
sinh: 6.2.10 Hyperbolic Sine Function
tan: 6.2.11 Tangent Function
tanh: 6.2.12 Hyperbolic Tangent Function
log2: 6.2.13 Base Two Logarithm Function
pow2: 6.2.14 Base Two Exponentiation Function
atan2: 6.2.15 Inverse Tangent Function With Two Arguments
angle: 6.2.16 Angle Corresponding to a Complex Value
asinh: 6.2.17 Inverse Hyperbolic Sine Function
acosh: 6.2.18 Inverse Hyperbolic Cosine Function
acoth: 6.2.19 Inverse Hyperbolic Cotangent Function
coth: 6.2.20 Hyperbolic Cotangent Function
atanh: 6.2.21 Inverse Hyperbolic Tangent Function
hypot: 6.2.22 Square Root of Sum of Squares
6.2.1: Inverse Cosine Function
Syntax acos(value)
See Also cos: 6.2.4 , asin: 6.2.2 , atan: 6.2.3 , acosh: 6.2.18
6.2.1.a: Description
Returns the element-by-element: 26.n inverse cosine of value in radians, where value is a real or double-precision matrix between -1 and 1, inclusive.
The elements of the result are between 0 and pi.
6.2.1.b: Example
acos([-1., 0, 1.])
returns
[ 3.14159 , 1.5708 , 0 ]
6.2.2: Inverse Sine Function
Syntax asin(value)
See Also sin: 6.2.9 , acos: 6.2.1 , atan: 6.2.3 , asinh: 6.2.17
6.2.2.a: Description
Returns the element-by-element: 26.n inverse sine of value in radians, where the elements of value are real or double-precision numbers between -1
and 1, inclusive. The elements of the result are between -pi/2 and pi/2.
6.2.2.b: Example
asin([-1., 0, 1.])
returns
[ -1.5708 , 0 ,
1.5708 ]
6.2.3: Inverse Tangent Function
Syntax atan(value)
See Also tan: 6.2.11 , acos: 6.2.1 , asin: 6.2.2 , atan2: 6.2.15
6.2.3.a: Description
Returns the element-by-element: 26.n inverse tangent of value in radians, where value is a real or double-precision matrix. The elements of the result
are between -pi/2 and pi/2.
6.2.3.b: Example
atan([-1., 0, 1.])
returns
[ -.785398 , 0 , .785398 ]
6.2.4: Cosine Function
Syntax cos(angle)
See Also acos: 6.2.1 , sin: 6.2.9 , tan: 6.2.11 , cosh: 6.2.5
6.2.4.a: Description
Returns the element-by-element: 26.n cosine of angle, where angle is a real, double-precision matrix, or complex matrix expressed in radians.
6.2.4.b: Example
cos([-PI / 3, 0, PI / 3])
returns
[ 0.5 , 1 , 0.5 ]
6.2.5: Hyperbolic Cosine Function
Syntax cosh(value)
See Also acosh: 6.2.18 , cos: 6.2.4 , sinh: 6.2.10 , tanh: 6.2.12
6.2.5.a: Description
Returns the element-by-element: 26.n hyperbolic cosine of value, where value is a real or double-precision matrix.
6.2.5.b: Example
cosh([-1., 0, 1.])
returns
[ 1.54308 , 1, 1.54308 ]
6.2.6: Exponential Function
Syntax exp(exponent)
6.2.6.a: Description
Returns the element-by-element: 26.n value of
exponent
e
where e is Euler's number and exponent, is a real, double-precision matrix, or complex matrix.
6.2.6.b: Example
exp(1.0)
returns
2.71828
6.2.7: Natural Logarithm Function
Syntax log(value)
6.2.7.a: Description
Returns the element-by-element: 26.n natural logarithm of value, where value is a real, double-precision matrix, or complex matrix. If value is a real or
double-precision matrix, its elements cannot be negative.
6.2.7.b: Example
log(1.0)
returns
0
If value is a complex number, the imaginary part of the result is between -pi and pi.
log([-1r0 + 1i0, -1r0 - 1i0])
returns
[ (0.346574,2.35619) , (0.346574,-2.35619) ]
6.2.8: Base Ten Logarithm Function
Syntax log10( value)
6.2.8.a: Description
Returns the element-by-element: 26.n base-ten logarithm of value, where the elements of value are nonnegative real or double-precision numbers.
6.2.8.b: Example
log10(100.)
returns
2
6.2.9: Sine Function
Syntax sin(angle)
See Also asin: 6.2.2 , cos: 6.2.4 , tan: 6.2.11 , sinh: 6.2.10
6.2.9.a: Description
Returns the element-by-element: 26.n sine of angle, where angle is a real, double-precision, or complex matrix expressed in radians.
6.2.9.b: Example
sin([0, PI / 4, PI / 2])
returns
[ 0 , 0.707107 , 1 ]
6.2.10: Hyperbolic Sine Function
Syntax sinh(value)
See Also asinh: 6.2.17 , sin: 6.2.9 , cosh: 6.2.5 , tanh: 6.2.12
6.2.10.a: Description
Returns the element-by-element: 26.n hyperbolic sine of value, where value is a real or double-precision matrix.
6.2.10.b: Example
sinh([-1., 0, 1.])
returns
[ -1.1752 , 0, 1.1752 ]
6.2.11: Tangent Function
Syntax tan(angle)
See Also atan: 6.2.3 , atan2: 6.2.15 , tanh: 6.2.12 , sin: 6.2.9 , cos: 6.2.4
6.2.11.a: Description
Returns the element-by-element: 26.n tangent of angle, where angle is a real or double-precision matrix expressed in radians. The value of tan is
unreliable where the cosine of an element of angle is zero.
6.2.11.b: Example
tan([-PI / 4, 0, PI / 4])
returns
[ -1 , 0 , 1 ]
6.2.12: Hyperbolic Tangent Function
Syntax tanh(value)
6.2.12.a: Description
Returns the element-by-element: 26.n hyperbolic tangent of value, where value is a real or double-precision matrix.
6.2.12.b: Example
tanh([-1., 0., 1.])
returns
[ -0.761594 , 0 , 0.761594 ]
6.2.13: Base Two Logarithm Function
Syntax f = log2(x)
[f,e] = log2(x)
6.2.13.a: Description
Computes the element-by-element: 26.n base-two logarithm of x where x is a real, double-precision or complex matrix.
6.2.13.b: One Return Value
In this case f satisfied the equation
f
x = 2
If any of the elements of x are negative, f is a complex matrix. Otherwise f has the same type as x.
6.2.13.c: Two Return Values
In this case the real part of all the elements of x must be positive and the return values f and e satisfy the equation
e
Re[x] = f * 2
where Re[x] denotes the
real part: 26.ad of x, f is a fraction in the interval [.5, 1.) and e is equal to an integer. If f is a complex matrix, f and e are
double-precision matrices. Otherwise f and e have the same type as x.
6.2.13.d: Example
log2(4.)
returns
2
If you enter
[f, e] = log2( [1, 2, 3, 4] )
{f , e}
{
[ .5 , .5, .5 ]
[ 1 , 2 , 2 , 3 ]
}
6.2.14: Base Two Exponentiation Function
Syntax x = pow2(e)
x = pow2(f, e)
6.2.14.a: Description
Computes the element-by-element: 26.n base-two exponentiation of e where e is a real, double-precision or complex matrix.
6.2.14.b: One Argument
If f is not present, x satisfied the equation
e
x = 2
6.2.14.c: Two Arguments
If f is present, x satisfied the equation
int(e)
x = Re[f] * 2
where Re[f]: 26.ad is the real part of f and int(e): 6.4.2 is the integer part of e. If both arguments are real, x is real, otherwise x is double-precision.
6.2.14.d: Example
pow2(2.)
returns
4
If you enter
pow2( [1., 2.], [0., 1.] )
{
[ 1 , 4 ]
}
6.2.15: Inverse Tangent Function With Two Arguments
Syntax atan2( y, x)
6.2.15.a: Description
Returns the element-by-element: 26.n inverse tangent of y / x where y and x are real or double-precision matrices. If the types of x and y do not
agree, coercion: 4.4 is done and then the result is computed. The elements of the result are between -pi and +pi.
6.2.15.b: Example
atan2(1., 1.)
returns
0.785398
Even though x is in the denominator in the definition above, zero is a valid value for an element of x.
atan2([0, 1., 0, -1.], [-1., 0, 1., 0])
returns
[ 3.14159 , 1.5708 , 0 , -1.5708 ]
6.2.16: Angle Corresponding to a Complex Value
Syntax angle( z)
6.2.16.a: Description
Returns a double precision matrix containing the element-by-element: 26.n angle between the direction vector
( Re(z), Im(z) )
where and the real axis where Re(z) and Im(z) above are the real and imaginary parts of the complex elements: 26.i of z. The elements of the result
are between -pi and +pi.
6.2.16.b: Example
angle(1 + 1i0)
returns
0.785398
If you enter
angle( [-1r0, 1i0, 1r0, -1i0] )
returns
[ 3.14159 , 1.5708 , 0 , -1.5708 ]
6.2.17: Inverse Hyperbolic Sine Function
Syntax asinh( y)
See Also sinh: 6.2.10 , acosh: 6.2.18 , atanh: 6.2.21 , acoth: 6.2.19
6.2.17.a: Description
Returns the element-by-element: 26.n inverse sinh of y, where y is a real or double-precision matrix.
6.2.17.b: Example
x = 1.5
asinh(x)
returns
1.19476
6.2.18: Inverse Hyperbolic Cosine Function
Syntax acosh( y)
See Also cosh: 6.2.5 , asinh: 6.2.17 , atanh: 6.2.21 , acoth: 6.2.19
6.2.18.a: Description
Returns the element-by-element: 26.n inverse cosh of y, where y is a real or double-precision matrix such that y(i, j) > 1 for all (i, j).
Note that cosh(x) = cosh(-x), so there are two choices for its inverse. The return value of acosh is the positive inverse.
6.2.18.b: Example
acosh(pi)
returns
1.81153
6.2.19: Inverse Hyperbolic Cotangent Function
Syntax acoth( y)
See Also coth: 6.2.20 , sinh: 6.2.10 , acosh: 6.2.18 , atanh: 6.2.21
6.2.19.a: Description
Returns the element-by-element: 26.n inverse acoth of y, where y is a real or double-precision matrix.
6.2.19.b: Example
acoth(2*pi)
returns
0.16052
6.2.20: Hyperbolic Cotangent Function
Syntax acoth( y)
See Also acoth: 6.2.19 , sinh: 6.2.10 , acosh: 6.2.18 , atanh: 6.2.21
6.2.20.a: Description
Returns the element-by-element: 26.n coth of y, where y is a real or double-precision matrix.
6.2.20.b: Example
coth(pi/2.)
returns
1.0903
6.2.21: Inverse Hyperbolic Tangent Function
Syntax y = atanh( x)
See Also tanh: 6.2.12 , asinh: 6.2.17 , acosh: 6.2.18 , acoth: 6.2.19
6.2.21.a: Description
Returns the element-by-element: 26.n inverse hyperbolic tangent of x, where x is a real or double-precision matrix. For each (i,j) that is a valid index
for x, the corresponding element of x satisfies
-1 <
x
< 1
i,j
6.2.21.b: Example
If you enter
atanh(tanh([-2., 0., 1.])
[ -2 , 0 , 1 ]
6.2.22: Square Root of Sum of Squares
Syntax x = hypot(a, b)
6.2.22.a: Description
Computes the element-by-element: 26.n sqrt(a^2 + b^2) where a and b are integer, real, or double-precision matrices with equal dimensions.
6.2.22.b: Example
hypot({1., 2}, {3, 4})
returns
{
3.16228
4.47214
}
6.3: Special Matrices
6.3.a: Contents
identity: 6.3.1 Obtaining A Copy Of The Identity Matrix
zeros: 6.3.2
Creating A Matrix Of Zeros
ones: 6.3.3
Creating A Matrix Of Ones
fill: 6.3.4
Filling A Matrix With Copies of Another Matrix
fillcols: 6.3.5 Filling A Matrix With A Column Vector
fillrows: 6.3.6 Filling A Matrix With A Row Vector
seq: 6.3.7
Generating A Sequence Of Integers
toeplitz: 6.3.8 Constructing Toeplitz Matrices
vander: 6.3.9 Vandermonde Matrix
hankel: 6.3.10 Hankel Matrix
hilb: 6.3.11
Hilbert Matrix
invhilb: 6.3.12 Exact Inverse of a Hilbert Matrix
diag: 6.3.13
The Diagonal Function
tril: 6.3.14
Lower Triangular Part of a Matrix
triu: 6.3.15
Upper Triangular Part of a Matrix
novalue: 6.3.16 The Novalue Type In O-Matrix
6.3.1: Obtaining A Copy Of The Identity Matrix
Syntax identity(dimension)
See Also ones: 6.3.3 , zeros: 6.3.2 , fill: 6.3.4 , diag: 6.3.13
6.3.1.a: Description
Returns an integer copy of the identity matrix with the specified dimension, where dimension is a positive integer scalar.
6.3.1.b: Example
identity(3)
returns
{
[ 1 , 0 , 0 ]
[ 0 , 1 , 0 ]
[ 0 , 0 , 1 ]
}
6.3.2: Creating A Matrix Of Zeros
Syntax zeros( m)
zeros( m, n)
6.3.2.a: Description
Returns an integer matrix of zeros with the specified dimension, where m is an integer scalar specifying the number of rows in the return value, and n,
if present, is an integer scalar specifying the number of columns in the return value. If n is not present, a column vector with m rows is returned.
6.3.2.b: Example
zeros(2, 3)
returns
{
[ 0 , 0 , 0 ]
[ 0 , 0 , 0 ]
}
6.3.3: Creating A Matrix Of Ones
Syntax ones(m)
ones(m, n)
6.3.3.a: Description
Returns an integer matrix of ones with the specified dimension, where m is an integer scalar specifying the number of rows in the return value, and n,
if present, is an integer scalar specifying the number of columns in the return value. If n is not present, a column vector with m rows is returned.
6.3.3.b: Example
ones(2, 3)
returns
{
[ 1 , 1 , 1 ]
[ 1 , 1 , 1 ]
}
6.3.4: Filling A Matrix With Copies of Another Matrix
Syntax z = fill(x, m, n)
z = fill(x,[m , n])
See Also repmat: 6.3.4.d , ones: 6.3.3 , zeros: 6.3.2 , fillrows: 6.3.6 , fillcols: 6.3.5
6.3.4.a: Description
Returns a matrix z with m x n subblocks each of which is equal to x. The return matrix has the same type as x, has m times as many rows as x and n
times as many columns as x. The (i,j)-th element of the return value is given by
z
i,j
= x
mod(i-1,m)+1 , mod(j-1,n)+1
The arguments m and n can be integer, real, or double-precision. If they are not integer, only their integer: 6.4.2 .
6.3.4.b: Example
For a scalar x example, enter
fill(1.5, 2, 3)
which returns
{
[ 1.5 , 1.5 , 1.5 ]
[ 1.5 , 1.5 , 1.5 ]
}
For a matrix x example, enter
fill([2.5 , 3.5], [2, 2])
which returns
{
[ 2.5 , 3.5 , 2.5 , 3.5 ]
[ 2.5 , 3.5 , 2.5 , 3.5 ]
}
6.3.4.c: Empty Matrices
You can use the fill command to create empty matrices. If you enter
x = fill(1, 0, 3)
print type(x), rowdim(x), coldim(x)
O-Matrix will respond
int 0 3
6.3.4.d: Mlmode
In Mlmode: 25 , this function is called repmat instead of fill. If in Mlmode you enter,
repmat([2.5 , 3.5],
[2 , 2])
which returns
{
[ 2.5 , 3.5 , 2.5 , 3.5 ]
[ 2.5 , 3.5 , 2.5 , 3.5 ]
}
6.3.5: Filling A Matrix With A Column Vector
Syntax fillcols(v, n)
6.3.5.a: Description
Returns the matrix that has n columns, each of which contains the vector v, where n is an integer scalar and v is a column vector. The return value has
the same type and row dimension as v, and its column dimension is equal to n.
6.3.5.b: Example
fillcols({1, 2, 3}, 3)
returns
{
[ 1 , 1 , 1 ]
[ 2 , 2 , 2 ]
[ 3 , 3 , 3 ]
}
6.3.6: Filling A Matrix With A Row Vector
Syntax fillrows(v, n)
6.3.6.a: Description
Returns the matrix that has n rows, each of which contains the vector v, where n is an integer scalar and v is a row vector. The return value has the
same type and column dimension as v, and its row dimension is equal to n.
6.3.6.b: Example
fillrows([1, 2, 3], 3)
returns
{
[ 1 , 2 , 3 ]
[ 1 , 2 , 3 ]
[ 1 , 2 , 3 ]
}
6.3.7: Generating A Sequence Of Integers
Syntax seq(length)
6.3.7.a: Description
Returns a column vector with the specified length and first element equal to 1, second element equal to 2, and so on, where length is a positive integer
scalar.
6.3.7.b: Example
seq(3)
returns
{
1
2
3
}
6.3.8: Constructing Toeplitz Matrices
Syntax t = toeplitz(c)
t = toeplitz(c, r)
6.3.8.a: Description
Constructs a Toeplitz matrix with first its first column equal to the vector c and its first row equal to the vector r. If the argument r is not present, its
default value is the complex conjugate: 6.1.7 of c. If the first element of r is not equal to the first element of c, the first element of c is used for the
diagonal of the matrix.
If the vectors c and r have equal length n, the return matrix is
/
|
|
|
|
t = |
|
|
|
|
\
c
r
1
r
2
c
c
2
c
...
2
.
.
.
c
n
c
n-1
r
\
|
|
r
|
n-1 |
.
|
.
|
.
|
|
c
|
1
/
n
r
1
.
.
.
.
.
.
...
3
...
n-2
In general, if n is the length of c and m is the length of r, the return value t is an n x m matrix with
/ c
/
t
if i - j > 0
i - j + 1
= <
i,j
\
r
\
if j - i > 0
j - i + 1
The type of t is the type that results from coercion: 4.4 between the type of c and r.
6.3.8.b: Example
If you enter
c = [ 1 , 2 , 3 ]
toeplitz(c)
{
[ 1 , 2 , 3 ]
[ 2 , 1 , 2 ]
[ 3 , 2 , 1 ]
}
6.3.9: Vandermonde Matrix
Syntax v = vander(c)
6.3.9.a: Description
Returns the Vandermonde matrix corresponding to the integer, real, double-precision or complex vector c. The return value v is a n x n matrix with
the same type as c where n is the length of c. The (i,j)-th element of v is given by
n-j
v
=
c
i,j
i
6.3.9.b: Example
If you enter
c = [ 1 , 2 , 3 ]
vander(c)
{
[ 1 , 1 , 1 ]
[ 4 , 2 , 1 ]
[ 9 , 3 , 1 ]
}
6.3.10: Hankel Matrix
Syntax h = hankel(c)
h = hankel(c, r)
6.3.10.a: Description
Returns the Hankel matrix with elements of its first column corresponding to the vector c and with elements of its last row corresponding to the vector
r.
If m is the length of the vector c and n is the length of the vector r, the return value h is the m x n matrix defined by
h(i, j)
/ c(i + j - 1)
if i + j - 1 < m
\ r(i + j - m)
otherwise
= <
Note that the first element of r is never used.
If the argument r is not present, the integer zero vector with the same length as c is used in its place.
6.3.10.b: Example
If you enter
c = 1 : 1 : 3
hankel(c)
{
[ 1 , 2 , 3 ]
[ 2 , 3 , 0 ]
[ 3 , 0 , 0 ]
}
If you continue by entering
r = 4 : -1 : 1
hankel(c, r)
{
[ 1 , 2 , 3 , 3 ]
[ 2 , 3 , 3 , 2 ]
[ 3 , 3 , 2 , 1 ]
}
6.3.11: Hilbert Matrix
Syntax h = hilb(n)
6.3.11.a: Description
Returns a double precision n x n Hilbert matrix where n is an integer, real, double-precision, or complex scalar and equal to a real integer. The return
value is defined by
1
h(i, j) = --------i + j - 1
6.3.11.b: Example
If you enter
hilb(3)
{
[ 1 , 0.5 , 0.333333 ]
[ 0.5 , 0.333333 , 0.25 ]
[ 0.333333 , 0.25 , 0.2 ]
}
6.3.12: Exact Inverse of a Hilbert Matrix
Syntax invhilb( n)
6.3.12.a: Description
Returns an n x n
inv(hilb(n)).
double-precision matrix containing the inverse of the n x n Hilbert matrix: 6.3.11 . This is slower but more accurate than
6.3.12.b: Example
If you enter
invhilb(2)
{
[ 4 , -6 ]
[ -6 , 12 ]
}
If you enter
invhilb(2) * hilb(2)
{
[ 1 , 0 ]
[ 0 , 1 ]
}
6.3.13: The Diagonal Function
Syntax diag(A)
diag(A, k)
See Also identity: 6.3.1 , triu: 6.3.15 , tril: 6.3.14 , seq: 6.3.7
6.3.13.a: Description
If A is a vector, diag returns a square matrix, of minimal dimension, that is zero except for its k-th diagonal which is equal to A. If A is a matrix, diag
returns the k-th diagonal of the matrix A. If the argument k is not present, the value zero is used in its place.
The argument k must be integer, real or double-precision. If k >= 0, the k-th diagonal of a matrix B is the column vector consisting of the sequence of
elements B(1, 1+k), B(2, 2+k), ... , where the sequence continues as long as both indices are within the matrix. If k <= 0, the k-th diagonal of a
matrix B is the column vector consisting of the sequence of elements B(1-k, 1), B(2-k, 2), ... , where the sequence continues as long as both indices
are within the matrix.
6.3.13.b: Example: Vector Argument
If you enter
A = {1, 2}
k = 1
diag(A, k)
O-Matrix will respond
{
[ 0 , 1 , 0 ]
[ 0 , 0 , 2 ]
[ 0 , 0 , 0 ]
}
6.3.13.c: Example: Matrix Argument
If you enter
A = {[1, 2, 3] , [4, 5, 6], [7, 8, 9]}
k = -1
diag(A, k)
O-Matrix will respond
{
4
8
}
6.3.14: Lower Triangular Part of a Matrix
Syntax tril(A)
tril(A, k)
6.3.14.a: Description
The syntax tril(A) returns the lower triangular part of A
The syntax tril(X,k) returns the elements on and below the k-th diagonal of A where k is an integer, real or double-precision scalar. The value k = 0
corresponds to the main diagonal, k > 0 corresponds to above the main diagonal, and k < 0 corresponds to below the main diagonal.
6.3.14.b: Example:
If you enter
A = {[1, 2], [3, 4]}
tril(A)
O-Matrix will respond
{
[ 1 , 0 ]
[ 3 , 4 ]
}
If you enter
A = {[1, 2 , 3], [4, 5, 6], [7, 8, 9]}
k = 1
tril(A, k)
O-Matrix will respond
{
[ 1 , 2 , 0 ]
[ 4 , 5 , 6 ]
[ 7 , 8 , 9 ]
}
6.3.15: Upper Triangular Part of a Matrix
Syntax triu(A)
triu(A, k)
6.3.15.a: Description
The syntax triu(A) returns the upper triangular part of A
The syntax triu(X,k) returns the elements on and above the k-th diagonal of A where k is an integer, real or double-precision scalar. The value k = 0
corresponds to the main diagonal, k > 0 corresponds to above the main diagonal, and k < 0 corresponds to below the main diagonal.
6.3.15.b: Example:
If you enter
A = {[1, 2], [3, 4]}
triu(A)
O-Matrix will respond
{
[ 1 , 2 ]
[ 0 , 4 ]
}
If you enter
A = {[1, 2 , 3], [4, 5, 6], [7, 8, 9]}
k = 1
triu(A, k)
O-Matrix will respond
{
[ 0 , 2 , 3 ]
[ 0 , 0 , 6 ]
[ 0 , 0 , 0 ]
}
6.3.16: The Novalue Type In O-Matrix
Syntax novalue
6.3.16.a: Description
The novalue function returns a matrix with type equal to "novalue". You can pass these matrices as arguments and you can check their type.
6.3.16.b: Example
This function can be used to define a variable before the value of the variable is known. (It is preferable to set such a variable to novalue rather than 0
so that an error will occur if the value is used.) If you enter
function f(x) begin
print type(x)
x = 5
end
f(y)
O-Matrix will attempt to find a file named Y.OMS and if it cannot it will respond with an error message saying that y is not defined. If you continue by
entering
y = novalue
f(y)
print y
O-Matrix will respond
novalue
5
6.4: Matrix Type Functions
6.4.a: Contents
type: 6.4.1
Determining The Type Of An Expression
int: 6.4.2
Conversion To Integer
real: 6.4.3
Conversion To Single-Precision
double: 6.4.4
Conversion To Double-Precision
complex: 6.4.5 Element-By-Element Conversion To Complex
char: 6.4.6
Element-By-Element Conversion To Character
logical: 6.4.7
Conversion To Logical
matchtype: 6.4.8 Matching The Types Of Two Matrices
6.4.1: Determining The Type Of An Expression
Syntax type(expression)
See Also logical: 6.4.7 , char: 6.4.6 , int: 6.4.2 , real: 6.4.3 , double: 6.4.4 , complex: 6.4.5
6.4.1.a: Description
Returns a character row vector containing the type of an expression.
6.4.1.b: Example
The following table contains some expressions and their corresponding types
Expression Type
true
"logical"
"a"
"char"
1
"int"
1e0
"real"
1d0
"double"
1i0
"complex"
novalue
"novalue"
function f "function"
Entering
type(1e0)
returns
real
Entering
clear
function f() begin
end
type(function f)
returns
function
6.4.2: Conversion To Integer
Syntax int(value)
See Also fix: 6.4.2.c , char: 6.4.6 , real: 6.4.3 , coercion: 4.4
6.4.2.a: Description
Returns the element-by-element: 26.n conversion of value to an integer.
6.4.2.b: Example
If value is real or double-precision, the int function will truncate value. For example, if you enter
int(1.9)
returns
1
Entering
int(-1.9)
returns
-1
If value is complex, int will return only the integer value of the real part. If you type
int(1.5r0 + 2.1i0)
O-Matrix will return
1
If value is a character matrix, int will return the ASCII value of each element of value.
int("abc")
returns
[ 97 , 98 , 99 ]
If value is a logical matrix, int will return 1 for each true element and 0 for each false element. If you enter
int(2 + 3 == 5)
O-Matrix will respond
1
6.4.2.c: Mlmode
In Mlmode: 25 this function is called fix instead of int. If in Mlmode you enter
fix(-1.9)
O-Matrix will respond
-1
6.4.3: Conversion To Single-Precision
Syntax real(value)
See Also mlmode_real: 6.4.4 , isreal: 6.6.10 , int: 6.4.2 , double: 6.4.4 , coercion: 4.4
6.4.3.a: Description
Returns the element-by-element: 26.n conversion of value to a single-precision number.
6.4.3.b: Example
real(1)
returns
1
If value is complex, real will return only the real part of value. (Note that double: 6.4.4 will return the same value but in the same precision as a
complex value.) If you enter
real(1.5r0 + 2.1i0)
O-Matrix will return
1.5
If value is a character matrix, real will return the ASCII value of each element of value.
real("xyz")
returns
[ 120 , 121 , 122 ]
If value is a logical matrix, real will return 1 for each true element and 0 for each false element. If you enter
real(false)
O-Matrix will respond
0
6.4.4: Conversion To Double-Precision
Syntax double(value)
See Also mlmode_real: 6.4.4.c , real: 6.4.3 , complex: 6.4.5 , coercion: 4.4
6.4.4.a: Description
Returns the element-by-element: 26.n conversion of value to a double-precision number.
6.4.4.b: Example
double(1)
returns
1
If value is complex, double will return only the real part of value. (Note that real: 6.4.3 will return the same value but in single-precision.) If you enter
double(1.5r0 + 2.1i0)
O-Matrix will return
1.5
If value is a character matrix, double will return the ASCII value of each element of value.
double("mno")
returns
[ 109 , 110 , 111 ]
If value is a logical matrix, double will return 1 for each true element and 0 for each false element. If you enter
double(true)
O-Matrix will respond
1
6.4.4.c: Mlmode
In Mlmode: 25 this function is called real instead of double. If in Mlmode you enter
x = real(1 + 1*i)
O-Matrix will set x to the double-precision representation of the value 1.
6.4.5: Element-By-Element Conversion To Complex
Syntax complex( value)
complex( real part, imaginary part)
6.4.5.a: Description
Returns the element-by-element: 26.n conversion of a single value or two values to a complex number.
complex(value)
If value is complex, the return value is equal to value, otherwise the real part of the return value is equal to value.
complex(real part,
imaginary part)
The return value has real part equal to real part and imaginary part equal to imaginary part, where real part and imaginary part are logical, character,
integer, real or double-precision matrices.
6.4.5.b: Example
6.4.5.b.a: One Argument
complex(1)
returns
(1,0)
If value is a character matrix, complex will return the ascii: 24.3 value of each element of value. If you enter
complex("mno")
O-Matrix will respond
[ (109,0) , (110,0) , (111,0) ]
If value is a logical matrix, complex will return 1 for each true element and 0 for each false element. If you enter
complex(true)
O-Matrix will respond
(1,0)
6.4.5.b.b: Two Arguments
complex(1, 2)
returns
(1,2)
If you enter
complex([1, 2, 3], [4, 5, 6])
O-Matrix will respond
[ (1,4) , (2,5) , (3,6) ]
You can combine scalars with matrices of any dimension
complex([1, 2, 3], 1.)
returns
[ (1,1) , (2,1) , (3,1) ]
6.4.6: Element-By-Element Conversion To Character
Syntax char(value)
6.4.6.a: Description
Returns the element-by-element: 26.n conversion of value to the corresponding ascii: 24.3 characters, where value is a logical, character, integer, real,
double-precision or complex matrix.
6.4.6.b: Example
The constant DOQUOTE is defined in autoexec: 24.1 to be equal to
char(34)
which returns
"
If value contains a fractional part, char truncates value before converting it to ASCII. If you enter
char(97.9)
O-Matrix will respond
a
6.4.7: Conversion To Logical
Syntax logical( value)
6.4.7.a: Description
Returns the element-by-element: 26.n conversion of value to a logical value.
6.4.7.b: Example
The logical function returns true, for each nonzero element of value and false for each zero element of value (these are printed as "T" and "F"
respectively). If you enter
logical([0, .3, 1])
O-Matrix will respond
[ F , T , T ]
If value is complex, both the real and imaginary parts must be zero for logical to return false. Entering
logical([0r0, 1i0, 0r0 + 1i0])
returns
[ F , T , T ]
6.4.8: Matching The Types Of Two Matrices
Syntax matchtype( value, match)
6.4.8.a: Description
Returns a copy of value that has the same type as match. The return value has the same dimensions as value. (When converting to an integer,
matchtype rounds to the nearest integer.)
6.4.8.b: Example
matchtype(3.14, 1)
returns
3
because 1 is an integer.
6.5: System Functions
6.5.a: Contents
time: 6.5.1
Elapsed Time Since Start of Session
clock: 6.5.2
Determining The Date and Time
tictoc: 6.5.3
Starting and Reading an Elapsed Timer
system: 6.5.4
Starting Another Process
cwd: 6.5.5
Getting And Setting The Current Working Directory
listdir: 6.5.6
Listing the Names of Files in a Directory
listdirs: 6.5.7
Listing A Directory And All Its Subdirectories
mvfile: 6.5.8
Renaming A File
rmfile: 6.5.9
Removing A File
rmdir: 6.5.10
Removing A Directory
rmdirs: 6.5.11
Removing A Directory And All Its Subdirectories
isdir: 6.5.12
Determining If There Is A Directory With A Specified Name
isfullpath: 6.5.13 Determines If Value Represents a Complete File Name
fullpath: 6.5.14 Creates a Full Path File Name
mkdir: 6.5.15
Creating A Directory
exists: 6.5.16
Checking For A File Or Directory
lenfile: 6.5.17
Determining The Length Of A File
cpfile: 6.5.18
Copying Files
tempfile: 6.5.19 Creating A Temporary File Name
sleep: 6.5.20
Slowing or Suspending Execution
version: 6.5.21 O-Matrix Version Specification
clc: 6.5.22
Clearing the Command Window
editorfont: 6.5.23 Setting the Font for Editors
beep: 6.5.24
Generating Sounds
getenv: 6.5.25
Getting an Environment Variable
6.5.1: Elapsed Time Since Start of Session
Syntax time
6.5.1.a: Description
Returns the number of seconds since the beginning of the current O-Matrix session as a double-precision scalars.
6.5.1.b: Example
If you enter,
t0 = time
for i = 1 to 10000 begin
end
print "elapsed seconds =", time - t0
O-Matrix will print the number of seconds required to execute a for loop ten thousand times.
6.5.1.c: Mlmode
In Mlmode: 25 , this function is called cputime instead of time. If in Mlmode you enter
t0 = cputime
for i = 1 : 10000
end
'elapsed seconds ='
cputime - t0
O-Matrix will print the number of seconds required to execute a for loop ten thousand times.
6.5.2: Determining The Date and Time
Syntax clock
6.5.2.a: Description
Returns the day of the week, month, day of the month, time, and year as a twenty-four-column character row vector.
The clock function output is as follows:
Column Data
Example
1-3
day of week "Fri"
5-7
month
"Oct"
9-10
day of month "21"
12-13 hour
"12"
15-16 minute
"39"
18-19 second
"17"
21-24 year
"1994"
6.5.2.b: Example
Entering
clock
at 12:39:17 P.M. on Friday, October 21, 1994, resulted in
Fri Oct 21 12:39:17 1994
6.5.3: Starting and Reading an Elapsed Timer
Syntax tic
toc
6.5.3.a: Description
The function tic initialized the elapsed timer to zero. The function toc returns the number of seconds since the previous call to tic as a doubleprecision scalar.
6.5.3.b: Example
The following example displays how long in seconds it takes to multiply two 300 by 300 matrices. The begin and end commands are used to makes
the elapsed time correspond to just execution and not compilation time. (Execution does not take place until the entire block: 5.2 is compiled.)
begin
X = rand(300, 300)
tic
X * X;
toc
end
6.5.4: Starting Another Process
Syntax system(program)
system(program, window style)
6.5.4.a: Description
Starts the specified program as a separate process, where program is a character row vector that contains the name of a program followed by the
command line arguments to the program.
If present, the character row vector window style controls how the program is initially displayed and has one of the following values:
value
meaning
"hide"
hidden from the user
"maximized" uses the full display
"normal"
normal display mode
"iconic"
display as an icon
If window style is not present, the default style "normal" is used.
6.5.4.b: Example
If you enter
style
= "normal"
system(program, style)
the Notepad program will be started and displayed in normal mode.
6.5.5: Getting And Setting The Current Working Directory
Syntax cwd
cwd(directory)
6.5.5.a: Description
If directory is not present, returns the current working directory as a character row vector. If directory is present, changes the current working directory
to the one specified, where directory is a character row vector. In this case, the return value of cwd is true if the directory change is successful and false
if the change fails.
6.5.5.b: Example
If your current working directory is C:\OMWIN, and you enter
cwd
O-Matrix will respond
C:\OMWIN
If you then enter
cwd("programs")
O-Matrix will respond
T
and will set your current working directory to C:\OMWIN\PROGRAMS. If you try to change to a directory that does not exist, such as C:\PMWINK, by
entering
cwd("c:\pmwink")
O-Matrix will respond
F
6.5.6: Listing the Names of Files in a Directory
Syntax listdir
listdir( directory)
listdir( directory, pattern)
See Also dir: 6.5.6.c , listdirs: 6.5.7 , exists: 6.5.16 , isdir: 6.5.12 , rmdir: 6.5.10 , findstr: 9.35 , find2: 9.31
6.5.6.a: Description
Returns a character matrix containing a listing of the specified directory, where directory is a character row vector. If directory is not present, returns a
listing of the current working directory. If the argument pattern is present, listdir returns only filenames that contain strings that match the
Regular Expressions: 26.ae specified by the character row vector pattern.
6.5.6.b: Example
If the directory c:\omwin\programs contains the files edit.oms and TEST.OMS , and you enter
listdir("c:\omwin\programs")
O-Matrix will respond
edit.oms
TEST.OMS
If you enter,
listdir([OM_INSTALL,"\function"], "^fn.*")
O-Matrix will list only the functions in the function directory that start with the characters "fn".
fn2cbp.oms
fn2clp.oms
fn2dbp.oms
fn2dlp.oms
fnbpole.oms
fnbut.oms
fncheb.oms
fncpole.oms
6.5.6.c: Mlmode
In Mlmode: 25 , this function is called dir instead of listdir. If the directory C:\omwin\programs contains the files edit.oms and TEST.OMS, and in
Mlmode you enter
dir("c:\omwin\programs")
O-Matrix will respond
edit.oms
TEST.OMS
6.5.7: Listing A Directory And All Its Subdirectories
Syntax listdirs(dir)
See Also listdir: 6.5.6 , lenfile: 6.5.17 , rmdir: 6.5.10 , mkdir: 6.5.15
6.5.7.a: Description
Returns a character matrix containing a listing of the directory specified by dir, including all of its files and subdirectories, where dir is a character row
vector. The first 10 columns of the return value contain the length in bytes for each file, but are blank for listings of directory names.
Directly below each directory, its files appear sorted alphabetically. The subdirectories then appear, sorted alphabetically.
6.5.7.b: Example
If O-Matrix is installed in C:\OMWIN, and you enter
listdirs("c:\omwin\dll")
69120
126464
61440
129536
10394
1421
9937
5728
2736
135
4655
5004
5012
3979
527
2161
50176
48640
c:\omwin\dll
c:\omwin\dll\FTP.DLL
c:\omwin\dll\MATFILE.DLL
c:\omwin\dll\SAMPLE.DLL
c:\omwin\dll\TECPLOT.DLL
c:\omwin\dll\SRC
c:\omwin\dll\SRC\BTEST.CPP
c:\omwin\dll\SRC\BWRITE.CPP
c:\omwin\dll\SRC\DLL.H
c:\omwin\dll\SRC\DLL.HPP
c:\omwin\dll\SRC\GET.BAT
c:\omwin\dll\SRC\MATRIX.H
c:\omwin\dll\SRC\MYCOLMAX.CPP
c:\omwin\dll\SRC\MYROWMAX.CPP
c:\omwin\dll\SRC\VC
c:\omwin\dll\SRC\VC\VC.DSP
c:\omwin\dll\SRC\VC\VC.DSW
c:\omwin\dll\SRC\VC\VC.PLG
c:\omwin\dll\SRC\VC\VC.ncb
c:\omwin\dll\SRC\VC\VC.opt
c:\omwin\dll\SRC\VC\Debug
c:\omwin\dll\SRC\VC\Release
6.5.8: Renaming A File
Syntax mvfile(old name, new name)
6.5.8.a: Description
Changes the name of the file specified by old name to new name, where old name and new name are character row vectors. If either of the files is
currently open for reading: 8.3 or writing: 8.10 it is closed before the operation is performed. If the name change is successful, the logical scalar true is
returned, otherwise the logical scalar false is returned.
6.5.8.b: Example
If the file TEMP.OMS exists in the current working directory ( cwd: 6.5.5 ), and you enter
mvfile("temp.oms", "junk.oms")
O-Matrix will respond
T
If you then enter
exists("junk.oms")
O-Matrix will respond
T
6.5.8.c: Reference
If there already is a file with the same name as specified by new name, the move will fail and mvfile will return false.
6.5.9: Removing A File
Syntax rmfile(file)
See Also delete: 6.5.9.c , exists: 6.5.16 , rmdir: 6.5.10 , listdir: 6.5.6 , isdir: 6.5.12
6.5.9.a: Description
Deletes the specified file, where file is a character row vector. If the file existed and was successfully deleted, the function returns the value true,
otherwise it returns false.
6.5.9.b: Example
If you enter
rmfile("file.tmp")
and file.tmp exists, O-Matrix will delete the file and respond
T
6.5.9.c: Mlmode
In Mlmode: 25 , this function is called delete instead of rmfile. If in Mlmode you enter
delete("file.tmp")
and file.tmp exists, O-Matrix will delete the file and respond
T
6.5.10: Removing A Directory
Syntax rmdir( name)
See Also rmdirs: 6.5.11 , mkdir: 6.5.15 , exists: 6.5.16 , isdir: 6.5.12
6.5.10.a: Description
Removes the empty directory specified by name, where name is a character row vector. If the directory is successfully removed, rmdir returns true;
otherwise it returns false ( rmdirs: 6.5.11 can be used to remove a directory that is not empty).
6.5.10.b: Example
If the directory C:\JUNK does not exist, and you enter
mkdir("c:\junk")
O-Matrix will create the directory and respond
T
you can remove the directory with the command
rmdir("c:\junk")
6.5.11: Removing A Directory And All Its Subdirectories
Syntax rmdirs(dir)
See Also rmdir: 6.5.10 , mkdir: 6.5.15 , isdir: 6.5.12 , exists: 6.5.16
6.5.11.a: Description
Removes the specified directory, including all its files and subdirectories, where dir is a character row vector.
6.5.11.b: Example
mkdir("\junk.0")
mkdir("\junk.0\junk.1")
rmdirs("\junk.0")
returns
T
T
Beginning directory: Junk.1
Removing directory: Junk.1
Removing directory: \junk.0
6.5.12: Determining If There Is A Directory With A Specified Name
Syntax isdir( name)
6.5.12.a: Description
Returns true, it there is a directory with the specified name and false otherwise, where name is a character row vector. Note that if name corresponds to
a file instead of a directory, the return value is false.
6.5.12.b: Example
if you enter
isdir("c:\omwin")
O-Matrix will respond
T
On the other hand, if you enter
isdir("c:\omwin\function\colmax.oms")
O-Matrix will respond
F
6.5.13: Determines If Value Represents a Complete File Name
Syntax isfullpath(file)
See Also fullpath: 6.5.14 , isdir: 6.5.12 , ischarvector: 6.6.13 , exists: 6.5.16 , rmfile: 6.5.9
6.5.13.a: Description
Returns true, if the argument file is a fully, path qualified file name.
6.5.13.b: Example
If you enter
isfullpath("mydata.dat")
O-Matrix will respond
F
6.5.14: Creates a Full Path File Name
Syntax fullpath(path)
6.5.14.a: Description
Returns the full file name, (including path), for the character vector argument path.
6.5.14.b: Example
If you enter
fullpath("autoexec.oms")
O-Matrix will respond
C:\omwin\autoexec.oms
(Provided that you have installed O-Matrix in the default location.)
6.5.15: Creating A Directory
Syntax mkdir( name)
6.5.15.a: Description
Creates a directory with the specified name, where name is a character row vector. If the directory is successfully created, mkdir returns true;
otherwise it returns false
6.5.15.b: Example
If the directory C:\JUNK does not exist, and you enter
mkdir("c:\junk")
O-Matrix will create the directory and respond
T
you can remove the directory with the command
rmdir("c:\junk")
6.5.16: Checking For A File Or Directory
Syntax exists(file)
See Also isdir: 6.5.12 , rmfile: 6.5.9 , mvfile: 6.5.8 , fullpath: 6.5.14
6.5.16.a: Description
Returns a "true" value if the specified file or directory exists and a "false" value otherwise, where file is a character row vector.
6.5.16.b: Example
If file includes a path, exists will return a true value only if the specified file or directory exists in that path. If your AUTOEXEC.BAT file is in the root
directory of C:, and you enter
exists("C:\AUTOEXEC.BAT")
O-Matrix will respond
T
If file does not include a path, the exists function will look for file in the current directory. The commands
if exists("TEMP.TMP") then rmfile("TEMP.TMP")
will delete a file named TEMP.TMP from the current directory, if it exists.
6.5.17: Determining The Length Of A File
Syntax lenfile( file)
6.5.17.a: Description
Returns an integer scalar equal to the number of bytes in the specified file, where file is a character row vector.
6.5.17.b: Example
If the file C:\OMWIN\AUTOEXEC.OMS is 3789 bytes long, and you enter
lenfile("C:\OMWIN\AUTOEXEC.OMS")
O-Matrix will respond
3789
6.5.18: Copying Files
Syntax cpfile(source, destination)
6.5.18.a: Description
Copies the file specified by source to the file specified by destination, where source and destination are character row vectors. If either of the files is
open for reading or writing it is closed before the copy is made. If the copy is successful, the logical scalar "true" is returned, otherwise the logical
scalar "false" is returned.
6.5.18.b: Example
If TEMP is a file in the current directory, you can copy it to the file JUNK by entering
cpfile("temp", "junk")
6.5.19: Creating A Temporary File Name
Syntax tempfile
6.5.19.a: Description
Returns a character row vector containing a name that can be used for a temporary file. If the system environment variable TMP is defined, tempfile
returns a file name within the directory that TMP specifies. Otherwise, if the environment variable TEMP is defined, tempfile returns a file name
within the directory that TEMP specifies. If neither TMP nor TEMP is defined, tempfile returns a local file name.
If you do not explicitly delete the file (for example using rmfile: 6.5.9 ), it is automatically deleted when it you exit the O-Matrix session.
6.5.19.b: Example
If the environment variable TMP is defined in your system to be C:\TEMP, and you enter
tempfile
O-Matrix will respond
C:\TEMP\TMP3.OMS
The exact number in the file name (3 above) may vary depending what temporary files are already in the C:\TEMP directory. (You can determine what
environment variables are defined in your system by selecting the system Control Panel | System | Environment dialog.)
6.5.20: Slowing or Suspending Execution
Syntax sleep
sleep( option)
6.5.20.a: Description
Slows or suspends O-Matrix execution. If option is an integer, real or double-precision scalar, it specifies the number of seconds to wait before
continuing execution. If option is the string: 26.al "off" (or "OFF"), subsequent calls to sleep are ignored. If option is the string "on" (or "ON"),
subsequent calls to sleep are not ignored. If option is not present, execution is suspended until the user selects a continue button in a special dialog
that is displayed.
6.5.20.b: Example
for i = 1 to 5 begin
print i
sleep(1)
end
Will print the numbers 1 though 5 at a rate of one number per second.
You can use the sleep function when creating animated graphics. The following example animates a sine wave though one cycle.
theta = 0. : .1 : 2 * pi
for i = 0 to 50 begin
alpha = 2 * pi * i / 50.
ginitview
gplot(theta, sin(alpha + theta))
gxaxis("offlin", 0., 2 * pi);
gyaxis("offlin", -1., 1.)
gupdate
sleep(.2)
end
6.5.20.c: Mlmode
In Mlmode: 25 this function is called pause instead of sleep. If in Mlmode you enter
for i = 1:5
i
pause(1)
end
O-Matrix will print the numbers 1 though 5 at a rate of one number per second.
6.5.20.d: Reference
The clear: 3.2 command resets the sleep function to the "on" state.
6.5.21: O-Matrix Version Specification
Syntax version
[v, d] = version
6.5.21.a: Description
Returns a character row vector v that describes the current version of O-Matrix. If the return value d is present, it is a character row vector containing
the date on which the current version was compiled.
6.5.21.b: Example
If you enter
version
O-Matrix will respond
O-Matrix 6.2:
6.5.22: Clearing the Command Window
Syntax clc
6.5.22.a: Description
Clears the Command output window
6.5.22.b: Example
If you enter
x = seq(100)
x * x'
the Command window will fill with numbers. If you continue by entering
clc
the Command will be cleared.
6.5.23: Setting the Font for Editors
Syntax editorfont(face,size)
6.5.23.a: Description
Sets the current default font for editor windows. The type face is set to face, where face is a character row vector. The font point size is set to size,
where size is a positive integer scalar.
The editorfont command only changes font settings for subsequently opened editors, not currently active edit windows. You may use the "Options |
Editor Font" menu command to change the font settings of a currently active edit window.
Font sizes are limited to a maximum of 64 points. In addition if you specify a point size that is not directly supported on your system the closest
available size will be used.
6.5.23.b: Example
If you enter the command
editorfont("Arial",32)
O-Matrix will set the default editor font to Arial with a 32 point size.
6.5.24: Generating Sounds
Syntax beep
beep(frequency, duration)
6.5.24.a: Description
Generates a tone on the speaker (provided that sound is enabled). If present, the integer scalars frequency and duration, specify the frequency of the
tone in hertz and the duration of the tone in milliseconds, respectively. The frequency must be between 37 and 32,767. If frequency and duration are
not specified, the frequency will be 1,000 Hz and the duration will be 1,000 ms (if your system supports variation in the frequency and duration of
sounds).
The return value will be true if the beep succeeds and false otherwise.
6.5.24.b: Example
If you enter
beep
a beep will sound and T will print in the command window. If you enter
for i = 1 to 20 begin
beep(100 * i, 50);
end
a sliding tone will play on your computer. (Note that the semi-colon suppresses the printing of the return value from beep.)
6.5.25: Getting an Environment Variable
Syntax getenv(name)
6.5.25.a: Description
Returns a string: 26.al containing the name of the specified system environment variable. If no such variable exists, an empty matrix: 26.o is returned.
6.5.25.b: Example
If you enter
getenv("path")
O-Matrix will print the system search path (as apposed to the O-Matrix search path: 20.2 ).
6.6: Checking For Certain Conditions
6.6.a: Contents
all: 6.6.1
Determining if All Elements are True
mlmode_all: 6.6.2
Determining if All Elements are True (Mlmode)
any: 6.6.3
Determining if Any Elements are True
mlmode_any: 6.6.4 Determining if Any Elements are True (Mlmode)
nnz: 6.6.5
Number of Nonzero Elements
equal: 6.6.6
Checking For Matrix Equality
fullprec: 6.6.7
Determining Which Values Have Full Precision
isempty: 6.6.8
Determines if a Matrix is Empty
isequal: 6.6.9
Checking For Matrix Equality
isreal: 6.6.10
Determines If All Elements Have Zero Imaginary Part
isnumscalar: 6.6.11 Determines If Value is Numeric-Valued Scalar
ischarmatrix: 6.6.12 Determines If Value is Character Matrix
ischarvector: 6.6.13 Determines If Value is Character Vector
islogicalscalar: 6.6.14 Determines If Value is Logical Scalar
isnummatrix: 6.6.15 Determines If Value is Numeric Matrix
isnumvector: 6.6.16 Determines If Value is a Numeric Vector
isfinite: 6.6.17
Determines Which Elements Are Finite
isinf: 6.6.18
Determines Which Elements Are Infinite
isnan: 6.6.19
Determines Which Elements Are Not A Number
islight: 6.6.20
Determines If This is a Light Version of O-Matrix
isrte: 6.6.21
Determines If This is an O-Matrix Run-Time Engine Version
isdeveloper: 6.6.22 Determines If This is a O-Matrix Developer Version
6.6.1: Determining if All Elements are True
Syntax y = all(x)
y = all(x, d)
6.6.1.a: Description
Determines if all of the elements of x are true where x is a logical matrix.
If d is not present, y is a logical scalar that is true if all of the elements of x are true.
If the argument d is the integer one, y is a logical row vector with the same column dimension as x. The j-th element of the y is true, if all of the
elements in the j-th column of x are true.
If the argument d is the integer two, y is a logical column vector with the same row dimension as x. The i-th element of the y is true, if all of the
elements in the i-th roe of x are true.
6.6.1.b: Example
If you enter
x = [ 0 2 0; 4 5 0 ]
all(x)
O-Matrix will respond
F
If you continue
all(x, 1)
O-Matrix will respond
[ F , T , F ]
If you continue
all(x, 2)
O-Matrix will respond
{
F
F
}
6.6.2: Determining if All Elements are True (Mlmode)
Syntax y = all(x)
y = all(x, d)
6.6.2.a: Description
In Mlmode: 25 , determines if all of the elements of x are true where x is a logical, integer, real, double-precision or complex matrix and true
corresponds to no-zero for the numeric types.
6.6.2.b: Vector Case
If x is a vector, y is the logical scalar true if all of the elements of x are true. Otherwise it is the logical scalar false.
6.6.2.c: Empty Case
If x is an empty matrix: 26.o , y is the logical scalar false.
6.6.2.d: Matrix Case
If x is not a vector or empty matrix, y is a logical row vector with the same column dimension as x. The j-th element of y is true, if all of the elements
in the j-th column of x are true.
all(x,
d)
If the argument d is present, it must be an integer, real or double-precision scalar equal to one or two. If d is one, y is a logical row vector with the
same column dimension as x. The j-th element of y is true, if all of the elements in the j-th column of x are true. If d is two, y is a logical column vector
with the same row dimension as x. The i-th element of y is true, if all of the elements in the i-th row of x are true.
6.6.2.e: Example
If in Mlmode you enter
x = [ 0 2 0; 4 5 0 ]
all(x)
O-Matrix will respond
[ T , T , F ]
6.6.3: Determining if Any Elements are True
Syntax y = any(x)
y = any(x, d)
6.6.3.a: Description
Determines if any of the elements of x are true where x is a logical matrix.
If d is not present, y is a logical scalar that is true if any of the elements of x are true.
If the argument d is the integer one, y is a logical row vector with the same column dimension as x. The j-th element of the y is true, if any of the
elements in the j-th column of x are true.
If the argument d is the integer two, y is a logical column vector with the same row dimension as x. The i-th element of the y is true, if any of the
elements in the i-th roe of x are true.
6.6.3.b: Example
If you enter
x = [ 0 2 0; 4 5 0 ]
any(x)
O-Matrix will respond
T
If you continue
any(x, 1)
O-Matrix will respond
[ T , T , F ]
If you continue
any(x, 2)
O-Matrix will respond
{
T
T
}
6.6.4: Determining if Any Elements are True (Mlmode)
Syntax y = any(x)
y = any(x, d)
6.6.4.a: Description
In Mlmode: 25 , determines if any of the elements of x are true where x is a logical, integer, real, double-precision or complex matrix and true
corresponds to no-zero for the numeric types.
6.6.4.b: Vector Case
If x is a vector, y is the logical scalar true if any of the elements of x are true. Otherwise it is the logical scalar false.
6.6.4.c: Empty Case
If x is an empty matrix: 26.o , y is the logical scalar false.
6.6.4.d: Matrix Case
If x is not a vector or empty matrix, y is a logical row vector with the same column dimension as x. The j-th element of y is true, if any of the elements
in the j-th column of x are true.
any(x,
d)
If the argument d is present, it must be an integer, real or double-precision scalar equal to one or two. If d is one, y is a logical row vector with the
same column dimension as x. The j-th element of y is true, if any of the elements in the j-th column of x are true. If d is two, y is a logical column
vector with the same row dimension as x. The i-th element of y is true, if any of the elements in the i-th row of x are true.
6.6.4.e: Example
If in Mlmode you enter
x = [ 0 2 0; 4 5 0 ]
any(x)
O-Matrix will respond
[ T , T , F ]
6.6.5: Number of Nonzero Elements
Syntax nnz(x)
See Also any: 6.6.3 , all: 6.6.1 , find: 9.30 , equality: 4.8
6.6.5.a: Description
Returns the number of element of x that are not equal to zero where x is a logical, character, integer, real, double-precision or complex matrix.
6.6.5.b: Example
If you enter
x = identity(5)
nnz(x)
5
6.6.6: Checking For Matrix Equality
Syntax equal( x, y)
6.6.6.a: Description
Returns the logical scalar value "true" if the dimensions of x and y are equal and every element of x is equal to the corresponding element of y
(otherwise returns "false"), where x and y are each logical, character, integer, real, double-precision, or complex matrices. If either x or y is a character
matrix, they both must be character matrices. If x and y do not have the same type, one of the values will be coerced: 4.4 to match the type of the other
6.6.6.b: Example
x = {[1, 2], [3, 4]}
y = {[1, 2], [4, 4]}
print equal(x, x) , equal(x, y)
returns
T F
6.6.6.c: Reference
It is actually faster to call the isequal: 6.6.9 function directly and this function is only provided for compatibility with previous versions of O-Matrix.
6.6.7: Determining Which Values Have Full Precision
Syntax fullprec(x)
6.6.7.a: Description
Determines which elements of x are small enough that they are represented in full precision (can be normalized). The argument x is real, doubleprecision or complex. The return value of fullprec is a logical matrix with the same dimensions as x. The (i, j) element of the return value is true,
if x(i, j) is represented in full precision.
6.6.7.b: Example
If you enter
fullprec(2 * DOUBLE_MAX)
F
because DOUBLE_MAX is the largest double-precision value that can be represented in full precision.
6.6.8: Determines if a Matrix is Empty
Syntax
isempty(x)
6.6.8.a: Description
Returns true, if x is an empty matrix: 26.o and false otherwise.
6.6.8.b: Example
If you enter
x = [ ]
isempty(x)
O-Matrix will respond
T
6.6.9: Checking For Matrix Equality
Syntax isequal( x, y, z, ...)
6.6.9.a: Description
Returns true if the dimensions of all the arguments are equal and the corresponding elements are equal, otherwise isequal returns false. The
arguments can be logical, character, integer, real, double-precision, or complex matrices. If the arguments do not have the same type, values will be
coerced: 4.4 to match before the comparison is made.
6.6.9.b: Example
x = {[1, 2], [3, 4]}
y = {[1, 2], [4, 4]}
print isequal(x, x) , isequal(x, y)
returns
T F
6.6.9.c: Reference
This is a more general version of the equal: 6.6.6 function and it is faster because it is an intrinsic function.
6.6.10: Determines If All Elements Have Zero Imaginary Part
Syntax isreal(z)
See Also complex: 6.4.5 , real: 6.4.3 , type: 6.4.1 , imag: 6.1.8
6.6.10.a: Description
Returns true, if the imaginary parts of all the elements of z are zero and false otherwise.
6.6.10.b: Example
If you enter
z = [ 1r0, 1i0 ]
isreal(z)
O-Matrix will respond
F
6.6.11: Determines If Value is Numeric-Valued Scalar
Syntax isnumscalar( z)
See Also complex: 6.4.5 , real: 6.4.3 , type: 6.4.1 , imag: 6.1.8
6.6.11.a: Description
Returns true, if the argument z is an integer, real, double, or complex-valued scalar.
6.6.11.b: Example
If you enter
z = 1d0
isnumscalar(z)
O-Matrix will respond
T
6.6.12: Determines If Value is Character Matrix
Syntax ischarmatrix(z)
See Also isnumscalar: 6.6.11 , complex: 6.4.5 , real: 6.4.3 , type: 6.4.1 , imag: 6.1.8
6.6.12.a: Description
Returns true, if the argument z is a character matrix.
6.6.12.b: Example
If you enter
z = "Hello"
ischarmatrix(z)
O-Matrix will respond
T
6.6.13: Determines If Value is Character Vector
Syntax ischarvector(z)
See Also ischarmatrix: 6.6.12 , isnumscalar: 6.6.11 , complex: 6.4.5 , real: 6.4.3 , type: 6.4.1 , imag: 6.1.8
6.6.13.a: Description
Returns true, if the argument z is a character vector.
6.6.13.b: Example
If you enter
z = {"Hello","World"}
ischarvector(z)
O-Matrix will respond
F
6.6.14: Determines If Value is Logical Scalar
Syntax islogicalscalar( z)
See Also ischarmatrix: 6.6.12 , isnumscalar: 6.6.11 , complex: 6.4.5 , real: 6.4.3 , type: 6.4.1 , imag: 6.1.8
6.6.14.a: Description
Returns true, if the argument z is a logical scalar.
6.6.14.b: Example
If you enter
islogicalscalar(pi)
O-Matrix will respond
F
6.6.15: Determines If Value is Numeric Matrix
Syntax isnummatrix( z)
See Also isnumvector: 6.6.16 , isnumscalar: 6.6.11 , complex: 6.4.5 , real: 6.4.3 , type: 6.4.1 , imag: 6.1.8
6.6.15.a: Description
Returns true, if the argument z is a numeric-valued matrix.
6.6.15.b: Example
If you enter
isnummatrix([ 1 , pi ])
O-Matrix will respond
T
6.6.16: Determines If Value is a Numeric Vector
Syntax isnumvector( z)
See Also isnummatrix: 6.6.15 , isnumscalar: 6.6.11 , complex: 6.4.5 , real: 6.4.3 , type: 6.4.1 , imag: 6.1.8
6.6.16.a: Description
Returns true, if the argument z is a numeric-valued vector.
6.6.16.b: Example
If you enter
isnumvector({[ 1 , pi ], [2 , 4]})
O-Matrix will respond
F
6.6.17: Determines Which Elements Are Finite
Syntax isfinite(x)
6.6.17.a: Description
Returns logical matrix with the same dimension as x containing the element-by-element result true, if the corresponding element of x is finite: 26.q and
false otherwise.
6.6.17.b: Example
If you enter
x = [ 0 , INF, -INF, NAN, -NAN ]
isfinite(x)
O-Matrix will respond
[ T , F , F , F , F ]
6.6.18: Determines Which Elements Are Infinite
Syntax isinf( x)
6.6.18.a: Description
Returns logical matrix with the same dimension as x containing the element-by-element result true, if the corresponding element of x is plus or minus
infinity: 26.u and false otherwise.
6.6.18.b: Example
If you enter
x = [ 0 , INF, -INF, NAN, -NAN ]
isinf(x)
O-Matrix will respond
[ F , T , T , F , F ]
6.6.19: Determines Which Elements Are Not A Number
Syntax isnan( x)
6.6.19.a: Description
Returns logical matrix with the same dimension as x containing the element-by-element result true, if the corresponding element of x is plus or minus
NAN: 26.u and false otherwise.
6.6.19.b: Example
If you enter
x = [ 0 , INF, -INF, NAN, -NAN ]
isnan(x)
O-Matrix will respond
[ F , F , F , T , T ]
6.6.19.c: Reference
If x is a logical, character or integer matrix, all of the elements of the return matrix are false.
6.6.20: Determines If This is a Light Version of O-Matrix
Syntax islight
6.6.20.a: Description
Returns true, if the this is a light version of O-Matrix, otherwise returns false.
6.6.20.b: Example
If you enter
islight
O-Matrix will respond
T
for the light version and
F
for the full version.
6.6.20.c: Mlmode
In Mlmode: 25 , this function is called isstudent instead of islight. If in Mlmode you enter
isstudent
O-Matrix will respond
T
for the light version and
F
for the full version.
6.6.21: Determines If This is an O-Matrix Run-Time Engine Version
Syntax isrte
See Also isdeveloper: 6.6.22 , islight: 6.6.20 , omlic: 24.12 , omrte: 23
6.6.21.a: Description
Returns true, if this O-Matrix installation is an RTE, or virtual machine version of O-Matrix.
6.6.21.b: Example
If you enter
isrte
O-Matrix will respond
T
for a program running in the O-Matrix run time engine.
F
for all other versions.
6.6.22: Determines If This is a O-Matrix Developer Version
Syntax isdeveloper
See Also omatrixlight: 24.15 , omlic: 24.12 , omrte: 23 isstudent: 6.6.20.c
6.6.22.a: Description
Returns true, if the this O-Matrix installation is licensed for use with the O-Matrix Development Kit (http://www.omatrix.com/omrte.html) .
6.6.22.b: Example
If you enter
isdeveloper
O-Matrix will respond
T
for the O-Matrix Developer Version
F
for all other versions.
6.7: The Binary Logical Exclusive Or Operation
Syntax xor(x, y)
6.7.a: Description
Element-by-element: 26.n exclusive or of the matrices x and y. The arguments x and y can be logical, integer, real, double-precision or complex
matrices. The return value is a logical matrix with its corresponding elements true if one but not both of the corresponding elements of x and y are true
or nonzero.
6.7.b: Example
If you enter
x = [ 2 , 0 , 1 , 0 ]
y = [ true, true, false, false]
xor(x, y)
O-Matrix will respond
[ F , T , T , F ]
6.8: Smallest Power of Two Greater or Equal a Specified Value
Syntax e = nextpow2(x)
6.8.a: Description
If x is a scalar, returns the smallest integer e such that
e
2
> | x |
If x is a vector, returns
nextpow2(length(x))
where length is the length of the vector x.
6.8.b: Example
If you enter
nextpow2(10)
4
If you enter
nextpow2(.2)
-2
6.9: Evenly Spaced Grid With a Specified Number of Points
Syntax linspace(lower, upper)
linspace(lower, upper, npoint)
6.9.a: Description
Returns a double-precision row vector of int(npoint): 6.4.2 equally spaced points starting at lower and ending at upper. The arguments lower, upper,
and npoint, are all integer, real, or double-precision scalars. If the argument npoint is not present, the value 100 is used in its place.
6.9.b: Example
If you enter
ginit
x = linspace(-pi, +pi)
plot(x, sin(x))
O-Matrix will draw the following plot
6.9.c: Reference
Note that the return value of linspace is a row vector. So, for example, to make the plot above using gplot: 10.1.1 you would enter
ginit
x = linspace(-pi, +pi)'
gplot(x, sin(x))
(Note the ' in this example that is not
in the example above.)
6.10: Create a Grid With Evenly Spaced Logarithms
Syntax logspace(lower, upper)
logspace(lower, upper, npoint)
6.10.a: Description
Returns a double-precision row vector of int(npoint): 6.4.2 points that have their logarithms equally spaced. The first point in the grid is 10^lower. If
upper is equal to PI: 24.1 , the last point in the grid is pi. Otherwise, the last point in the grid is 10^upper. The arguments lower, upper, and npoint,
are all integer, real, or double-precision scalars. If the argument npoint is not present, the value 50 is used in its place.
6.10.b: Example
If you enter
ginit
x = logspace(-1, +1)
plot(x, 1d0 / x)
gyaxis("log")
O-Matrix will draw the following plot
6.10.c: Reference
Note that the return value of logspace is a row vector. So, for example, to make the plot above using gplot: 10.1.1 you would enter
ginit
x = logspace(-1, +1)'
gplot(x, 1d0 / x)
gyaxis("log")
(Note the ' in this example that is
not in the example above.)
6.11: Difference Between Successive Elements In Each Column
Syntax coldiff( x)
6.11.a: Description
Returns a matrix in which the (i,j)th element contains x(i+1,j) - x(i,j), where x is an integer, real, double-precision, or complex matrix. The
return value has the same type and column dimension as x and has one less row.
6.11.b: Example
x = [seq(4), seq(4)^2]
coldiff(x)
returns
{
[ 1 , 3 ]
[ 1 , 5 ]
[ 1 , 7 ]
}
6.12: Finite Differences of Arbitrary Order
Syntax diff(x)
diff(x, k)
6.12.a: Description
Computes the k-th order finite difference of the integer, real, double-precision or complex matrix x. If the argument k is not present, the first order
difference is computed. The return value has the same type as x.
6.12.b: Vector Case
If x is a vector, the return value is its k-th order finite difference and has k fewer elements than x.
6.12.c: Matrix Case
If x is not a vector, each column of the return value is the k-th order finite difference of the corresponding column of x. In this case the return value has
k fewer rows than x.
6.12.d: Finite Difference
If y is a vector of length m, its k-th order finite difference is a vector of length m - k defined by
0
dy
= y
i
k
dy
for i = 1 , ... , m
i
k-1
= y
i
k-1
-
y
i+1
for i = 1 , ... , m-k
and k > 0
i
6.12.e: Example
If you enter
i = 1 :: 4
x = [ i , i^2 ]
diff(x)
{
[ 1 , 3 ]
[ 1 , 5 ]
[ 1 , 7 ]
}
If you continue by entering
diff(x, 2)
{
[ 0 , 2 ]
[ 0 , 2 ]
}
6.13: Replaces Zero By a Small Value
Syntax nozero(x, bound)
6.13.a: Description
Returns the element-by-element: 26.n value
/ x
if |x|
> bound
\ sign(x) bound
if |x|
< bound
nozero(x) = {
where sign(x) is the sign of the corresponding element of x (interpreted as 1 when x is 0).
This function can be used to avoid division by 0 when x is used as an element-by-element divisor.
6.13.b: Example
x
= [-.1, -.01, -.001, 0., .001, .01, .1]
bound = .002
nozero(x, bound)
returns
[-0.1 , -0.01 , -0.002 , 0.002 , 0.01 , 0.1 ]
7: Working with Rows, Columns and Sub-Blocks of Matrices
7.a: Contents
Elements Of A Vector: 7.1
Elements Of A Matrix: 7.2
Accessing A Single Row Or Column: 7.3
Accessing Sequential Rows Or Columns: 7.4
Sequential Elements Of A Vector: 7.5
Accessing A Subblock Of A Matrix: 7.6
Accessing Non-sequential Rows And Columns: 7.7
Vector Indices: 7.8
Using End As An Index Value: 7.9
Changing Matrix Indices: 7.10
Determining The Base Column Index Of A Matrix: 7.11
Determining The Base Row Index Of A Matrix: 7.12
7.1: Elements Of A Vector
Syntax vector ( index )
See Also elements: 3.4 , base: 7.10 , sequential subvectors: 7.5 , and matrix elements: 7.2
7.1.a: Description
References the element with the specified index in the specified vector, where index is an integer scalar. (If index is real, or double-precision, it is
interpreted as an integer using the same convention as in the int: 6.4.2 function. )
7.1.b: Tutorial
The indices of a vector are numbered from 1 to n, where n is the number of elements in the vector. The expression x(2) accesses the second element
of the vector x. If you enter
x = [3, 5, 7]
x(2)
O-Matrix will respond
5
You can also use this notation to assign an element of an existing vector. The result has the type that corresponding to coercion: 4.4 between the type
of the original matrix and the type of the element.
x = [1, 2, 3]
x(2) = 4.4
print type(x), x
results in
real [ 1 , 4.4 , 3 ]
7.2: Elements Of A Matrix
Syntax matrix (row index, column index)
See Also base: 7.10 , elements: 3.4 , and vector elements: 7.1
7.2.a: Description
References the element with the specified row and column index in the specified matrix, where row index and column index are integer scalars. (If
either of the indices is real, or double-precision, it is interpreted as an integer using the same convention as in the int: 6.4.2 function. )
7.2.b: Tutorial
The row indices of a matrix are numbered from 1 to m, where m is the number of rows in the matrix. Similarly, the column indices of a matrix are
numbered from 1 to n, where n is the number of columns in the matrix. The expression x(2, 3) accesses the element in the second row and third
column of the matrix x. If you enter
x = {[1, 2, 3, 4], [5, 6, 7, 8]}
x(2, 3)
O-Matrix will respond
7
You can also use this notation to assign an element of an existing matrix. The result has the type that corresponds to coercion: 4.4 between the type of
the element and the original matrix.
x(1, 4) = 23d0
print type(x), x
results in
double {
[ 1 , 2 , 3 , 23 ]
[ 5 , 6 , 7 , 8 ]
}
7.3: Accessing A Single Row Or Column
Syntax matrix.row(row index)
matrix.col(column index)
See Also base: 7.10 , matrix element: 7.2 , and sequential rows or columns: 7.4
7.3.a: Description
References a row or column of a matrix, where row index and column index are integer scalars. (If either of the indices is real, or double-precision, it is
interpreted as an integer using the same convention as in the int: 6.4.2 function. )
7.3.b: Tutorial
If you enter
x = {[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]}
x.row(2)
O-Matrix will respond
[ 5 , 6 , 7 , 8 ]
If you continue the example above by entering
x.col(3)
O-Matrix will respond
{
3
7
11
}
You can also use .row to assign a row and .col to assign a column. Continuing the previous example, if you type
x.row(2) = fill(3.3, 1, 4)
print type(x), x
O-Matrix will respond
real {
[ 1 , 2 , 3 , 4 ]
[ 3.3 , 3.3 , 3.3 , 3.3 ]
[ 9 , 10 , 11 , 12 ]
}
Note that the result has the type corresponding to coercion: 4.4 between the type of the original matrix and the new row or column.
7.4: Accessing Sequential Rows Or Columns
Syntax matrix.row(starting index, number)
matrix.col(starting index, number)
See Also base: 7.10 , one row or column: 7.3 , and non-sequential rows or columns: 7.7
7.4.a: Description
References the submatrix starting at the specified row or column index and containing the specified number of rows or columns, where starting index
and number are integer scalars. (If either starting index, or number, is real, or double-precision, it is interpreted as an integer using the same
convention as in the int: 6.4.2 function. )
7.4.b: Tutorial
If you enter
x = {[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]}
x.row(1, 2)
O-Matrix will respond
[ 1 , 2 , 3 , 4 ]
[ 5 , 6 , 7 , 8 ]
If you then enter
x.col(1, 2)
O-Matrix will respond
{
[ 1 , 2 ]
[ 5 , 6 ]
[ 9 , 10 ]
}
You can also use .row and .col to assign a submatrix. The result will have the type that corresponds to coercion: 4.4 between the type of the original
matrix and the submatrix. Continuing the previous example, if you enter
x.col(3, 2) = fill(5.5, 3, 2)
print type(x), x
O-Matrix will respond
real {
[ 1 , 2 , 5.5 , 5.5 ]
[ 5 , 6 , 5.5 , 5.5 ]
[ 9 , 10 , 5.5 , 5.5 ]
}
7.5: Sequential Elements Of A Vector
Syntax vector.blk(starting index, number)
See Also base: 7.10 , sequential rows or columns: 7.4 , and vector elements: 7.1
7.5.a: Description
References the subvector with the specified starting index and number of elements, where starting index and number are integer scalars.
7.5.b: Tutorial
The value starting index specifies the first element of the subvector and the value number specifies the number of elements in the subvector. If you
enter
x = [4, 6, 8, 10]
x.blk(2, 2)
O-Matrix will respond
[ 6 , 8 ]
You can also use .blk to assign a subvector. The result has the type that corresponds to coercion: 4.4 between the type of the original vector and the
subvector.
x = {1, 2, 3, 4}
x.blk(2, 3) = {5.5, 5.5, 5.5}
x
results in
{
1
5.5
5.5
5.5
}
7.6: Accessing A Subblock Of A Matrix
Syntax matrix.blk(starting row, starting column, rows, columns)
7.6.a: Description
References the subblock with upper-left corner at the specified starting row and column, with the specified number of rows and columns, where
starting row, starting column, rows and columns are integer scalars. (If starting row, starting column, rows, or columns, is real, or double-precision, it
is interpreted as an integer using the same convention as in the int: 6.4.2 function. )
7.6.b: Tutorial
If you enter
x = {[1, 2, 3, 4], [5, 6, 7, 8]}
x.blk(1, 2, 2, 3)
O-Matrix will respond
{
[ 2 , 3 , 4 ]
[ 6 , 7 , 8 ]
}
You can also use .blk to assign a submatrix. The result will have the type that corresponds to coercion: 4.4 between the type of the original matrix and
the subblock. Continuing the example above
x.blk(1, 2, 2, 2) = fill(6.6, 2, 2)
print x
results in
{
[ 1 , 6.6 , 6.6 , 4 ]
[ 5 , 6.6 , 6.6 , 8 ]
}
7.7: Accessing Non-sequential Rows And Columns
Syntax matrix.row(row flag)
matrix.col(column flag)
matrix.blk(row flag, column flag)
7.7.a: Description
References the submatrix consisting of the specified rows and columns matrix. The row flag is a logical vector with length equal to the number of rows
in matrix. It specifies which rows are included in the submatrix. The column flag is a logical vector with length equal to the number of columns in
matrix. It specifies which columns are included in the submatrix.
7.7.b: Tutorial
You can use logical vectors to access submatrices. If you enter
x = { [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]}
rowflag = {true, false, true}
x.row(rowflag)
O-Matrix will respond
{
[ 1 , 2 , 3 , 4 ]
[ 9 , 10 , 11 , 12 ]
}
If you continue by entering
colflag = [false, true, false, true]
x.col(colflag)
O-Matrix will respond
{
[ 2 , 4 ]
[ 6 , 8 ]
[ 10 , 12 ]
}
If you then enter
x.blk(rowflag, colflag)
O-Matrix will respond
{
[ 2 , 4 ]
[ 10 , 12 ]
}
You can also use logical row and column vectors to assign a value to a submatrix. The result has the type that corresponds to coercion: 4.4 between the
type of the original matrix and the type of the submatrix. If you continue the previous example by entering
x.blk(rowflag, colflag) = {[0, -1.1], [-1.1, 0]}
print type(x), x
O-Matrix will respond
real {
[ 1 , 0 , 3 , -1.1 ]
[ 5 , 6 , 7 , 8 ]
[ 9 , -1.1 , 11 , 0 ]
}
If you then enter
x.row(rowflag) = {[4, 3, 2, 1], [12, 11, 10, 9]}
x
O-Matrix will respond
{
[ 4 , 3 , 2 , 1 ]
[ 5 , 6 , 7 , 8 ]
[ 12 , 11 , 10 , 9 ]
}
If you continue by entering
x.col(colflag) = [{11, 6, 3}, {9, 8, 1}]
print x
O-Matrix will respond
{
[ 4 , 11 , 2 , 9 ]
[ 5 , 6 , 7 , 8 ]
[ 12 , 3 , 10 , 1 ]
}
7.7.c: Reference
You can use this syntax with logical expressions to select rows or columns of a matrix. For example, if you enter
x = seq(4)
y = seq(5)'
z = x * y
z.blk(x <= 3, y >= 3)
O-Matrix will respond
{
[ 3 , 4 , 5 ]
[ 6 , 8 , 10 ]
[ 9 , 12 , 15 ]
}
7.8: Vector Indices
Syntax vector(indices)
matrix(row indices, :)
matrix(:, column indices)
matrix(row indices, column indices)
See Also vector elements: 7.1 , matrix elements: 7.2 , base: 7.10 , non-sequential access: 7.7
7.8.a: Description
References the subvector consisting of the elements with the specified indices, or the submatrix consisting of the rows and columns with the specified
indices, where indices, row indices and column indices are integer vectors (it does not matter if they are row or column vectors). (If row indices or
column indices is real, or double-precision, it is converted to integer using the same convention as in the int: 6.4.2 function.)
The result of an assignment has the type that corresponds to coercion: 4.4 between the type of the left and right hand side of the assignment.
If either of the index vectors is real, or double-precision, it is interpreted as an integer vector using the same convention as in the int: 6.4.2 function.
7.8.b: Tutorial
7.8.b.a: Subvectors
You can use integer vector indices to access subvectors. If you enter
x
= {5., 4., 3., 2.}
indices = {1, 4}
x(indices)
O-Matrix will respond
{
5
2
}
If you continue by entering
x = x'
x(indices)
O-Matrix will respond
[ 5 , 2 ]
You can also use integer vector indices to assign values to a subvector. If you continue by entering
x(indices) = [0., 0.]
print type(x), x
O-Matrix will respond
real [ 0 , 4 , 3 , 0 ]
Note that the result is real because the original vector was integer and the subvector was real. In addition, the subvector x(indices) is a row vector
because x is a row vector (it doesn't matter whether indices is a row or column vector).
7.8.b.b: Submatrices
You can also use integer vector indices to access submatrices. If you enter
x
= {[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]}
rows = {1, 3}
x(rows, :)
O-Matrix will respond
{
[ 1 , 2 , 3 , 4 ]
[ 9 , 10 , 11 , 12 ]
}
If you continue by entering
cols = {2, 4}
x(:, cols)
O-Matrix will respond
{
[ 2 , 4 ]
[ 6 , 8 ]
[ 10 , 12 ]
}
If you then enter
x(rows, cols)
O-Matrix will respond
{
[ 2 , 4 ]
[ 10 , 12 ]
}
You can also use integer vector indices to assign a value to a submatrix. If you continue the previous example by entering
x(rows, cols) = {[0, -1.1], [-1.1, 0]}
print x
O-Matrix will respond
{
[ 1 , 0 , 3 , -1.1 ]
[ 5 , 6 , 7 , 8 ]
[ 9 , -1.1 , 11 , 0 ]
}
If you then enter
x(rows, :) = {[4, 3, 2, 1], [12, 11, 10, 9]}
print x
O-Matrix will respond
{
[ 4 , 3 , 2 , 1 ]
[ 5 , 6 , 7 , 8 ]
[ 12 , 11 , 10 , 9 ]
}
If you continue by entering
x(:, cols) = [{11, 6, 3}, {9, 8, 1}]
print x
O-Matrix will respond
{
[ 4 , 11 , 2 , 9 ]
[ 5 , 6 , 7 , 8 ]
[ 12 , 3 , 10 , 1 ]
}
7.8.c: Removing Matrix Elements
Normally the submatrix on the left side of an assignment operator ( = ) must have the same number of elements as the matrix on the right side of the
assignment operator. There is an exception to this rule when the matrix on the right side of the assignment operator is an empty matrix: 26.o . In this
case, the elements corresponding to the submatrix specified by indices are removed from the matrix on the left side of the assignment operator. For
example, if you enter
x = [1, 2, 3, 4]
k = [2, 3]
x(k) = []
print x
O-Matrix will respond
[ 1 , 4 ]
If you enter
x = { [ 1 , 2 ] , [ 3 , 4 ] }
x(:, 1) = []
print x
O-Matrix will respond
{
2
4
}
If you enter
x = { [ 1 , 2 ] , [ 3 , 4 ] }
x(1, :) = []
print x
O-Matrix will respond
[ 3 , 4 ]
7.9: Using End As An Index Value
Syntax vector(exp:end)
matrix(exp, exp:end)
matrix(exp:end, exp)
7.9.a: Description
When the keyword end is used as part of an index expression: 7.8 , it refers to the maximum index in the vector or matrix being referenced.
7.9.b: Tutorial
7.9.b.a: One Index
You can use end when only one index is specified. If you enter
x = {5., 4., 3., 2.}
x(2 :: end)
O-Matrix will respond
{
4
3
2
}
If you continue by entering
x(1 :: end - 1)
O-Matrix will respond
{
5
4
3
}
You can also use end when assigning a value to a subvector. If you continue by entering
x = x'
x(end - 1 :: end) = [0, 0]
print x
O-Matrix will respond
[ 5 , 4 , 0 , 0 ]
7.9.b.b: Two Indices
You can also use end when two indices are specified. If you enter
x
= {[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]}
x(2::end, :)
O-Matrix will respond
{
[ 5 , 6 , 7 , 8 ]
[ 9 , 10 , 11 , 12 ]
}
If you continue by entering
x(:, 1 :: end - 2)
O-Matrix will respond
{
[ 1 , 2 ]
[ 5 , 6 ]
[ 9 , 10 ]
}
If you then enter
x(2 :: end, 1 :: end - 2)
O-Matrix will respond
{
[ 5 , 6 ]
[ 9 , 10 ]
}
You can also use end when assigning a value to a submatrix. If you continue the previous example by entering
x(end - 1 :: end, end - 1 :: end) = {[0, 0], [0, 0]}
print x
O-Matrix will respond
{
[ 1 , 2 , 3 , 4 ]
[ 5 , 6 , 0 , 0 ]
[ 9 , 10 , 0 , 0 ]
}
7.10: Changing Matrix Indices
Syntax base variable(row, column)
7.10.a: Removed From Language
The base command was present in version 4 of O-Matrix but has been removed in version 5. If this command is used in version 5x, an error message
to this effect is displayed. The old documentation for the base command is included below to aid in converting programs that use this command to run
under version 5.
7.10.b: Description
Changes the index of the upper-left corner of variable to the specified row and column, where row and column are integer scalars.
7.10.c: Tutorial
The default base of a matrix is (1, 1). You can use the base statement to change the indices.
Entering
x = {-6, -3, 0, 3, 6}
base x(-2, 1)
print x(-1), x(0), x(1)
O-Matrix will respond
-3 0 3
because x(-2) corresponds to the first element of the column vector x.
Entering
y = {[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]}
base y(-1, -2)
print y.row(0)
will result in
[ 6 , 7 , 8 , 9 , 10 ]
If you continue the example above by entering
print y.col(0)
O-Matrix will respond
{
3
8
13
}
If you continue the example above by entering
print y(0, 0)
O-Matrix will respond
8
7.11: Determining The Base Column Index Of A Matrix
Syntax colbase( matrix)
7.11.a: Removed From Language
The colbase command was present in version 4 of O-Matrix but has been removed in version 5. If this command is used in version 5, an error
message to this effect is displayed. The old documentation for the colbase command is included below to aid in converting programs that use this
command to run under version 5.
7.11.b: Description
Returns the index corresponding to the first column of a matrix.
7.11.c: Example
x = [1, 2, 3]
base x(0, 2)
colbase(x)
returns
2
7.12: Determining The Base Row Index Of A Matrix
Syntax rowbase( matrix)
7.12.a: Removed From Language
The rowbase command was present in version 4 of O-Matrix but has been removed in version 5. If this command is used in version 5, an error
message to this effect is displayed. The old documentation for the rowbase command is included below to aid in converting programs that use this
command to run under version 5.
7.12.b: Description
Returns the index corresponding to the first row of a matrix.
7.12.c: Example
x = [1, 2, 3]
base x(0, 2)
rowbase(x)
returns
0
8.a: Working with Text Files
The following functions can be used for creating, writing, reading and loading arbitrary format ASCII text files created by O-Matrix or other
applications.
Reading The Next Row From A File
Reading A Specified Number Of Rows From A File
Reading A Matrix Of Specified Size From A File
Reading Files with a Specified Data Value Separator
Specifying Value to be Used for Missing Input Data
write: 8.10
Writing a Matrix to the Screen or a File
write3: 8.11 Specifying Number of Elements per Output Line
writesep: 8.12 Specifying Value for Separating File Output Data
nrows: 8.1
Determining The Number Of Matrix Rows In A File
ncols: 8.2
Determining The Number Of Columns In Each Row Of A File
close: 8.13
Closing Files
eof: 8.14
Detecting End of File
ioformat: 8.17 Setting and Getting Output Formats
8.b: O-Matrix Format Binary Files
O-Matrix binary data files provides a compact, highly efficient format for storing data.
omwrite: 8.15 Writing an O-Matrix Native Format Binary File
8.c: Working with Excel Files
xlwrite: 8.19 Writing Excel Data
xlsheets: 8.20 Getting Excel Worksheet Names
8.d: Other Formats
diary: 8.27
Saving Output Written in Command Window
8.e: Reading and Writing Binary Data
The following functions can be used to read arbitrary format files from other software packages, custom applications, and instruments.
bwrite: 8.23 Writing Binary Files
8.f: Network and Internet IO
netio: 8.29 Reading and Writing to Network Folders
urlget: 8.30 Reading Data from the Internet
ftp: 8.31 Transferring Files Over the Internet Using FTP
8.1: Determining The Number Of Matrix Rows In A File
Syntax nrows( file)
8.1.a: Description
Returns the number of rows in the specified file, where file is a character row vector. The return value is an integer scalar.
The number of rows is equal to the number of lines except that the ellipsis (...) joins the following line to the current one. The expression
rowdim(ncols(file, "byte")): 8.2 can be used to count the actual number of lines in a file.
8.1.b: Example
You can create a file called temp.dat that contains the text
pi = 3.14159
e = 2.71828
by entering
clear
file = "temp.dat"
rmfile(file);
write(file, "pi = 3.14159")
write(file, "e = 2.71828")
close(file)
If you then enter
nrows("temp.dat")
O-Matrix will respond
2
because temp.dat has two rows.
The nrows function also counts empty lines. You can create a file called temp.dat that contains the text
pi = 3.14159
e = 2.71828
one = 1
by entering
clear
file = "temp.dat"
rmfile(file);
write(file, "pi = 3.14159")
write(file, "")
write(file, "e = 2.71828")
write(file, "one = 1")
close(file)
If you then enter
nrows("temp.dat")
O-Matrix will respond
4
If a line contains an ellipsis (...), nrows will not count the following line separately. You can create a file called temp.dat that contains the text
square root of 2 equals ...
1.41421
a separate row
by entering
clear
file = "temp.dat"
rmfile(file);
write(file, "square root of 2 equals ...")
write(file, "1.41421")
write(file, "a separate row")
close(file)
and you enter
nrows("temp.dat")
O-Matrix will respond
2
8.2: Determining The Number Of Columns In Each Row Of A File
Syntax ncols( file, matrix type)
8.2.a: Description
Determines the number of columns of the type specified by matrix type that is in each row of the file specified by file, where both matrix type and file
are character row vectors. The valid matrix types are "logical", "char", "byte", "int", "real", "double", and "complex". The return value is an integer
column vector with the same number of rows as are in the file. The i-th element of the return value is equal to the number of entries in the i-th row of
the file.
8.2.b: Example
You can create a file called temp.dat that contains the text
1 2 3
4 5
by entering the following commands
clear
file = "temp.dat"
rmfile(file);
write(file, "1 2 3")
write(file, "4 5")
close(file)
If you then enter
ncols("temp.dat", "int")
O-Matrix will respond
{
3
2
}
because temp.dat has three integers in its first row and two in its second row. If you continue by entering
ncols("temp.dat", "char")
O-Matrix will respond
{
5
3
}
because temp.dat has five characters in its first row and three in its second row (there is one space between each of the numbers).
8.2.c: Ellipsis
If a line contains an ellipsis (...), ncols will not count the following line separately, (characters from the ellipsis up to and including the next new
line are replaced by a single space). You can create a file called temp.dat that contains the text
1
4
6
9
2 3 ...
5
7 8 ...
10
by entering the following commands
clear
file = "temp.dat"
rmfile(file);
write(file, "1 2 3 ...")
write(file, "4 5")
write(file, "6 7 8 ...")
write(file, "9 10")
If you then enter
ncols("temp.dat", "int")
O-Matrix will respond
{
5
5
}
The matrix type "byte" is the same as "char" but the interpretation of the ellipsis is suppressed. If you continue by entering
ncols("temp.dat", "byte")
O-Matrix will respond
{
9
3
9
4
}
8.3: Reading The Next Row From A File
exists: 6.5.16 , nrows: 8.1 , readh: 8.6 , write: 8.10 , file2str: 9.14 , strreplace: 9.8 , bread: 8.22 , spread: 8.21 , xlread: 8.18 , and
See
Also
8.3.a: Description
Returns a row vector of the specified type containing the data from the current marker position in the specified file to the end of the current row, where
file is a character row vector, and mtype is "logical", "char", "int", "real", "double", "complex" or "byte".
If a line of a file is empty, read returns an empty matrix for that line.
8.3.b: Example
Each file has a marker that points to the next line in the file. The marker starts at the first line of the file and moves top to bottom.
8.3.b.a: Integer
If mtype is "int", the lines read from file can only contain integer values. You can create a file called temp.dat that contains the text
1
3
2
4
by entering the following commands
clear
file = "temp.dat"
rmfile(file);
write(file, "1 2")
write(file, "3 4")
close(file)
If you then enter
O-Matrix reads the first line of temp.dat and responds
[ 1 , 2 ]
The file marker now points to the second line of temp.dat. If you continue the previous example by entering
O-Matrix will respond
[ 3 , 4 ]
8.3.b.b: Real
If mtype is "real", the lines read from file can contain integer and real values. You can create a file called temp.dat that contains the text
3.3 5
by entering the following commands
clear
file = "temp.dat"
rmfile(file);
write(file, "3.3 5")
close(file)
If you then enter
O-Matrix will respond
[ 3.3 , 5 ]
8.3.b.c: Double
If mtype is "double", the lines read from file can contain integer, real, and double-precision values. You can create a file called temp.dat that contains
the text
3.3 5 2.5d0
by entering the following commands
clear
file = "temp.dat"
rmfile(file);
write(file, "3.3 5 2.5d0")
close(file)
If you then enter
O-Matrix will respond
[ 3.3 , 5 , 2.5 ]
8.3.b.d: Logical
If mtype is "logical", the lines read from file can only contain the values "T" and "F". You can create a file called temp.dat that contains the text
T
F
T
by entering the following commands
clear
file = "temp.dat"
rmfile(file);
write(file, "T F T")
close(file)
If you then enter
O-Matrix will respond
[ T , F , T ]
8.3.b.e: Character
If mtype is "char" or "byte", the lines are read from the file as ascii characters. You can create a file called temp.dat that contains the text
The bright red fox
jumped over the dull white fence.
by entering the following commands
clear
file = "temp.dat"
rmfile(file);
write(file, "The bright red fox")
write(file, "jumped over the dull white fence.")
close(file)
If you then enter
print line2
O-Matrix will respond
jumped over the dull white fence.
8.3.b.f: Complex
If mtype is "complex", the lines read from file can contain integer, real, or double-precision numbers grouped in pairs. Each pair is enclosed by
parentheses, with the real and imaginary parts separated by a comma. You can create a file called temp.dat that contains the text
(1,2) (3,4)
by entering the following commands
clear
file = "temp.dat"
rmfile(file);
write(file, "(1,2) (3,4)")
close(file)
If you then enter
print 2 * x
O-Matrix will respond
[ (2,4) , (6,8) ]
8.3.c: Ellipsis
In all of the examples above each row of the matrix resulting from a read corresponded to one line of the file. An ellipsis can be used to continue a row
on the next line of a file. You can create a file called temp.dat that contains the text
The bright red fox...
jumped over the dull white fence.
by entering the following commands
clear
file = "temp.dat"
rmfile(file);
write(file, "The bright red fox...")
write(file, "jumped over the dull white fence.")
close(file)
If you then enter
print line1
O-Matrix will respond
The bright red fox jumped over the dull white fence.
On the other hand this interpretation of the ellipsis can be suppressed. If you continue by entering
print line1
O-Matrix will respond
The bright red fox...
The ellipsis can also be used for comments because the read function ignores characters from the ellipsis to the end of the line. (In actual fact the text
from ellipsis to the end of the line is replaced by a single space.) You can create a file called temp.dat that contains the text
... This entire line is ignored
The bright red fox... This text is ignored
jumped over the dull white fence.
by entering the following commands
clear
file = "temp.dat"
rmfile(file);
write(file, "... This entire line is ignored")
write(file, "The bright red fox... This text is ignored")
write(file, "jumped over the dull white fence.")
close(file)
If you then enter
print line1
O-Matrix will respond
The bright red fox jumped over the dull white fence.
Note that the ellipsis and the rest of the characters on the line are replaced by a single space.
8.4: Reading A Specified Number Of Rows From A File
8.4.a: Description
Reads values from the specified file and returns a matrix of the specified type with the specified number of rows. The arguments file and mtype have
the same meaning as in read(file, mtype): 8.3 . The integer scalar nr specifies the number of rows to read and return. The number of columns in the
returned matrix equals the number of columns in the first row read. All rows read from file must contain the same number of columns. The first row of
the resulting matrix corresponds to the first values read, the next row to the next values read, and so on.
8.4.b: Example
You can create a file called complexvals.dat that contains the text representation of the following complex values
(1,2) (3,4) (5,6)
(7,8) (9,10) (11,12)
by entering the following commands
clear
file = "complexvals.dat"
rmfile(file);
write(file, "(1,2) (3,4) (5,6)")
write(file, "(7,8) (9,10) (11,12)")
close(file)
If you then enter
O-Matrix will respond
{
[ (1,2) , (3,4) , (5,6) ]
[ (7,8) , (9,10) , (11,12) ]
}
8.5: Reading A Matrix Of Specified Size From A File
8.5.a: Description
Description Reads values from the specified file and returns a matrix of the specified type and dimension. The arguments file and mtype have the same
meaning as in read(file, mtype): 8.3 . The integer scalars nr and nc specify the dimension of the return value.
The first row of the resulting matrix corresponds to the first values read, the next row to the next values read, and so on. If there are not enough
elements in a row of the file, spaces are used to fill character matrices and zeros are used to fill numeric matrices. If there are more than enough
elements in a row of the file, the extra elements are ignored.
8.5.b: Example
You can create a file called temp.dat that contains the text
(1,2) (3,4) (5,6)
(7,8) (9,10) (11,12)
by entering the following commands
clear
file = "temp.dat"
rmfile(file);
write(file, "(1,2) (3,4) (5,6)")
write(file, "(7,8) (9,10) (11,12)")
close(file)
If you then enter
O-Matrix will respond
{
[ (1,2) , (3,4) ]
[ (7,8) , (9,10) ]
}
8.6.a: Description
Reads text headers from the specified file and returns a character matrix containing the headers in the given text file. The argument file has the same
meaning as in read(file, mtype): 8.3 . The returned value headers contains N rows where N is the number of headers at the current line in the file file.
Headers in the input file file must be separated by spaces or tabs and each header string must not contain spaces or tabs.
The first row of the resulting matrix corresponds to the first header, the next row to the next header, and so on.
8.6.b: Examples
If you have a data file, "temp.dat" that contains the following
Sample1
1.1
2.1
Sample2 Sample3
1.2
1.3
2.2
2.3
and you enter
clear
file = "temp.dat"
O-Matrix will respond,
Sample1
Sample2
Sample3
If you continue by entering
O-Matrix will respond,
{
[ 1.1 , 1.2 , 1.3 ]
[ 2.1 , 2.2 , 2.3 ]
}
The read function can also read text files that contain multiple header lines at arbitrary lines within the numeric data. If you have a sample file
Test One
Sample1 Sample2 Sample3
1.1 1.2 1.3
2.1 2.2 3.3
Test Two
Sample4 Sample5 Sample6
3.1 3.2 3.3
4.1 4.2 4.3
5.1 5.2 5.3
and you enter,
clear
# skip descriptive text line
D1 = read(file, "real", 2, 3)
# read the 2 lines of data that follow
D2 = read(file, "real", 3, 3)
# read the 2 lines of data that follow
# print headers and data for 'Test One'
print H1.row(1), H1.row(2), H1.row(3)
print D1
# print headers and data for 'Test Two'
print H2.row(1), H2.row(2), H2.row(3)
print D2
O-Matrix will print,
Sample1 Sample2 Sample3
{
[ 1.1 , 1.2 , 1.3 ]
[ 2.1 , 2.2 , 3.3 ]
}
Sample4
{
[ 3.1 ,
[ 4.1 ,
[ 5.1 ,
}
Sample5 Sample6
3.2 , 3.3 ]
4.2 , 4.3 ]
5.2 , 5.3 ]
The header values can be used for labelling graphs and other O-Matrix output. If you continue the example above by entering,
gxtitle(H2.row(2))
gplot(D2.col(2))
O-Matrix will create a plot of the second column of data from 'Test Two' in the sample data above, using the corresponding data header value.
8.7: Skipping Lines When Reading Data
Syntax read(file, mtype, nr, nc, nSkip)
8.7.a: Description
The argument nSkip must be an integer scalar which specifies the number of lines to skip before loading data.
8.7.b: Examples
If you have sample data file sample.dat that contains
Sample Data
One Two Three
1.1
2.1
1.2
2.2
1.3
2.3
and you enter,
clear
file = "sample.dat"
O-Matrix will respond,
{
[ 1.1 , 1.2 , 1.3 ]
[ 2.1 , 2.2 , 2.3 ]
}
8.8: Reading Files with a Specified Data Value Separator
Syntax read(file, mtype, nr, nc, nSkip, separator)
8.8.a: Description
The argument separator must be a character scalar which specifies a character in addition to the default white space characters for separating values of
input. O-Matrix always treats spaces and tabs as value separators when reading text files. The argument separator is used in addition to space and tab
as a value delimiter.
8.8.b: Examples
If you have sample data file sample.dat that contains
Sample Data
1.1;1.2;1.3
2.1;2.2;2.3
and you enter,
clear
file = "sample.dat"
read(file, "real", 2, 3, 1, ";")
O-Matrix will respond,
{
[ 1.1 , 1.2 , 1.3 ]
[ 2.1 , 2.2 , 2.3 ]
}
8.9: Specifying Value to be Used for Missing Input Data
Syntax read(file, mtype, nr, nc, nSkip, separator, missingValue)
8.9.a: Description
The missingValue argument is a numeric scalar which is used to replace, or substitute for entries which are not present in input data. When the
missingValue argument is specified, a non white-space separator value must also be specified.
8.9.b: Examples
If the file missingdata.txt contains
1,,,
1,2,3
,1,2
and you enter
clear
read("missingdata.txt", "int", 3, 4, ",", 0, 99)
O-Matrix will print
{
[ 1 , 99 , 99 , 99 ]
[ 1 , 2 , 3 , 0 ]
[ 99 , 1 , 2 , 0 ]
}
8.10: Writing a Matrix to the Screen or a File
Syntax write( file, matrix)
8.10.a: Description
Writes matrix to the specified file or the screen, where file is a character row vector.
Each element is written using the same format as described in the floating point: 8.17.3 and integer: 8.17.2 format sections.
The brackets, braces, and commas that the print: 3.12 statement displays are not included. A single space is included between each value in a row
unless matrix is a character matrix. Each row of the matrix corresponds to a line in file.
8.10.b: Example
If there is no file named TEMP.OMS in the current directory, and you enter
z = {[0r0, 1i0], [1r0, 1r0 + 1i0]}
write("TEMP.OMS", z)
close
the file TEMP.OMS will be created and will contain
/ 0
i \
the complex valued matrix
\ 1
1+i /
If there is a file named TEMP.OMS in the current directory, the example above will append the matrix to TEMP.OMS.
Continuing the previous example, you can view TEMP.OMS by selecting "File | Open Program" and choosing TEMP.OMS from the file browser, which
will then display the following:
(0,0) (0,1)
(1,0) (1,1)
If file is "screen", O-Matrix writes the matrix to the command output window.
x = {[1, 2], [3, 4]}
write("screen", x)
results in
1 2
3 4
8.11: Specifying Number of Elements per Output Line
Syntax write( file, matrix, max)
8.11.a: Description
Writes matrix to the specified file or the screen, where file is a character row vector. The output is similar to write(file, matrix): 8.10 except that max is
an integer scalar specifying the maximum number of elements written in each line.
8.11.b: Example
If the number of columns in matrix is less than or equal to max, the write function writes one line of the file for each row of the matrix. If you enter
x = {[1.1, 2.2], [3.3, 4.4]}
write("TEMP.OMS", x, 5)
close
O-Matrix will write
to
1.1 2.2
3.3 4.4
the file TEMP.OMS.
If the number of columns in matrix is greater than max, the write function uses the ellipsis ("...") to signify that a row continues on the next line of the
file.
x = {[1.1, 2.2, 3.3, 4.4, 5.5], [6.6, 7.7, 8.8, 9.9, 10.1]}
write("screen", x, 3)
results in
1.1
4.4
6.6
9.9
2.2 3.3 ...
5.5
7.7 8.8 ...
10.1
Note that each row of the matrix ends in a line without an ellipsis.
8.12: Specifying Value for Separating File Output Data
Syntax write( file, matrix, max, separator)
8.12.a: Description
Writes matrix to the specified file, where file is a character row vector. The definition of max is the same as in write(file, matrix,max): 8.11 . The
argument separator is a character scalar which is used to separate individual values in the output instead of the default space character.
8.12.b: Examples
If you enter,
D = {[1.1, 1.2, 1.3], [2.1, 2.2, 2.3]}
write("sep.dat", D, coldim(D), ";")
close
O-Matrix will create the file sep.dat in the current working
1.1;1.2;1.3
2.1;2.2;2.3
directory: 6.5.5 which contains,
8.13: Closing Files
Syntax close
close( file)
See Also eof: 8.14 , exists: 6.5.16 , rmfile: 6.5.9 , isdir: 6.5.12 , read: 8.3 , write: 8.10
8.13.a: Description
Closes the file specified by the character row vector file. If file is not specified, all open files that are open for reading: 8.3 or writing: 8.10 are closed.
8.13.b: Example
You can use the close function to reset a file marker to the first line of its file. If the file TEMP.DAT contains
1
4
2
5
3
6
and you enter
file = "TEMP.DAT"
O-Matrix will respond
[ 1 , 2 , 3 ]
If you continue by entering
close(file)
O-Matrix will respond
{
[ 1 , 2 , 3 ]
[ 4 , 5 , 6 ]
}
8.14: Detecting End of File
Syntax eof(file_name)
8.14.a: Description
Returns true, if there are no characters past the current read: 8.3 location marker for the specified file and false otherwise, where file_name is a
character row vector.
8.14.b: Example
If the file temp.dat is located in the current working directory: 6.5.5 and contains
1 0
0 1
and you enter
f = "temp.dat"
while not eof(f) begin
end
O-Matrix will respond
[ 0 , 1 ]
[ 1 , 0 ]
8.15: Writing an O-Matrix Native Format Binary File
Syntax omwrite( file, matrix)
omwrite( file, matrix, varNames)
8.15.a: Description
Stores the variable type, dimension, name, and value of expression matrix in the file specified by the file name file. If the file name file does not
include a suffix, the omwrite function will append the string .OMD to file. If the file specified by file exists it is overwritten. The type: 6.4.1 of matrix
must be "int", "real", "double", or "complex".
If specified the variable varNames is a character matrix where row 1 is the variable name for the first column of matrix, row 2 is the variable name for
the second column, etc. The number of rows in varNames must be less than or equal the coldim: 3.14 of matrix.
See the omread: 8.16 function for more details on the information that is stored in O-Matrix format binary files.
8.15.b: Example
If you enter,
x = [1.1, 1.2]
omwrite("tst", x)
O-Matrix will create a new file, tst.OMD in the current working directory that contains the matrix x If you continue the example above by entering
omwrite("tst", x, {"Col 1", "Two"})
O-Matrix will re-create the file tst.OMD and store the strings "Col 1" and "Two" to specify the names of each column of variable x.
See the omread: 8.16 function for more detailed examples of using the omwrite and omread functions.
8.16: Reading an O-Matrix Native Format Binary File
[D, valueName, variableNames] = omread( file)
[D, valueName, variableNames, createDate] = omread( file)
8.16.a: Description
Loads the data stored in file file which was created with the omwrite: 8.15 function. The returned value D is the same type: 6.4.1 and size: 3.16 as was
created with omwrite. If the file name file does not include a suffix, the omread function will append the string .OMD to file.
If specified, the returned value valueName is a character row vector which is the name of the variable stored in file. If specified, the returned value
variableNames is a character matrix where each row of variableNames is the name of each column of data in D. The number of rows in
variableNames is less than or equal the column dimension of D. If specified, the returned value createDate is a character row vector which contains
the time that file was created. The format of createDate is the same as the clock: 6.5.2 function.
8.16.b: Examples
If you enter,
D = {[1.1, 1.2], [2.1, 2.2], [3.1, 3.2]}
omwrite("tst", D)
print type(D)
print D
O-Matrix will create a file tst.OMD, load the data from
the data.
real
the file, print the type: 6.4.1 of the data that was stored in tst.OMD and then print the value of
{
[ 1.1 , 1.2 ]
[ 2.1 , 2.2 ]
[ 3.1 , 3.2 ]
}
8.16.b.a: Specifying valueName
If you continue the example by entering
print valueName
O-Matrix will print the name of the data variable when it was created. Note that the variable that omread assigns to, e.g. matrix above, does not need
to be the same name as when the file was created.
D
8.16.b.b: Specifying variableNames
If you enter
omwrite("NamedData.dat", D, {"Column 1", "Col 2"})
O-Matrix will create the file NamedData.dat in the current working directory: 6.5.5 which contains the variable D and the strings "Column 1" and "Col
2". If you continue by entering,
print varNames.row(1)
print varNames.row(2)
O-Matrix will print each of the stored strings that represent the names of the first 2 columns in D.
Column 1
Col 2
8.16.b.c: Specifying createDate
If you continue by entering
[D, valueName, varNames, createDate] = omread("NamedData.dat")
print createDate
O-Matrix will print the date and time that the file NamedData.dat was created.
If the value stored by omwrite is an expression: 4 value, that is not a named variable then the value of valueName is t#### where #### is the number
of microseconds that O-Matrix had been running when fileName was created. If you enter,
clear
R = rand(10000,300)
omwrite("C.OMD", R * 1i0)
print valueName
O-Matrix will print a value of the form
t3429157
8.17: Setting and Getting Output Formats
8.17.a: Overview
O-Matrix provides support for controlling the screen and file output format of numeric and textual data.
8.17.b: Contents
Getting An Output Format: 8.17.1
Setting The Integer Output Format: 8.17.2
Setting Floating Point Output Formats: 8.17.3
Set Printing and Tracing Options: 8.17.4
8.17.1: Getting An Output Format
Syntax format(type)
8.17.1.a: Description
Returns a character row vector containing the current format setting for the specified type, where type is "int", "real", "double", or "complex".
8.17.1.b: Example
If you enter
format real "f10.5"
format("real")
O-Matrix will respond
f10.5
8.17.2: Setting The Integer Output Format
Syntax format int places
Command | Numeric Format . . .
8.17.2.b: Description
Sets the output format for integer matrices to the specified number of places, where places is a character row vector. If places is an empty vector, the
output format is reset.
8.17.2.c: Tutorial
If you enter
clear
format int "5"
each subsequent integer value output will be right-justified in five columns. If you then enter
x = [1, 2, 3]
x
O-Matrix will respond
[
1 ,
2 ,
3 ]
The format statement also affects the values output by the write: 8.10 function. If you continue the example above by entering
write("screen", x)
O-Matrix will respond
1
2
3
Note that the write function inserts an extra space between elements of the matrix.
Entering
format int ""
will reset integer output to have no leading spaces.
8.17.3: Setting Floating Point Output Formats
Syntax format real form
format double form
format complex form
Command | Numeric Format . . .
8.17.3.b: Description
Sets the output format for the specified type of matrix, where form is a character row vector. If form is an empty vector, the output format is reset.
8.17.3.c: Tutorial
8.17.3.c.a: Fixed Format
If form begins with the character "f", numeric output will be right-justified in the number of columns specified by the integer following the "f". A
decimal point and integer may then follow, in which case the second integer specifies the number of digits to the right of the decimal point for numeric
output.
If you enter
format real "f5"
x = [1.2, 2.4, 3.6]
x
O-Matrix will respond
[
1 ,
2 ,
4 ]
Note that the values are rounded to the nearest integer. If you continue by entering
format real "f5.2"
x
O-Matrix will respond
[
1.20 ,
2.40 ,
3.60 ]
The format statement also affects the values output by the write: 8.10 function. If you enter
x = double(x)
format double "f5.2"
write("screen", x)
O-Matrix will respond
1.20
2.40
3.60
In addition, the format statement affects the values returned by the ntoa: 9.5 function. If you enter
x = complex(x)'
format complex "f5.2"
ntoa(x)
O-Matrix will respond
( 1.20, 0.00)
( 2.40, 0.00)
( 3.60, 0.00)
8.17.3.c.b: Exponential Format
If form begins with the character "e", numeric output will be expressed in scientific notation and right-justified in the number of columns specified by
the integer following the "e". A decimal point and integer may then follow, in which case the second integer specifies the number of digits to the right
of the decimal point in the mantissa.
If you enter
format real "e12.3"
x = [1.1, 10.1, 100.01]
x
O-Matrix will respond
[
1.100e+000 ,
1.010e+001 ,
1.000e+002 ]
The "e", the sign of the exponent, and the exponent itself combine to occupy five columns of output.
8.17.3.d: Free Format
If form begins with the character "g", numeric output will be right-justified in the number of columns specified by the integer following the "g". A
decimal point and integer may then follow, in which case the second integer specifies the number of digits of precision. If a number cannot be output
in decimal notation using the specified number of digits of precision, it will be displayed in scientific notation.
If you enter
x = [1.1, 10.1, 100.01]
format double "g12.2"
double(x)
O-Matrix will respond
[
1.1 ,
10 ,
1e+002 ]
8.17.3.d.a: Field Width
All of the formats above will produce stared output if the number cannot not be represented in the specified number of columns with the specified
precision. If you enter
x = 12345r0
format complex "f5.2"
x
O-Matrix will respond
(*****,*****)
On the other hand, if you just specify the type of formatting, "f", "e" or "g", O-Matrix will adjust the number of columns and decimal places to fit the
value being printed. If you continue the example above by entering
format complex "g"
x
O-Matrix will respond
(12345,0)
("g" is the default setting for the O-Matrix floating point output values.)
8.17.3.d.b: Resetting Format
The commands
format real ""
format double ""
format complex ""
reset the floating point formats to their default values.
8.17.4: Set Printing and Tracing Options
Syntax setprint("continue", flag)
setprint("trace",
flag)
setprint("include", flag)
8.17.4.a: Description
This function controls some special printing and tracing options.
setprint("continue", flag)
If the logical scalar flag is true, each matrix is printed is such a way that a variable can be assigned to the matrix by copying it from the output window
and pasting it to a file or the command line The default value for this setting is false.
setprint("trace", flag)
The value of a statement that consists of a single expression is printed unless it is equal to novalue: 6.3.16 . For example, if you enter
1 + 2
O-Matrix will print the value
3
If the logical scalar flag is true, the file and line number is printed next to the value of each expression statement that is printed. The default value for
flag is false. This print option can help in locating expression statements that result in printed output.
setprint("include", flag)
Function and script files are often automatically included. If the logical scalar flag is true, a message is printed identifying what file was needed and
where it was required.
8.17.4.b: Example
8.17.4.b.a: Trace
If the file TEMP.OMS contains the text
1 + 2
and you enter
include temp.oms
3
If you then enter
setprint("trace", true)
include temp.oms
expression statement: file C:\OMWIN\TEMP.OMS, line 1
3
8.17.4.b.b: Continue
If you enter
setprint("continue", true)
print seq(3) * seq(3)'
O-Matrix will respond
{
[
[
[
}
...
1 , 2 , 3 ], ...
2 , 4 , 6 ], ...
3 , 6 , 9 ] ...
Note that the continuation characters enable you to use this matrix as source code within an O-Matrix program. When using the continue option,
character matrices will be surrounded by the " character when printed. If continue this example by entering
print { "The quick brown fox", "jumped over the fence"}
O-Matrix will respond
{ ...
"The quick brown fox", ...
"jumped over the fence" ...
}
8.17.4.b.c: Include
If you enter
clear
setprint("include", true)
colsum( {1, 2, 3} )
O-Matrix will respond
Automatic include of C:\OMWIN\FUNCTION\COLSUM.OMS
required at line 5 in command line
6
The value six is equal to one plus two plus three. The value 5 may be different
depending on the number of commands entered before this example.
8.18.a: Overview
Reads data from Microsoft Excel files, (.XLS files). The argument file must be a character row vector that specifies the name of the file to load. By
default xlread loads the first worksheet in the given file. If all data in the given worksheet are numeric-valued, then the value returned by xlread is
an NR by NC double matrix where NR is the number of rows in the worksheet, and NC is the number of columns. The first non-empty row in the
worksheet is assumed to be column headers used by Excel and are not loaded by the xlread function. If present, the second argument sheetName must
be a character row vector that specifies the name of the worksheet within the given file to load.
8.18.b: Examples
If you have an Excel file xlio.xls, that contains 2 columns and 5 rows of numeric data that looks like
and at the O-Matrix prompt you enter,
O-Matrix will respond
{
[
[
[
[
[
}
1
2
3
4
5
,
,
,
,
,
1
1
2
4
8
]
]
]
]
]
If you continue the above example by renaming the second sheet of xlio.xls to MySheet and enter the following data
and then enter the following at the command prompt
O-Matrix will respond
{
[ 1 , 1 ]
[ 2 , 4 ]
[ 3 , 9 ]
}
If you have an Excel file xlascii.xls that contains two non-numeric columns,
and you enter
O-Matrix will create the character matrix T. Excel returns the default number of columns for each column in the spread sheet, so the result T will
contain 2 rows and 510 columns since each column A, and B contain 255 characters. You can use the align function to reduce the result. If at the OMatrix prompt you enter
align(T," ",[10,10])
O-Matrix will respond
oneone
twoone
threeone
onetwo
twotwo
threetwo
Alternatively, if you know that each column of your Excel file contains the default number of characters, (255), you can use the following function to
trim the blank columns from the result
function xlclip(T) begin
nc = coldim(T)/255
nr = rowdim(T)
iCol = fill("",nr,1)
for j = 0 to nc-1 begin
iCol = [iCol, strclip(T.blk(1,j*255+1,nr,255))]
end
return iCol
end
8.18.c: Notes
The xlread function can only load Excel files that contain 30000 rows or less. You must have a copy of Excel installed on your machine to use the
xlread function. The xlread function is compatible with Excel versions prior to Excel 2007. See the file omwin\function\xlread.oms for
instructions on using xlread with Excel 2007.
8.19: Writing Excel Data
Syntax xlwrite( fileName, varName)
xlwrite( file, varName, sheetName)
xlwrite( file, varName, sheetName, xlsRange)
8.19.a: Overview
Create or update Microsoft Excel files. The character row vector fileName specifies the file name to be used in Excel. If fileName does not exist it is
created, otherwise it is opened. The argument varName must be an expression that returns a character, integer, real, or double-precision matrix. By
default, the xlwrite function copies data to Excel starting in cell A1 of the current or specified work sheet. The character row vector, xlsRange may
be used to specify an alternate location for the transferred data.
8.19.b: Examples
8.19.b.a: Creating and Updating Numeric Excel Files
If at the O-Matrix prompt you enter,
xlFile = "C:\temp\tst.xls"
rmfile(xlFile);
xlwrite(xlFile, rand(4,2))
O-Matrix will create a new Excel file that contains 4 rows and 2 columns of numeric data starting in cell A1 of the first sheet. If you continue the
example above by entering
xlwrite(xlFile, seq(10), "MySheet")
O-Matrix will open the existing tst.xls file, create a new work sheet named MySheet, and add 10 rows of data starting in cell A1.
8.19.b.b: Using Excel Range Specifications
By default, O-Matrix transfers data to the first column and the first row of the first worksheet, or the worksheet specified by sheetName. If present, the
character row vector xlsRange can be used to specify the cells to use for the transferred data. If you continue the example above by entering
xlwrite(xlFile, identity(3), "MySheet", "D4:F6")
O-Matrix will open the tst.xls file and add the 3 row by 3 column identity matrix to the MySheet worksheet starting in row 4 of column 4.
8.19.b.c: Transferring Character Data to Excel
Character vectors are transferred to individual cells in Excel. By default a character row vector is transferred to the first cell of the first worksheet. If at
the O-Matrix prompt you enter
xlFile = "c:\temp\chars.xls"
rmfile(xlFile);
xlwrite(xlFile, "Hello World")
O-Matrix will create a new Excel file that contains the string "Hello World" in the first row of the first column in Sheet1. Character range values are
specified as a single cell If you continue the example by entering
xlwrite(xlFile, "Greetings", "Characters", "B2")
O-Matrix will open the chars.xls file, create a new worksheet named Characters and write the string Greetings in the second row of the second
column.
8.20: Getting Excel Worksheet Names
Syntax xlsheets(file)
8.20.a: Overview
Gets the names of the worksheets in the given Excel file, file. The argument file must be a character row vector specifying a valid Excel file. The result
from xlsheets is an NR by NC character matrix, where NR is the number of worksheets in file and NC is the length of the longest worksheet name in
file.
8.20.b: Example
If you have an Excel file, xlsheets.xls that contains seven worksheets and looks like
and you enter,
xlsheets("xlsheets.xls")
O-Matrix will respond
Fri$Mon$
Sat$Sun$
Thurs$Tue$
Wed8.20.c: Notes Excel stores sheet names with the dollar character appended to the end of the name. When passing sheet names to the xlread function you may omit this character if desired. 8.21: Reading SigmaPlot Data Syntax spread(file, item left, top, right, bottom) See Also read: 8.3 , write: 8.10 , xlread: 8.18 8.21.a: Description Returns data from a SigmaPlot worksheet in file file within the specified range. SigmaPlot must be installed and running when this function is called. The argument file must be a character row vector specifying the name of a SigmaPlot data file. The argument item must be a character row vector specifying the name of the data item to be read. The arguments, left, top, right, and bottom must be integer scalars. The argument left specifies the first column, and the argument top specifies the first row. The argument right specifies the last column and bottom specifies the last row. If all cells of the current worksheet within the specified range contain numbers, the spget function returns an NR by NC double-precision matrix. If the first cell in the specified range is text data, the range specified must be a vector. Note: If you specify a range that is outside of the current worksheet, the SigmaPlot server will generate an exception. If retrieving numeric data, all cells within the specified must contain valid numeric data. If retrieving character data, all cells in the specified column must contain valid text data. 8.21.b: Examples If SigmaPlot is running and at the O-Matrix prompt you enter, clear file = [OM_INSTALL,"\example\IO\SplotSample.jnb"] spread(file, "RationalData", 1, 1, 4, 2) O-Matrix will echo, { [ 3.14159 , 6.28319 , 9.42478 , 12.5664 ] [ 6.28319 , 12.5664 , 18.8496 , 25.1327 ] } 8.22: Reading Binary Files Syntax bread bread(file) bread(dtype, nbyte, dnum) See Also: read: 8.3 , xlread: 8.18 , bwrite: 8.23 8.22.a: Description If no arguments are present, the file currently open for binary reading is closed. If one argument is present, the specified file is opened for binary input where file is a character row vector. If a file is already open for reading its is closed before file is opened. If three arguments are present, a specified number of elements are read from the file. The character row vector dtype specifies the type of data that is being read from the file and must be either "char", "int", or "real". The integer scalar nbyte specifies the number of bytes corresponding to each data value in the file. If dtype is "char", nbyte must be 1. If dtype is "int", nbyte may be 2 or 4. If dtype is "real" , nbyte may be 4 or 8. The integer scalar dnum specifies the number of data elements that are read. The return value is a double-precision column vector of length dnum containing the data. If dtype is "char", the return value can be converted to character using the char function. 8.22.b: Example The function bread is linked according to the convention in linkdll: 22.3.1 . If you enter file = "temp.dat" rmfile(file); write(file, "abcd") close(file) dll dll\sample.dll, bread bread(file) bread("char", 1, 4) O-Matrix will respond { 97 98 99 100 } which are the ASCII: 24.3 codes of the letters a, b, c, and d respectively. 8.23: Writing Binary Files Syntax bwrite bwrite(file) bwrite(dtype, nbyte, data) See Also: write: 8.10 , bread: 8.22 8.23.a: Description If no arguments are present, the file currently open for binary writing is closed. If one argument is present, the specified file is opened for binary output where file is a character row vector. If a file is already open for writing its is closed before file is opened. If three arguments are present, the values in data are written to the file. The character row vector dtype specifies the type of data that is being written to the file and must be either "char", "int", or "real". The integer scalar nbyte specifies the number of bytes corresponding to each data value in the file. If dtype is "char", nbyte must be 1. If dtype is "int", nbyte may be 2 or 4. If dtype is "real", nbyte may be 4 or 8. The double-precision column vector data contains the values that are written to the file. 8.23.b: Example The function bwrite is linked according to the convention in linkdll: 22.3.1 . If you enter dll dll\sample.dll, bwrite file = "temp.dat" rmfile(file); data = double({97, 98, 99, 100, 10}) bwrite(file) bwrite("char", 1, data) read(file, "char") O-Matrix will respond abcd because the ASCII: 24.3 codes 97, 98, 99, 100, 10 correspond to the characters a, b, c, d, and NEW_LINE. 8.24: Reading and Plotting WAV Audio Files Syntax readwav( file) Syntax readwav( file, plot, print) See Also bread: 8.22 8.24.a: Description Reads .WAV format audio files and returns a double precision column vector. The character row vector file specifies the file to read. If present, the arguments plot and print must be logical scalars. If the argument plot equals true the readwav function will plot the contents of the input file. If the argument print equals true, the readwav function will print information about the contents of the file. 8.24.b: Example If you enter D = readwav([OM_INSTALL, "\example\chimes.wav"], true, true) O-Matrix will plot the contents of the chimes.wav audio file from the distribution and echo the following results to the screen file length is 15912 bytes format tag, 1 = PCM 1 number of channels 1=mono 2=stereo 1 sample rate (samples/sec) 22050 bytes per sec 22050 block align 1 bits per sample 8 length of data block in bytes is 15876 8.25: Reading HDF Data Syntax h5read(file, object parent, object name) See Also: h5write: 8.26 , read: 8.3 , bread: 8.22 8.25.a: Description Reads a dataset or attribute from the specified file. The argument file is a character row vector that specifies a valid HDF5 file. The argument object parent is a character row vector specifying a valid group or dataset in file file. The argument object name is a character row vector specifying the name of the dataset or attribute to read. If object name is a dataset, object parent must be a valid group, otherwise object parent may be either a group or dataset. O-Matrix supports reading, writing, and creating HDF5 files. See the NCSA HDF 5 (http://hdf.ncsa.uiuc.edu/HDF5) site for more information about HDF5, and a description of this file format. 8.25.b: Example If you have an HDF5 file test.h5 that contains a dataset "vector", which is a three-element dataset that contains the value 1, and you enter h5read("test.h5", "/", "vector") O-Matrix will respond { 1 1 1 } If the dataset "vector", contains a character attribute, "description", whose value is "My Data", and you enter h5read("test.h5","/vector","description") O-Matrix will respond My Data 8.26: Writing HDF Data Syntax h5write(file, object type, object parent, object name, matrix) See Also: h5read: 8.25 , write: 8.10 , bwrite: 8.23 8.26.a: Description Writes a matrix to an HDF file. The argument file is a character row vector that specifies an HDF5 file. If file does not exist, it is created. The argument object type is a character row vector which must be either "dataset" or "attribute". If object type equals "dataset" then the given matrix is added to the HDF file as an HDF dataset. If object type equals "attribute" then matrix is added as an HDF attribute. The argument object parent is a character row vector that specifies the fully-qualified name of an object for storing matrix. If object parent does not exist, it is created as a new group. If object parent is a dataset, object type must equal "attribute". The argument object name is a character row vector specifying the name for the output matrix. The argument matrix is an character, integer, real, or double-precision valued matrix. O-Matrix supports reading, writing, and creating HDF5 files. See the NCSA HDF 5 (http://hdf.ncsa.uiuc.edu/HDF5) site for more information about HDF5, and a description of this file format. 8.26.b: Example If the file h5write.h5 does not exist, and you enter h5write("h5write.h5","dataset","/","dmat", {[1d0, 2], [3, 4]}) h5write("h5write.h5","dataset","/Integer Data","vector", seq(3) ) O-Matrix will create a new HDF file that contains four HDF objects: the root group "/", the dataset "dmat", the group "/Integer Data", and the dataset "/Integer Data/vector". If you continue the example by entering h5write("h5write.h5","attribute","/Integer Data/vector","description", "My Data" ) h5write("h5write.h5","attribute","/","Number", 1) O-Matrix will add two attributes to the h5write.h5 data file. The attribute "description" is attached to the dataset "/Integer Data/vector". The attribute "Number" is attached to the group "/". You can enter the following commands to display the contents of h5write.h5 h5read("h5write.h5", h5read("h5write.h5", h5read("h5write.h5", h5read("h5write.h5", "/", "dmat") "/Integer Data", "vector") "/Integer Data/vector", "description") "/", "Number") and O-Matrix will respond { [ 1 , 2 ] [ 3 , 4 ] } { 1 2 3 } My Data 1 8.27: Saving Output Written in Command Window Syntax diary diary( name) diary("on") diary("off") See Also commandio: 2.5.2 8.27.a: Description This function is used to save a file that is a copy of the text printed in the Command window: 2.5.2 . diary toggles on and off the saving of output to the current diary file. diary("on") turns on the saving of output to the current diary file. This has no effect if saving of output is already turned on. diary("off") turns off the saving of output to the current diary file. This has no effect if saving of output is already turned off. diary(name) sets the current diary file to the one specified by name where name is a character row vector. In addition, it turns on output to the current diary file. The default value for the current diary file is "diary". 8.27.b: Example If you enter diary("MyDiary.txt") print "sample diary file" diary("off") O-Matrix will add the text sample diary file at the end of the file MyDiary.txt in the current working directory: 6.5.5 . 8.28: Reading MATLAB® Data See Also: read: 8.3 , bread: 8.22 , h5read: 8.25 , xlread: 8.18 8.28.a: Overview The MATLAB IO functions can be used to load numeric MATLAB data, i.e. MAT-Files, into O-Matrix. A description of each of the available commands can be found in the following sections. 8.28.b: Contents Reading MAT-Files: 8.28.1 Listing the Variables in a MAT-File: 8.28.2 8.28.1: Reading MAT-Files Syntax mfread(file, varName) See Also mfvars: 8.28.2 8.28.1.a: Description Returns an nr by nc double-precision matrix containing the value of varName from the MAT-file file. The values of nr and nc are equal to the row and column dimensions of varName. The file file must only contain numeric-valued matrices. In particular the mfread function does not support loading MAT-Files that contain sparse matrices, cell arrays or structures. 8.28.1.b: Example If in MATLAB you enter the commands x = [ 1 2 3 ] save tst.mat MATLAB will create the file tst.mat which contains one variable x. If you continue the example by entering mfread("tst.mat","x") at the O-Matrix prompt, O-Matrix will respond [ 1 , 2 , 3 ] 8.28.2: Listing the Variables in a MAT-File Syntax mfvars(file) See Also mfread: 8.28.1 8.28.2.a: Description Returns a character matrix containing the variables in the MAT-file specified by the character row vector file. The value returned contains nr rows where nr equals the number of variables in file. The value returned contains nc columns where nc is the length of the longest variable name in file. 8.28.2.b: Example If in MATLAB you enter the commands x = [ 1 2 3 ] save tst.mat MATLAB will create the file tst.mat which contains one variable x. If you continue the example by entering mfvars("tst.mat") at the O-Matrix prompt, O-Matrix will respond x 8.29: Reading and Writing to Network Folders See Also h5read: 8.25 , read: 8.3 , write: 8.10 , and urlget: 8.30 8.29.a: Description The input and output routines in O-Matrix support reading and writing to local network shares and extranet folders such as WebDAV servers. This provides a convenient method for centrally locating your data. Other O-Matrix users can run your applications without copying your data to their local machine and you can easily load centrally located data without copying it to your local machine. 8.29.b: Examples 8.29.b.a: Data IO on a Network Share This example creates the file rand.txt on the network share \\Harmonic\temp, (You will need to edit the value of shareFolder in the example to a value that is a valid shared directory on your local network). If at the O-Matrix command line prompt you enter clear const shareFolder = "\\Harmonic\temp\" fileName = [shareFolder,"rand.txt"] data = rand(10 , 15) write(fileName, data) close(fileName) O-Matrix will create the file rand.txt in the \temp folder on the machine Harmonic. Selecting My Network Places in Windows explorer you can browse to this machine and directory to verify that the file was created. If you continue the example by entering data = read(fileName,"double", 10, 15) data(1,1) O-Matrix will respond 0.253719 8.29.b.b: Data IO to a WebDAV Folder WebDAV is an Internet file access protocol. Windows XP includes WebDAV support which enables you to access servers on the Internet just as you would a file or server share. The MSN Communities and XDrive servers support this protocol for public access. The following example reads and displays the README.TXT file stored in the OMatrix folder on the MSN Communities server. clear const webFolder = "\\www.msnusers.com\OMatrix\Documents\" fileName = [webFolder,"README.TXT"] Nr = nrows(fileName) read(fileName, "char", Nr, 60) close(fileName) O-Matrix will respond This folder is intended for storage of O-Matrix related documents, utilities, and applications. Users interested in participating in the O-Matrix news group should visit http://groups.yahoo.com/group/omatrix/ (Note that the first operation on a WebDAV server may be slow but subsequent operations generally run quickly) You can also directly write to a WebDAV folder. If you continue the example above by entering fileName = [webFolder,"TEST.TXT"] for i = 1 to 3 begin write( fileName, seq(4)*i ) end close O-Matrix will create the file TEST.TXT on the server. Using Internet Explorer you can browser to the server directory to verify the contents of the file. 8.30: Reading Data from the Internet Syntax urlget(URL, urlget(URL, output file) output file, "binary") See Also: h5read: 8.25 , read: 8.3 8.30.a: Description Reads a file from the address specified by the given Internet URL. The argument URL is a character row vector that specifies the valid URL of an ASCII file. The argument output file is a character row vector specifying the name of a file on your local system for storing the retrieved data. If present, the third argument must be "binary" and instructs the function to transfer the file at URL in binary-mode. That is no carriage return or line feed translations are performed. 8.30.b: Transferring ASCII Data The two-argument form of urlget transfers the requested data in ASCII. That is any necessary carriage return and line feed transforms that are necessary for the given system are performed before storing the data on your system. This provides an efficient method of loading HTML, XML, or raw text data from Internet resources. 8.30.b.a: Examples If you enter urlget("http://www.omatrix.com/urlget.csv", "C:\temp\tst.csv") O-Matrix will download the file urlget.csv from the home directory on omatrix.com and save it on your local system. You can verify that this download succeeded by entering M = read("C:\temp\tst.csv", "int", 100, 100) contour(M) which will produce the following contour plot The urlget function can also be used to access server-side CGI resources. If you enter clear const tickers = {"hcow", "unfi","ebay"} NTickers = rowdim(tickers) uriStart = "http://table.finance.yahoo.com/table.csv?a=0&b=1&c=2002&d=11&e=31&f=2002&s=" uriEnd ="&y=0&g=w&ignore=.csv" for i = 1 to NTickers begin sym = tickers.row(i) URL = [uriStart, sym, uriEnd] oFile = [sym, ".csv"] urlget(URL, ["c:\temp\", oFile]); end O-Matrix will download weekly stock data for the symbols HCOW, UNFI, and EBAY from the Yahoo stock chart server. 8.30.c: Transferring Binary Data The three-argument form of urlget transfers the requested data in binary mode. This function provides highly-optimized binary transfer of data from Internet resources to your local system. 8.30.c.a: Example If you enter urlget("http://www.omatrix.com/downloads/LibSetup.zip", "C:\temp\Lib.zip", "binary") O-Matrix will download the file LibSetup.zip from omatrix.com and save it on your local system. 8.31: Transferring Files Over the Internet Using FTP Syntax ftp(command, ...) See Also: mkdir: 6.5.15 , rmdir: 6.5.10 , listdir: 6.5.6 , urlget: 8.30 8.31.a: Dll Linkage The ftp routine is a dynamic link library and must be linked to O-Matrix before it can be used. The command dll dll\ftp.dll, ftp performs this linkage and is required before any calls to ftp and after any clear commands. 8.31.b: Overview The ftp function can be used to transfer files over the internet. The character row vector command specifies which ftp command to execute and must be one of the following: "open", "close", "get", "ls", "delete", "cd" or "type". A description of each of these commands can be found in its corresponding section below. 8.31.c: Contents open - Opening an ftp Connection to a Remote Host: 8.31.1 close - Closing the ftp Connection to a Remote Host: 8.31.2 get - Retrieving a File From a Remote Host: 8.31.3 put - Transferring a File To a Remote Host: 8.31.4 ls - Listing File and Directory Names On a Remote Host: 8.31.5 delete - Deleting a File on a Remote Host: 8.31.6 cd - Changing Directories on a Remote Host: 8.31.7 type - Setting the File Transfer Type: 8.31.8 8.31.1: open - Opening an ftp Connection to a Remote Host Syntax ftp("open,remote site name,user id,password) See Also: closeftp: 8.31.2 8.31.1.a: Description Opens an ftp connection to a remote site over the internet. The return value is true if the connection was established and false otherwise. The character row vector remote site name specifies the name of the remote site. The character row vector user id specifies the login user name on the remote machine. The character row vector password specifies the password for the user. 8.31.1.b: Example If ftp is not currently linked to O-Matrix, enter the command dll dll\ftp.dll, ftp You can now open a remote connection by entering the command ftp("open", "ftp.microsoft.com", "anonymous", "guest") O-Matrix will attempt to connect to the Microsoft ftp site. O-Matrix will respond T if the connection is successful and F otherwise. 8.31.2: close - Closing the ftp Connection to a Remote Host Syntax ftp("close") See Also: openftp: 8.31.1 8.31.2.a: Description Terminates current ftp connection. 8.31.2.b: Example If ftp is not currently linked to O-Matrix, enter the command dll dll\ftp.dll, ftp You can now open a remote connection by entering the command ftp("open", "ftp.microsoft.com", "anonymous", "guest") If O-Matrix responds T the connection was successful. In this case you can close the connection by entering ftp("close") 8.31.3: get - Retrieving a File From a Remote Host Syntax ftp("get", remote file name) See Also: openftp: 8.31.1 , lsftp: 8.31.5 , putftp: 8.31.4 8.31.3.a: Description Gets the specified file from the currently connected remote machine and puts it in the O-Matrix current working directory. The character row vector remote file name specifies the name of the file on the remote host to retrieve. The return value is true if the file was successfully retrieved and false otherwise. 8.31.3.b: Example If ftp is not currently linked to O-Matrix, enter the command dll dll\ftp.dll, ftp You can now open a remote connection by entering the command ftp("open", "ftp.microsoft.com", "anonymous", "guest") If O-Matrix responds T the connection was successful. In this case, you can copy the file dirmap.htm from the remote machine by entering ftp("get", "dirmap.htm") If you then enter listdir The file dirmap.htm will be included in the listing for the current O-Matrix working directory. 8.31.4: put - Transferring a File To a Remote Host Syntax ftp("put", file name) See Also: openftp: 8.31.1 , getftp: 8.31.3 , lsftp: 8.31.5 8.31.4.a: Description Transfers a file from the local machine to the currently connected remote machine. The character row vector file name specifies the name on the local machine of the file to transfer. The return value is true if the file was successfully transferred and false otherwise. 8.31.5: ls - Listing File and Directory Names On a Remote Host Syntax ftp("ls") See Also: openftp: 8.31.1 , cdftp: 8.31.7 8.31.5.a: Description Returns a character matrix containing a listing of the current directory on the remote machine. Each row of the return value contains a directory entry left justified in the row with spaces used to fill the right side. The column dimension of the return value is the maximum number of characters over all the directory entries. 8.31.5.b: Example If ftp is not currently linked to O-Matrix, enter the command dll dll\ftp.dll, ftp You can now open a remote connection by entering the command ftp("open", "ftp.microsoft.com", "anonymous", "guest") If O-Matrix responds T the connection was successful. In this case you can list the current directory on the remote machine by entering ftp("ls") 8.31.6: delete - Deleting a File on a Remote Host Syntax ftp("delete", remote file name) See Also: openftp: 8.31.1 , lsftp: 8.31.5 8.31.6.a: Description Deletes the specified file on a remote host. The character row vector remote file name specifies the name of the file to delete. The return value is true if the file was deleted and false otherwise. 8.31.7: cd - Changing Directories on a Remote Host Syntax ftp("cd") ftp("cd", remote directory) See Also: openftp: 8.31.1 , lsftp: 8.31.5 8.31.7.a: Description The return value is a character row vector containing the name of the current directory on the remote host. If present, the character row vector remote directory specifies a directory on the host that is to become the current directory. 8.31.7.b: Example If ftp is not currently linked to O-Matrix, enter the command dll dll\ftp.dll, ftp You can now open a remote connection by entering the command ftp("open", "ftp.microsoft.com", "anonymous", "guest") If O-Matrix responds T the connection was successful. In this case you can change into the subdirectory called Products by entering the following command ftp("cd", "Products") If this change of directory is successful, O-Matrix will respond Products 8.31.8: type - Setting the File Transfer Type Syntax ftp("type", type name) See Also: openftp: 8.31.1 , closeftp: 8.31.2 , lsftp: 8.31.5 8.31.8.a: Description Specifies the ftp file transfer type. The character row vector type name must be either "ASCII" or "BINARY" . The type "ASCII" should be used when transferring text files and "BINARY" should be used for other files. The default mode is ascii. In binary mode, the file is moved byte-by-byte. 8.31.8.b: Example If ftp is not currently linked to O-Matrix, enter the command dll dll\ftp.dll, ftp You can now open a remote connection by entering the command ftp("open", "ftp.microsoft.com", "anonymous", "guest") If O-Matrix responds T the connection was successful. In this case you can copy the file LS-LR.ZIP by entering the commands ftp("type", "BINARY") ftp("get", "LS-LR.ZIP") If you then enter the command listdir The file LS-LR.ZIP will be included in the listing for the current O-Matrix working directory. 9: Strings, Searching and Sorting 9.a: Contents align: 9.1 atod: 9.2 atoi: 9.3 char2dbl: 9.4 ntoa: 9.5 num2str: 9.6 str2num: 9.7 strreplace: 9.8 strclip: 9.9 clipstr: 9.10 low2up: 9.11 up2low: 9.12 dquote: 9.13 file2str: 9.14 pack: 9.15 unpack: 9.16 char2id: 9.17 reprow: 9.18 str2strdir: 9.19 sort: 9.20 Lining Up Data Fields In A Character Matrix Converting ASCII Numbers To Double-Precision Column Vector Converting ASCII Numbers To Integer Conversion of Text Matrix to a Double Precision Matrix Converting A Number To ASCII Characters Conversion of Numeric Matrix to Character Matrix Converting a Character Matrix to a Numeric Matrix Substituting Strings in Character Matrices Removing Trailing Spaces Remove Leading and Trailing Spaces Converting Lower Case to Upper Case Converting Upper Case to Lower Case Surrounding Text in Quotes Converts a Text File to a Character Row Vector Packs An Entire Character Matrix Into One Row Vector Unpacks A Character Matrix From a Row Vector Convert a Character Row Vector to a Valid O-Matrix Identifier Replacing a Row of a Character Matrix Map All Occurrences of a String In a Directory Sorting Rows Of A Matrix sort3: 9.21 Sorting Rows With a Specified Key psort: 9.22 Sorting The Rows Of A Matrix By Pointers psort3: 9.23 Specifying Sort Key When Sorting By Pointers mlmode_sort: 9.24 Sorting (Mlmode) reverse: 9.25 Reversing Row Order Of A Matrix flipud: 9.26 Flipping the Row Order of a Matrix fliplr: 9.27 Flipping the Column Order of a Matrix rot90: 9.28 Rotate A Matrix By a Multiple of 90 Degrees nonzeros: 9.29 Obtaining the Nonzero Elements of a Matrix find: 9.30 Determining Indices Corresponding to Nonzero Elements find2: 9.31 Determining Indices Where A Text Pattern Occurs find3: 9.32 Determining Indices Where A Character Is Between Limits dec2hex: 9.33 Conversion From Decimal to Hexadecimal hex2dec: 9.34 Conversion From Hexadecimal to Decimal findstr: 9.35 Searching Strings and Matrices using Regular Expressions whichrow: 9.36 Matching Rows of A Character Matrix 9.1: Lining Up Data Fields In A Character Matrix Syntax [data] = align(text, separator, width) [data] = align(text, separator, width, adjust) [data, width] = align(text, separator, width) See Also read: 8.3 , sort: 9.20 , atod: 9.2 , char2dbl: 9.4 , find2: 9.31 , strreplace: 9.8 9.1.a: Description Returns the character matrix data which contains the information in text with fields aligned to certain columns. The character row vector separator specifies a list of characters that separate fields in the matrix text. The integer row vector width can be either an input value or a return value determined by align. It specifies the number of columns in each field and the number of fields. If present, adjust must be "right" and specifies that the resulting values should be right, instead of left, adjusted. 9.1.b: Example The align function fills the end of each field with spaces to obtain the specified width. Suppose you had recorded the following weather conditions: city temp. Chicago 65 Atlanta 80 Washington, D.C. 72 Seattle 63 Los Angeles 77 conditions windy sunny humid rain cloudy If you enter clear text = { ... "Chicago;65;windy", ... "Atlanta;80;sunny", ... "Washington, D.C.;72;humid", ... "Seattle;63;rain", ... "Los Angeles;77;cloudy" ... } separator = ";" [data, width] = align(text, separator) print data O-Matrix will respond Chicago 65 windy Atlanta 80 sunny Washington, D.C. 72 humid Seattle 63 rain Los Angeles 77 cloudy If you continue by entering print width O-Matrix will respond [ 17 , 3 , 7 ] If a field is longer than the specified width, it is truncated. If you continue the last example by entering width = [10, 5, 15] align(text, separator, width) O-Matrix will respond Chicago 65 Atlanta 80 Washington72 Seattle 63 Los Angele77 windy sunny humid rain cloudy If a row of text contains two or more separators with no other character between, they only count as one field separator. Thus multiple spaces can be used to separate fields. In addition, leading and trailing blanks are deleted from each field. If you enter text = { ... " a; b c ", ... "d ;e f " ... } separator = "; " width = [5, 5, 5] align(text, separator, width) O-Matrix will reply a d b e c f By default align uses left adjustment of the fields (as in the previous example). The right adjustment option fills the beginning of each field with spaces to obtain the specified width. If you enter format int "5" x = {[1, 2, 3, 4], [5, 6, 7, 8]} title = "one;two;three;four" separator = ";" width = [5, 6, 6, 6] adjust = "right" header = align(title, separator, width, adjust) write("screen", header) write("screen", x) O-Matrix will respond one 1 5 two three 2 3 6 7 four 4 8 Note that field widths for the second, third, and fourth columns are 6 because an extra space is printed between the elements on each row. 9.2: Converting ASCII Numbers To Double-Precision Column Vector Syntax atod(text) See Also char2dbl: 9.4 , atoi: 9.3 , ntoa: 9.5 , double: 6.4.4 9.2.a: Description Returns a column vector, with the same row dimension as text, in which each element is the double-precision value for the corresponding row of the character matrix text. 9.2.b: Example x = {"3.50", "4.50"} 2. * atod(x) results in { 7 9 } atod The function ignores white space: 26.ar at the beginning of each row. The number is represented by a sequence of characters from the set "0" through "9", "D", "d", "E", "e", "+", and "-". Any other character signals that the number terminated at the previous character. If there are no valid characters following leading white space, zero is returned. atod({" two", " 4", "+4d3", "-4e3", "4i3"}) results in { 0 4 4000 -4000 4 } (Note that the character "i" is not in the set of characters defined above.) 9.3: Converting ASCII Numbers To Integer Syntax atoi(x) See Also atod: 9.2 , ntoa: 9.5 , int: 6.4.2 9.3.a: Description Returns an integer column vector representation of x, where x is a character matrix. The return value has the same row dimension as x. The ith row of the matrix x is converted to the ith element of the return value. Any fractional part of x is ignored. 9.3.b: Example ascii = "3.3" atoi(ascii) returns 3 9.4: Conversion of Text Matrix to a Double Precision Matrix Syntax char2dbl(text, separator) See Also atod: 9.2 , align: 9.1 9.4.a: Description Returns a double precision matrix containing the free format values represented by text. The return value has the same row dimension as text. The columns dimension is equal to the maximum number of fields in any of the rows of the matrix text. The character row vector separator specifies a list of character that separate fields in each row of text (each field in text corresponds to a column in the return value). 9.4.b: Example If you enter text = { ... "1,2,3", ... "4;,5; 6", ... "7 8 9" ... } separator = ",; " x = char2dbl(text, separator) print x O-Matrix will respond { [ 1 , 2 , 3 ] [ 4 , 5 , 6 ] [ 7 , 8 , 9 ] } Note that a connected sequence of separators characters have the same effect as one separator character. 9.4.c: Reference If no value is present for a certain field, the value zero is returned. For example, if you enter text = { ... "1,2", ... "4;,5; 6", ... "7 8" ... } separator = ",; " x = char2dbl(text, separator) print x O-Matrix will respond { [ 1 , 2 , 0 ] [ 4 , 5 , 6 ] [ 7 , 8 , 0 ] } 9.5: Converting A Number To ASCII Characters Syntax ntoa(numbers) See Also atod: 9.2 , atoi: 9.3 , char: 6.4.6 , format: 8.17.1 9.5.a: Description Returns a character-matrix representation of the specified numbers, where numbers is an integer, real, double-precision, or complex column vector. The i-th element of numbers is represented by the i-th row of the return value. The current format: 8.17.1 for the type of numbers is used to convert the values. For example, if numbers is real, and the current format of real values specifies that they be displayed within 10 columns, ntoa will return a character matrix with 10 columns. This function is useful when you want to display a number as text in a graphics plot or when you want to use different formats for outputting different columns of a matrix. 9.5.b: Example format real "f10.5" x = ntoa({4., 3., pi}) format real "f5.1" y = ntoa({4., 3., pi}) print [x, y] returns 4.00000 3.00000 3.14159 4.0 3.0 3.1 You can restore real formatting to its original value with the command format real "" 9.6: Conversion of Numeric Matrix to Character Matrix Syntax num2str( x) num2str( x, f) See Also ntoa: 9.5 9.6.a: Description Converts an integer, real, double-precision or complex matrix to a character matrix representation. Each row of the result corresponds to a row of x. If f is an integer, real, or double-precision scalar and equal to an integer value, it specifies the number of digits of precision in the result. If f is a character row vector, it specifies the format used by sprintf: 20.13 to convert each element of x to a string. The default value for f is three. 9.6.b: Example If you enter x = 1. / (seq(3) * seq(3)') num2str(x) O-Matrix will reply 1 0.5 0.333 0.5 0.25 0.167 0.333 0.167 0.111 9.7: Converting a Character Matrix to a Numeric Matrix Syntax str2num( s) See Also num2str: 9.6 , atod: 9.2 , atoi: 9.3 9.7.a: Description Converts a character matrix to a numeric matrix. The elements of the result are specified and separated the same as an input array in Mlmode: 25.2.9 with the exception that the outside surrounding [ and ] need not be included in s. 9.7.b: Example If in Mlmode you enter s = [ '1 2 3+i' ; '4+j 5 6' ] str2num(s) O-Matrix will reply { [ (1,0) , (2,0) , (3,1) ] [ (4,1) , (5,0) , (6,0) ] } 9.7.c: Speed This routine uses the eval: 20.10 function to enable compilation of expressions (such as 4+j in the example above). It therefore is much slower than the routine atod: 9.2 which does not allow as general a set of input formatting. 9.8: Substituting Strings in Character Matrices Syntax strreplace(x, oldString, newString) strreplace(x, oldString, newString, matchCase) See Also lower: 9.12.c , ntoa: 9.5 , atod: 9.2 , atoi: 9.3 , char: 6.4.6 , file2str: 9.14 , align: 9.1 , find2: 9.31 9.8.a: Description Replaces all occurrences of the character row vector oldString with the character row vector newString in the character matrix x. If present, the argument matchCase must be a logical scalar which specifies if case matching should be used when replacing strings. 9.8.b: Examples If you enter, strreplace("Hello World", "Hello", "Hi") O-Matrix will respond Hi World The strreplace function can also replace strings in matrices with more than one row and patterns that do not have the same length. If you enter M = {"aA1a","a1"} strreplace(M, "a", "bb") O-Matrix will return, bbA1bb bb1 By default, the strreplace function is case sensitive, and patterns must match exactly to be replaced. If you continue the example above by entering, strreplace(M, "a", "bb", false) O-Matrix will respond bbbb1bb bb1 9.9: Removing Trailing Spaces Syntax strclip( text) See Also deblank: 9.9.c , clipstr: 9.10 , strreplace: 9.8 , findstr: 9.35 , align: 9.1 , ntoa: 9.5 9.9.a: Description Returns a copy of text in which the trailing spaces are deleted, where text is a character matrix. If text has more than one row, the trailing spaces are all spaces past the last column that has a non space character in it. If all the characters in text are spaces, the column dimension of the return value is zero. 9.9.b: Example str = "Jack " print [DQUOTE, str, DQUOTE] returns "Jack " if you continue by entering print [DQUOTE, strclip(str), DQUOTE] O-Matrix will respond "Jack" 9.9.c: Mlmode In Mlmode: 25 this function is called deblank instead of strclip. If in Mlmode you enter, str = 'Jack '; [DQUOTE, str, DQUOTE] returns "Jack " if you continue by entering [DQUOTE, deblank(str), DQUOTE] O-Matrix will respond "Jack" 9.10: Remove Leading and Trailing Spaces Syntax clipstr( text) See Also strclip: 9.9 , strreplace: 9.8 , findstr: 9.35 , align: 9.1 9.10.a: Description Returns a copy of the character matrix text with leading and trailing spaces removed. The return value is a character matrix with the same row dimension as text. 9.10.b: Example If you enter setprint("continue", true) x = " 1 " x O-Matrix will respond " 1 " If you then enter x = clipstr(x) x O-Matrix will respond "1" You can use clipstr with a matrix that has more than one row. If you continue the example above by entering x = { " one", " four" } x O-Matrix will respond { ... " one ", ... " four" ... } If you then enter x = clipstr(x) x O-Matrix will respond { ... " one", ... "four" ... } You can return O-Matrix to its default printing mode by entering the command setprint("continue", false) 9.11: Converting Lower Case to Upper Case Syntax low2up(x) See Also upper: 9.11.c , up2low: 9.12 , ntoa: 9.5 , atod: 9.2 , atoi: 9.3 , strreplace: 9.8 , char: 6.4.6 9.11.a: Description Returns a copy of x in which the lowercase letters are converted to uppercase, where x is a character matrix. 9.11.b: Example x = "aBcDeFg" low2up(x) returns ABCDEFG 9.11.c: Mlmode In Mlmode: 25 , this function is called upper instead of low2up. If in Mlmode you enter x = 'aBcDeFg'; upper(x) O-Matrix will respond ABCDEFG 9.12: Converting Upper Case to Lower Case Syntax up2low(x) See Also lower: 9.12.c , low2up: 9.11 , ntoa: 9.5 , atod: 9.2 , atoi: 9.3 , strreplace: 9.8 , char: 6.4.6 9.12.a: Description Returns a copy of x in which the uppercase letters are converted to lowercase, where x is a character matrix. 9.12.b: Examples x = "aBcDeFg" up2low(x) returns abcdefg The up2low and low2up: 9.11 functions can also enable more general string comparisons than provided by the built in operators. If you enter, x = "aBcde" y = "ab12" up2low(x.col(1,2)) == up2low(y.col(1,2)) O-Matrix responds T 9.12.c: Mlmode In Mlmode: 25 , this function is called lower instead of up2low. If in Mlmode you enter x = 'aBcDeFg'; lower(x) O-Matrix will respond abcdefg 9.13: Surrounding Text in Quotes Syntax dquote(text) See Also autoexec: 24.1 , and call back: 26.a 9.13.a: Description Returns a copy of the character row vector text that is surrounded by the " character. The return value is a character row vector with two more elements that text. 9.13.b: Example This function is useful for forming call back: 26.a commands. If you enter cmd = dquote("My Caption") cmd O-Matrix will respond "My Caption" If you continue by entering cmd = ["delwin(", cmd, ")"] cmd O-Matrix will respond delwin("My Caption") If you continue by entering adddialog("My Caption", [100, 100, 200, 100], cmd) O-Matrix will display an empty dialog window. If you then choose the "Close" option from the dialog's menu, the command specified by cmd will execute and the dialog will be deleted. In addition the text T will echo in the command window because it is the return value of the delwin function when the window deletion is successful. 9.14: Converts a Text File to a Character Row Vector Syntax file2str(file) file2str(file, oldString, newString) See Also fullpath: 6.5.14 , exists: 6.5.16 , strreplace: 9.8 , ischarvector: 6.6.13 , read: 8.3 , pack: 9.15 9.14.a: Description Reads a text file as a character row vector. If the character row vector arguments oldString and newString are present, they specify strings that are to be substituted during file loading. 9.14.b: Example If the file test.txt contains Hello World and you enter f = file2str("test.txt") O-Matrix will create the character row vector f which contains Hello followed by CRLF, followed by World. If you continue the example by entering file2str("test.txt", "World", "Earth") O-Matrix will respond Hello Earth 9.15: Packs An Entire Character Matrix Into One Row Vector Syntax pack(mat, ch) See Also clipstr: 9.10 , unpack: 9.16 , file2str: 9.14 9.15.a: Description Returns a character row vector that contains the information in the entire character matrix mat where mat has at least one row. Leading and trailing spaces in each row of mat are not included in the return value. The character ch, followed by a space, is placed between the rows of mat in the return value. To be specific, if row1, row2, ... , and rowN are the rows of mat with leading and trailing spaces removed, the return value is the row vector [row1, ch, " ", row2, ch, " ", ... , rowN] The function pack is useful when multiple character matrices need to be packed into one large character matrix. If the character ch is not present in the matrix mat, the original information can be recovered using the function unpack: 9.16 . 9.15.b: Example If you enter mat = {"row 1", "row 2", "row 3"} ch = "," pack(mat, ch) O-Matrix will respond row 1, row 2, row 3 9.16: Unpacks A Character Matrix From a Row Vector Syntax unpack(vec, ch) See Also pack: 9.15 9.16.a: Description Returns a character matrix corresponding to the character row vector vec. Each row of the return value is equal to the characters (not including leading white space) between occurrences of the character ch, in the vector vec. To be specific, suppose the vector vec is equal to [Row1, ch, Row2, ch, ... , RowN] and there are no other occurrences of the character ch in the vector vec. The return value has N rows and is equal to row1 row2 ... rowN where for each j, rowj is equal to Rowj with leading spaces removed. In the special case where vec only contains spaces and the ch character, the return value has N rows and one column and its elements are all spaces. 9.16.b: Example If you enter vec = "row 1, row 2, row 3" ch = "," unpack(vec, ch) O-Matrix will respond row 1 row 2 row 3 9.17: Convert a Character Row Vector to a Valid O-Matrix Identifier Syntax char2id( v) See Also ntoa: 9.5 , atod: 9.2 , up2low: 9.12 , low2up: 9.11 9.17.a: Description This function returns a character row vector that is a valid O-Matrix identifier. The return value has the same length as the character row vector v and is as close to v as possible. If the first character of v is not a letter, it is converted to an underbar in the return value. If any other character of v is not a letter or a number between "0" and "9", it is also converted to an underbar in the return value. 9.17.b: Example If you enter char2id("Size of Truck") O-Matrix will respond Size_of_Truck 9.18: Replacing a Row of a Character Matrix Syntax reprow(mat, i, value) See Also string equality: 4.16 , strclip: 9.9 , clipstr: 9.10 , strreplace: 9.8 , findstr: 9.35 9.18.a: Description Returns a copy of the character matrix mat with row number i replaced by the character row vector value. If the integer scalar i is less that one or greater than the row dimension of mat, the return value is identical to mat. Otherwise the column dimension of the return value is the maximum of the column dimensions of mat and value and spaces are used to pad the necessary rows on the right. 9.18.b: Example If you enter mat = {"row 1", "row 2", "row 3"} value = "line 2" reprow(mat, 2, value) O-Matrix will respond row 1 line 2 row 3 9.19: Map All Occurrences of a String In a Directory Syntax str2strdir( oldstr, ... newstr, ... olddir, ... newdir, ... logfile,... oldext, ... newext, ... space ... ) See Also fullpath: 6.5.14 , filediff: 20.16 9.19.a: Description This routine creates a new directory in which the files in the directory specified by olddir have a copy in newdir with certain text conversion oldstr newstr The arguments oldstr and newstr are character matrices with the same row dimension which we denote by m. Let s1, s2, ... , sm be the rows in oldstr not including trailing blanks. Let n1, n2, ... , nm be the rows in newstr not including trailing blanks. The text conversions are s1 -> n1 s2 -> n2 ... ... ... sm -> nm Note that replacements are made in the order of the rows; i.e., a match for s2 can include part of n1. olddir is a character row vector specifying the name of the old directory. This directory must exist when str2strdir is called. All of the files and directories in this directory will be copied and converted in the new directory. newdir is a character row vector specifying the name of the new directory. This directory must not exist when str2strdir is called. The parent directory of newdir must exist or else newdir can not be created. logfile is a character row vector specifying the name of the file in which a log of the changes is written. If this file already exists, it is first deleted and then a new log is written. The new and old version of every line that is changed is written in the log file together with the name of the name of the modified file. oldext is a character matrix. Each row of the matrix contains an file extension that should be included in the conversion. All files that have extensions that appear in oldext will be converted. Other files will just be copied from the old to new directory. newext This argument is optional and need not appear in the calling syntax. If it is present, it is a character matrix with the same number of rows as oldext. All files that have extensions that appear in oldext will not only be edited as specified above. In addition, they will also be converted to have the corresponding extension specified by newext. space This argument is optional and need not appear in the calling syntax. If it is present, it is a character scalar specifying a character in newstr that should be output as a space. Because trailing spaces are removed before using each row of newstr, it is not possible to specify trailing spaces using newstr. The space argument can be used for this purpose. 9.19.b: Converting Old O-Matrix Source Code Version 5.1 of O-Matrix uses the file extension *.oms instead of the extension *.mat. In addition, the command matlab ( MATLAB® ) has been changed to mlmode. It is no longer necessary, or suggested, that directories be in include commands. In addition, some functions that were previously *.mat files, have been converted to intrinsic functions. The following example creates a directory called c:\temp\programs in which all of the *.mat, *.oms, and *.omh files in or below the directory c:\omwin\programs have been converted from the old O-Matrix source code conventions to the new conventions: clear oldstr = { ... ".mat", ... Old default extension ".MAT", ... "matlab", ... Old command for Mlmode ... "include function\", ... Old specification of library "include lib\", ... "include toolbox\", ... ... "include ncols.oms", ... Version 5.1 *.oms files "include inv.oms", ... Version 5 *.mat library files "include conj.oms", ... "include imag.oms", ... "include floor.oms", ... "include isfinite.oms", ... "include isinf.oms", ... "include isnan.oms", ... "include up2low.oms", ... "include low2up.oms", ... "include any.oms", ... "include all.oms", ... "include mod.oms", ... "include snormal.oms", ... Older *.mat library files "include cholesky.oms" ... } newstr = { ... ".oms", ... New default extension ".OMS", ... "mlmode", ... New mlmode command ... "include@", ... No longer should specify library "include@", ... "include@", ... ... "# include ncols", ... Version 5.1 intrinsic functions "# include inv", ... Version 5 intrinsic functions "# include conj", ... "# include imag", ... "# include floor", ... "# include isfinite", ... "# include isinf", ... "# include isnan", ... "# include up2low", ... "# include low2up", ... "# include any", ... "# include all", ... "# include mod", ... "# include snormal", ... Now intrinsic functions "# include cholesky" ... } olddir = "c:\omwin\programs" newdir = "c:\temp\programs" logfile = "str2strdir.log" oldext = { ... ".mat", ... ".oms", ... ".omh" ... } newext = { ... ".oms", ... ".oms", ... ".omh" ... } space = "@" # character in newstr that is convert to a space str2strdir( ... oldstr, ... newstr, ... olddir, ... newdir, ... logfile, ... oldext, ... newext, ... space ... ) 9.19.c: Reference The editing commands are done repeatedly on a line until the corresponding row in oldstr cannot be matched. If a row of newstr entirely contains the corresponding row of oldstr, str2strdir will try to make the replacement an infinite number of times. This is why the extension has been dropped from the file specifications in the commented out include commands in the example above. 9.20: Sorting Rows Of A Matrix Syntax sort(matrix) See Also psort: 9.22 , mlsort: 9.24 , reverse: 9.25 sort(matrix, start, width): 9.21 9.20.a: Description Returns a copy of matrix with its rows in ascending order, where matrix is a character, integer, real, or double-precision matrix. The first element that is not equal between two rows determines which row comes first. The argument matrix cannot be an empty matrix: 26.o . 9.20.b: Example The sort function can be used to sort the elements of a column vector. If you enter x = {1, 3, 2} sort(x) O-Matrix will respond The { 1 2 3 } sort function can also be used to sort x = {[2, 1], [1, 2], [1, 1]} sort(x) the rows of a matrix. If you enter O-Matrix will respond { [ 1 , 1 ] [ 1 , 2 ] [ 2 , 1 ] } Note that when two rows have equal first elements, the second element of each row determines which row is greater. If the second elements are equal, the sort function then looks at the third element, and so on. To sort in descending order, use the reverse: 9.25 function. 9.21: Sorting Rows With a Specified Key Syntax sort(matrix, start, width) See Also reverse: 9.25 , sort(matrix): 9.20 , and psort(matrix, start, width): 9.23 9.21.a: Description Returns a copy of matrix with its rows in ascending order, where matrix is a character, integer, real, or double-precision matrix. The order of the rows is determined by the values in the field beginning at column start and width columns wide, where start and width are integer scalars. 9.21.b: Example To sort the matrix / 1 | 2 \ 3 3 \ 4 | 2 / by the second column, enter y = {[1, 3], [2, 4], [3, 2]} sort(y, 2, 1) O-Matrix will respond The { [ 3 , 2 ] [ 1 , 3 ] [ 2 , 4 ] } sort function can also be used with character matrices. x = {"Mary Frye", "Joe Friday", "Jack Frost"} y = align(x, " ", [8, 8]) sort(y, 9, 8) returns Joe Jack Mary Friday Frost Frye 9.22: Sorting The Rows Of A Matrix By Pointers Syntax psort( matrix) See Also sort: 9.20 , pmax: 6.1.4 , reverse: 9.25 , and psort(matrix, start, width): 9.23 9.22.a: Description Returns an integer column vector containing a ranking of the rows of matrix, where matrix is an integer, real, double-precision, or character matrix. The first element of the returned vector contains the row number of the smallest row in matrix, the second element contains the row number of the next largest, and so on. One row of matrix is considered larger than another in the same sense as in sort(matrix): 9.20 . 9.22.b: Example If you enter x = {"Baker", "Alpha", "Charlie"} p = psort(x) print p O-Matrix will respond { 2 1 3 } The 2 is the row number of "Alpha", the 1 is the row number of "Baker", and the 3 is the row number of "Charlie". If you continue the previous example by entering x(p, :) O-Matrix will respond Alpha Baker Charlie 9.23: Specifying Sort Key When Sorting By Pointers Syntax psort( matrix, start, width) See Also psort(matrix): 9.22 9.23.a: Description Returns an integer column vector containing a ranking of the rows of matrix, where matrix is an integer, real, double-precision, or character matrix. The first element of the returned vector contains the row number of the smallest row in matrix, the second element contains the row number of the next largest, and so on. One row of matrix is considered larger than another in the same sense as in sort(matrix, start, width): 9.21 . 9.23.b: Example If you enter x = {"03/28/64", "06/10/52", "08/12/68"} psort(x, 7, 2) O-Matrix will respond { 2 1 3 } which is the order of the rows of x when sorted by year. 9.24: Sorting (Mlmode) Syntax y = sort(x) y = sort(x, d) [y, idx] = sort(x) [y, idx] = sort(x, d) See Also sort: 9.20 , reverse: 9.25 9.24.a: Description Sorts the elements of the matrix x where x is a character, integer, real, or double-precision matrix. (See sort: 9.20 for sorting rows of a matrix.) The return value y has the same type and dimension as x. 9.24.b: Direction of Sort The argument d is an integer, real or double-precision scalar equal to one or two. The value one corresponds to sorting each column and two corresponding to sorting each row. If d is not present and the row dimension of x is not equal to one, the columns of x are sorted (same as d = 1 case). If d is not present and the row dimension of x is equal to one, the row vector x is sorted (same as d = 2 case). 9.24.c: Index of Sort The return value idx in an integer matrix with the same dimension as x. In the d = 1 case, y In i,j the d = 2 y i,j = x idx(i,j) , j case, = x i, idx(i,j) 9.24.d: Example If in Mlmode: 25 you enter x = [ 3 2 1 0 ] [y, idx] = sort(x) y O-Matrix will reply [ 0 1 2 3 ] If you continue by entering idx O-Matrix will reply [ 4 3 2 1 ] 9.25: Reversing Row Order Of A Matrix Syntax reverse( matrix) See Also sort: 9.20 9.25.a: Description Returns a copy of matrix with the rows in reverse order. 9.25.b: Example You can use reverse to sort a vector in descending order. If you enter v = {4, 1, 5} s = sort(v) reverse(s) O-Matrix will respond { 5 4 1 } 9.26: Flipping the Row Order of a Matrix Syntax flipud(matrix) See Also fliplr: 9.27 , sort: 9.20 , reverse: 9.25 9.26.a: Description Returns a copy of matrix with the rows in reverse order. 9.26.b: Example If you enter x = { ... [ 1 , 2 , 3 ] , ... [ 4 , 5 , 6 ] ... } flipud(x) O-Matrix will respond { [ 4 , 5 , 6 ] [ 1 , 2 , 3 ] } 9.26.c: Reference This function has the same specification as reverse: 9.25 but reverse is faster because it is an intrinsic function. 9.27: Flipping the Column Order of a Matrix Syntax fliplr(matrix) See Also flipud: 9.26 , reverse: 9.25 9.27.a: Description Returns a copy of matrix with the columns in reverse order. 9.27.b: Example If you enter x = { ... [ 1 , 2 , 3 ] , ... [ 4 , 5 , 6 ] ... } fliplr(x) O-Matrix will respond { [ 3 , 2 , 1 ] [ 6 , 5 , 4 ] } 9.28: Rotate A Matrix By a Multiple of 90 Degrees Syntax rot90( x, n) See Also flipud: 9.26 , fliplr: 9.27 , transpose: 4.14 9.28.a: Description Rotates the matrix x by n times 90 degrees in the counterclockwise direction where n is a scalar and equal to an integer. The default value for n is one. A single rotation by 90 degrees is the same as reversing the order of the elements in each row and then transposing the matrix; i.e., rot90(x) = x(end : -1 : 1, :)' Values of n greater than zero result in the specified number of rotations by 90 degrees. Values of n less than zero correspond to the inverse mapping for the corresponding absolute value of n. 9.28.b: Example If you enter x = { ... [ 5 , 3 , 1 ], ... [ 6 , 4 , 2 ] ... } rot90(x) O-Matrix will respond { [ 1 , 2 ], ... [ 3 , 4 ], ... [ 5 , 6 ] ... } 9.29: Obtaining the Nonzero Elements of a Matrix Syntax nonzeros(x) See Also find: 9.30 , nnz: 6.6.5 9.29.a: Description Returns a column vector with the same type as x containing the elements of x that are not equal to zero. The order of the elements in the return value is the same as their column major ordering: 26.c in the matrix x 9.29.b: Example If you enter x = [ 1 , 0 , 2 , 0 , 3 ]; nonzeros(x) O-Matrix will respond { 1 2 3 } 9.30: Determining Indices Corresponding to Nonzero Elements Syntax i = find(flag) [i, j] = find(flag) [i, j, nz] = find(flag) See Also find string: 9.31 , nnz: 6.6.5 9.30.a: Description Determines the indices that correspond to elements of flag that are not equal to zero. If flag is a row vector, the return values are row vectors. Otherwise the return values are column vectors. The length of the return values is equal to the number of elements of flag that are not equal to zero. The return values i and j have type integer and the return value nz has the same type as flag. The values i(k), j(k) and nz(k) all correspond to the kth nonzero element of flag in column major order: 26.c . i = find(flag) If only one return value is specified, the indices in i correspond to the column major ordering of the matrix flag. [i, j] = find(flag) If two or three return values are specified, the values in i correspond to the row indices and j correspond to the column indices of the matrix flag. [i, j, nz] = find(flag) If three return values are specified, the values in nz are the elements of flag that are not equal to zero. 9.30.b: Example If you enter find([1, 0, 1]) O-Matrix will reply [ 1 , 3 ] If you enter x = [{0 , 1}, {0, 2}] find(x) O-Matrix will reply { 2 4 } 9.31: Determining Indices Where A Text Pattern Occurs Syntax i = find(text, pattern) [i, j] = find(text, pattern) See Also findstr: 9.35 , find nonzero: 9.30 , find characters: 9.32 , strreplace: 9.8 , string equality: 4.16 and string ordering: 4.17 9.31.a: Description Returns the indices in the character matrix text at which there are occurrences of the pattern specified by the character row vector pattern. If both i and j are present, they are integer column vectors containing the row and column indices in text. Otherwise i is a two column integer matrix with the first column corresponding to row indices and the second to column indices. Trailing blanks in pattern are not ignored and must be matched. 9.31.b: Example If you enter list = {"TEST.FOR", "TEST.MAT", "WRITE.MAT", "WRITE.FOR"} find(list, ".MAT") O-Matrix will respond { [ 2 , 5 ] [ 3 , 6 ] } 9.32: Determining Indices Where A Character Is Between Limits Syntax i = find(text, lower, upper) [i, j] = find(text, lower, upper) See Also strreplace: 9.8 , find text: 9.31 , string equality: 4.16 and string ordering: 4.17 9.32.a: Description Returns the indices in the character matrix text where there are occurrences of the characters that fall between the limits specified by the row vectors lower and upper, which must be of equal length. If both i and j are present, they are integer column vectors containing the row and column indices in text. Otherwise i is a two column integer matrix with the first column corresponding to row indices and the second to column indices. Trailing blanks in lower and upper are not ignored and must be matched. 9.32.b: Example If you enter list = {"TEST.A9", "TEST.B8", "TEST.C7", "TEST.D3"} find(list, "A1", "B5") O-Matrix will respond { [ 1 , 6 ] [ 2 , 6 ] [ 4 , 7 ] } because the sixth column of the first row ("A") and the sixth column of the second row ("B") of list are within the boundaries of the first elements of upper and lower, and the seventh element of the fourth row ("3") is within the boundaries of the second elements of upper and lower. 9.33: Conversion From Decimal to Hexadecimal Syntax dec2hex(dec) dec2hex(dec, n) See Also hex2dec: 9.34 , ntoa: 9.5 , atoi: 9.3 , atod: 9.2 9.33.a: Description Converts the decimal values dec to hexadecimal representation where dec is an integer, real, double-precision or complex matrix. The return value is a character matrix in which the i-th row contains the hexadecimal representation of the i-th element of dec (if dec is a matrix, this refers to column major ordering: 26.c of its elements). If the argument n is present, it is equal to a positive integer and specifies the minimum number of columns in the return value of dec2hex. 9.33.b: Example If you enter dec2hex([ 10, 16.]) O-Matrix will respond 0A 10 9.33.c: Reference Each of the elements of dec must be equal to an integer value and if dec is complex, only its real part is used. 9.34: Conversion From Hexadecimal to Decimal Syntax hex2dec( hex) See Also dec2hex: 9.33 , atoi: 9.3 , atod: 9.2 9.34.a: Description Converts the hexadecimal representation hex to decimal integer where hex is a character matrix. The return value is an integer row vector in which the i-th element contains the decimal representation of the i-th row of hex In hexadecimal representation that valid characters are the decimal digits 0 through 9 and the letters a through f (the letters A through F can also be used). The letters represent the values 10 though 15 in alphabetic order. 9.34.b: Example If you enter hex2dec({ "09", "19", "0a", "1A" }) O-Matrix will respond { 9 27 10 26 } 9.34.c: Reference White space: 26.ar characters are not valid hexadecimal digits. You must use 0 for the value zero. 9.35: Searching Strings and Matrices using Regular Expressions Syntax findstr( x, pattern) [R, C, M] = findstr( x, pattern) See Also lower: 9.12.c , find2: 9.31 , strreplace: 9.8 , ntoa: 9.5 , align: 9.1 9.35.a: Description Finds strings in the character matrix x that match the regular expression pattern. If called with one return value, findstr returns all rows of x that contain at least one match for pattern. If called with three return values, findstr returns the row and column indices in x where matches were found, and the length of each match. The values, R, C and M are integer column vectors with row dimension equal to the number of matches found in x. O-Matrix uses Perl-compatible Regular Expressions: 26.ae for the argument pattern. See http://search.cpan.org/dist/perl/pod/perlre.pod for more details about Perl-compatible regular expressions. 9.35.b: Examples If you enter, findstr({"hip", "hipe", "hills", "hope", "Hippy"}, O-Matrix will respond hip hipe hope Hippy If you continue the example by entering S = {"hip", "hipe", "hills", "hope", "Hippy"} "[hH].p+") [R,C,M]=findstr(S, print [R, C, M] "[hH].p+") O-Matrix will return, { [ [ [ [ } 1 2 4 5 , , , , 1 1 1 1 , , , , 3 3 3 4 ] ] ] ] where R contains the row indices of each match, C contains the column indices of each match, and M contains the length of each match. If you continue by entering the following, for i = 1 to rowdim(R) begin print S.blk( R(i), C(i), 1, M(i) ) end O-Matrix will print each of the matched strings, hip hip hop Hipp 9.36: Matching Rows of A Character Matrix Syntax whichrow(cm, cr) See Also string equality: 4.16 , findstr: 9.35 , strreplace: 9.8 , find2: 9.31 9.36.a: Description Returns the indices of the rows of the character matrix cm that are equal to the character row vector cr The return value is an integer column vector with the same number of rows as cm. If the number of rows is zero, none of the rows of cm are equal to cr. Trailing white space is ignored in this comparison. 9.36.b: Example If you enter cm = {"line 1", "line 2"} cr = "line 2" whichrow(cm, cr) O-Matrix will respond 2 10: Graphics, Plotting, and Data Visualization 10.a: Contents Basic Graphics: 10.1 Axis Labeling And Manipulation: 10.2 Plotting Functions Of Two Variables: 10.3 Special Plots: 10.4 Line Plots Using One Command: 10.5 Using Tecplot with O-Matrix: 10.6 Data Visualizer for O-Matrix: 10.7 10.1: Basic Graphics 10.1.a: Contents gplot: 10.1.1 Drawing Line Plots gplotstyle: 10.1.2 Drawing Line Plots With Specified Style gplotlevels: 10.1.3 Drawing Line Plots Z denoted by Color glevel: 10.1.4 Setting Z Values Corresponding To Color Changes In Plots ginit: 10.1.5 Initializing Graphic gstyle: 10.1.6 Setting The Line Plotting Style gprint: 10.1.7 Printing A Graphic Window gcopy: 10.1.8 Copying A Graphic Window To The Clipboard gsave: 10.1.9 Saving a Graphic to a File gcolor: 10.1.10 Line Color Sequence For The Current Viewport gaddwin: 10.1.11 Creating A New Graphics Window gaddwin1: 10.1.12 Specifying A Graphics Window's Caption gaddwin2: 10.1.13 Specifying A Graphics Window's Geometry gaddwin3: 10.1.14 Specifying A Graphics Window's Call Back Command gaddwin4: 10.1.15 Specifying A Graphics Window's Initial Style gwin: 10.1.16 Using Identifier To Switch Between Graphic Windows glistwin: 10.1.17 Listing Graphic Window Identifiers gaddview: 10.1.18 Creating A New Viewport In The Current Graphic Window setview: 10.1.19 Setting Various Viewport Options gview: 10.1.20 Using Identifier To Switch Between Graphic Viewports gview2: 10.1.21 Using Location To Switch Between Graphic Viewports glistview: 10.1.22 Listing Viewport Identifiers For Current Graphic Window ginitview: 10.1.23 Clearing The Current Viewport gdelview: 10.1.24 Deleting A Viewport gaddborder: 10.1.25 Adding A Border Around The Current Viewport gdelborder: 10.1.26 Removes The Border Around The Current Viewport gborder: 10.1.27 Determining If There Is A Border Around Current Viewport gupdate: 10.1.28 Updating The Current Graphic Window 10.1.1: Drawing Line Plots Syntax gplot( y) gplot( x, y) gplot( x, y, z) See Also gaddview: 10.1.18 , gxyzaxis: 10.2.3 , and gplot(x, y, style): 10.1.2 10.1.1.a: Description Plots a curve for each column of y, where y is an integer, real, or double-precision matrix specifying the y value for each point. The first column correspond to a curve with the next color in the current color sequence: 10.1.10 , the second column corresponds to the following color and so on. If x is not present, i is the x value corresponding to y(i,j). If z is not present, 0 is the z value corresponding to y(i,j). If x is present, it is an integer, real, or double-precision matrix and has same number of rows as y. If x is a column vector, x(i) is the x value corresponding to y(i,j). Otherwise x also has the same number of columns as y and x(i,j) is the x value corresponding to y(i,j). If z is present, it is an integer, real, or double-precision matrix and has same number of rows as y. If z is a column vector, z(i) is the z value corresponding to y(i,j). Otherwise z also has the same number of columns as y and z(i,j) is the z value corresponding to y(i,j). The current line style, width and symbol size are determined by the previous call to the gstyle: 10.1.6 function. 10.1.1.b: Example If you enter ginit x = 0. : .1 : 2 * pi y = [sin(x), cos(x)] gplot(y) O-Matrix will draw with the following plot If you enter ginit x = 0. : .1 : 2 * pi y = [sin(x), cos(x)] gplot(x, y) O-Matrix will draw the following plot If you enter ginit y = 0. : .01 : 2 * pi z = cos(4 * y) x = sin(4 * y) gplot(x, y, z) grotate(30, 0, 70) gxtitle("x") gytitle("y") gztitle("z") O-Matrix will draw the following plot 10.1.2: Drawing Line Plots With Specified Style Syntax gplot( x, y, style) gplot( x, y, z, style) See Also gplot(x, y, z): 10.1.1 , gplot(x, y, z, style, levels): 10.1.3 10.1.2.a: Description Plots each column of y as a curve with the specified style, where style is "solid", "dotted", "dashed", "triangle", "star", "square", "plus", "diamond", "dot", "cross", or "circle". The line width and symbol size are determined by the previous call to the gstyle: 10.1.6 function. The line color and arguments x, y, and z, have the same specifications as in gplot(x, y, z): 10.1.1 . 10.1.2.b: Example If you enter ginit x = 0. : .2 : 2 * pi y = [sin(x), cos(x)] gplot(x, y, "plus") O-Matrix will draw the following plot If you enter ginit y = 0. : .2 : 2 * pi z = cos(4 * y) x = sin(4 * y) gplot(x, y, z, "dotted") grotate(30, 0, 70) gxtitle("x") gytitle("y") gztitle("z") O-Matrix will draw the following plot 10.1.3: Drawing Line Plots Z denoted by Color Syntax gplot( x, y, z, style, "levels") See Also glevel: 10.1.4 , and gplot(x, y, z, style): 10.1.2 10.1.3.a: Description Plots each column of y as a curve that changes color depending on the value of z. The values of z at which the colors change are specified by the previous call to glevel: 10.1.4 . The corresponding color values are specified by the previous call to gcolor: 10.1.10 . The arguments x, y, and z, have the same meaning as in gplot(x, y, z): 10.1.1 . The argument style has the same meaning as in gplot(x, y, z, style): 10.1.2 . 10.1.3.b: Example If you enter ginit y = {-1, 0, 1} x = y z = y levels = {-.5, 0, .5} colors = {"red", "black", "green", "blue"} glevel(levels) gcolor(colors) gplot(x, y, z, "solid", "levels") O-Matrix will generate a plot that changes color at z = -.5, z = 0, and z = .5. (Note that 4 colors are plotted, but there are only 3 color changes.) 10.1.4: Setting Z Values Corresponding To Color Changes In Plots Syntax glevel glevel(levels) See Also gplot: 10.1.3 , and mesh or surface: 10.3.7 10.1.4.a: Description If levels is present, sets the values of z at which curves plotted with the "levels" version of gplot: 10.1.3 , mesh or surface: 10.3.7 change color, where levels is an integer, real, or double-precision column vector that is strictly monotone increasing: 26.y . The first color in the current color sequence: 10.1.10 is used where z is less than or equal to the first element of levels, the second color is used where z is between the first and second elements, and so on. If there are more levels than there are colors in the current color sequence, the sequence will "wrap around" to the first color after using the last color in the sequence. If levels is not present, returns the current plotting levels as a double-precision column vector. 10.1.4.b: Example If you enter ginit y = {-1, 0, 1} x = y z = y levels = {-.5, 0, .5} colors = {"red", "black", "green", "blue"} glevel(levels) gcolor(colors) gplot(x, y, z, "solid", "levels") O-Matrix will generate a plot that changes color at z = -.5, z = 0, and z = .5. (Note that 4 colors are plotted, but there are only 3 color changes.) 10.1.5: Initializing Graphic Syntax ginit See Also ginitview: 10.1.23 , delwin: 19.22 , clear: 3.2 Menu Command Graphics | Initialize Graphics 10.1.5.a: Description Deletes all graphics windows (except "Graphic 0", which it erases) and restores all graphics-related settings to their default values. 10.1.5.b: Example If you enter gplot(seq(3)) gaddwin; gplot(seq(3)) O-Matrix draw two plots, one in the default graphic window, and one in the new window created by the gaddwin function. If you then enter ginit The new window will be deleted and the plot in the default window will be erased. 10.1.6: Setting The Line Plotting Style Syntax gstyle(style) gstyle(style, width) gstyle(style, width, size) See Also gplot: 10.1.1 10.1.6.a: Description Sets the style for plotting lines in the current viewport, where style is equal to one of the following character row vectors: Lines Points Polygons Filled "solid" "dot" "triangle" "filltriangle" "dotted" "star" "square" "fillsquare" "dashed" "plus" "diamond" "filldiamond" "cross" "circle" "fillcircle" The integer scalar width specifies a plotting line width in pixels and must be a positive odd value. This width is used to plot the axes, tick marks and grid lines. In addition, it is used for subsequent lines that are plotted in the viewport. If width is not specified, a value of 1 is used. The integer scalar size specifies the symbol size in 10 times printer point units and must be positive. If size is not specified, a value of 40 is used. 10.1.6.b: Example ginit gstyle("diamond") gplot({1, 2, 3}, {10, 20, 30}) will plot diamonds at the points (1, 10), (2, 20), and (3, 30). If style is specified in the gplot: 10.1.1 command, that style is used for that command only. ginit gstyle("diamond") gplot({1, 2, 3}, {10, 20, 30}, "solid") gplot({1, 2, 3}, {10, 20, 30}) will plot a line segment between (1, 10) and (3, 30), and diamonds at the points (1, 10), (2, 20), and (3, 30). You can plot five diamonds at the default size by entering ginit gstyle("diamond", 1, 40) gplot(seq(5)) You can then surround the diamonds by larger ones with thicker lines by entering gstyle("diamond", 5, 80) gplot(seq(5)) You can then return the axes to their original width by entering gstyle("solid", 1) 10.1.6.c: Style Demonstration The following program demonstrates all of the plotting styles: clear list = { ... "solid", ... "dotted", ... "dashed", ... "dot", ... "star", ... "plus", ... "cross", ... "triangle", ... "square", ... "diamond", ... "circle", ... "filltriangle", ... "fillsquare", ... "filldiamond", ... "fillcircle" ... } N = rowdim(list) gxaxis("linear", 0., 1., 1, 1) gyaxis("linear", 0., 1., 1, 1) gcolor("black") for i = 1 to N begin style = strclip(list.row(i)) x = {.1, .2} y = {i, i} / double(N + 1) gplot(x, y, style) p = gcoord(.3, y(1)) gaddtext(style, p, [0., .5]); end 10.1.7: Printing A Graphic Window Syntax gprint See Also print: 10.1.7.c , gcopy: 10.1.8 , gsave: 10.1.9 , gaddwin: 10.1.11 Menu Command File | Print . . . 10.1.7.a: Description Prints the current graphic window. 10.1.7.b: Example If you enter ginit gplot(seq(5)) gprint O-Matrix will print a copy of the plot in the Graphic 0 window. 10.1.7.c: Mlmode In Mlmode: 25 , this function is called print instead of gprint. If in Mlmode you enter clear x = -10 : +10 plot(x, x.^2) print O-Matrix will print a copy of the plot in the Graphic 0 window. 10.1.8: Copying A Graphic Window To The Clipboard Syntax gcopy See Also gprint: 10.1.7 , copy: 22.4 , gsave: 10.1.9 Menu Command Edit | Copy (when graphics window is active) 10.1.8.a: Description Copies the current graphic window to the system clipboard. 10.1.8.b: Example If you enter ginit gplot(seq(5)) gcopy then open the windows WordPad program and choose Edit | Paste from its menu, a copy of the plot will appear in the WordPad document. 10.1.9: Saving a Graphic to a File Syntax gcopy( file, format) See Also gprint: 10.1.7 , gcopy: 10.1.8 10.1.9.a: Description Saves the current graphic window to a file. The argument file must be a character row vector that is a valid filename. The argument format must be one of the following graphic file formats: "bmp", "gif", "png", "tif", or "jpg". 10.1.9.b: Example If you enter ginit x = seq(10) gplot(x, x^2) gsave("xsquared.png", "png") O-Matrix will create the PNG format image file, xsquared.png in your current working directory. 10.1.10: Line Color Sequence For The Current Viewport Syntax gcolor gcolor(colors) See Also gplot: 10.1.1 , contour: 10.3.1 , glevel: 10.1.4 Menu Command Graphics | Colors . . . 10.1.10.a: Description If the character matrix colors is present, gcolor sets the current color sequence to the specified colors. If colors is not present, gcolor returns the current color sequence. Unless specified by gcolor, O-Matrix uses the following sequence of colors for plotting: "black", "maroon", "green", "olive", "navy", "purple", "teal", "gray", "silver", "red", "lime", "yellow", "blue", "fuschia", and "aqua". That is, the first line plotted with gplot: 10.1.1 will be black, the second will be maroon, and so on. The sequence starts over after an aqua plot. (The color sequence is also used by contour: 10.3.1 and glevel: 10.1.4 .) The color "white" can be added to the color sequence, but it is not part of the default sequence. It is primarily useful for erasing lines from a plot. 10.1.10.b: Example If you enter ginit colors = gcolor print colors O-Matrix will print the default color sequence in the Command window. If you then enter ncolor = rowdim(colors) gxaxis("linear", 0, 20, 4, gxtick("outside") for i = 1 to ncolor begin x = {i, i} y = {0, 1} gplot(x, y) end 5) O-Matrix will display one line of each color, with the index of the color in the sequence equal to the x value in the plot. The gcolor function can be used to define a different sequence of colors. For example, if you enter ginit gcolor({"red", "yellow", "green"}) gplot(1, 4, "triangle") gplot(1, 3, "diamond") gplot(1, 2, "star") gplot(1, 1, "cross") O-Matrix will generate a graph with a red triangle at (1, 4), a yellow diamond at (1, 3), a green star at (1, 2), and a red cross at (1, 1). 10.1.11: Creating A New Graphics Window Syntax gaddwin See Also delwin: 19.22 , gplot: 10.1.1 , and gaddwin(caption): 10.1.12 Menu Command Graphics | Add Window 10.1.11.a: Description Adds a new graphics window and selects it as the current window for plotting. The return value is an integer identifier for the new window. It can be used to reference the window in subsequent calls to the gwin: 10.1.16 function. 10.1.11.b: Default Settings This syntax uses default settings for the arguments caption: 10.1.12 , geometry: 10.1.13 , call back: 10.1.14 , and style: 10.1.15 . The caption is set to "Graphic #" where "#" is replaced by the identifier for the new graphic window. The geometry is chosen by the windowing system. The call back command is set to delwin(caption). The style is set to "normal". 10.1.11.c: Example If you enter clear id = gaddwin gplot(seq(3), seq(3)) O-Matrix will create a window the caption: 26.b "Graphic 1" and plot a line in the new window. If you then enter print id O-Matrix will respond 1 which is the identifier for the new graphic window. 10.1.12: Specifying A Graphics Window's Caption Syntax gaddwin(caption) See Also delwin: 19.22 , gplot: 10.1.1 , and gaddwin(caption, geometry): 10.1.13 Menu Command Graphics | Add Window 10.1.12.a: Description Adds a new graphics window with the specified caption: 26.b and selects it as the current window for plotting. The return value is an integer identifier for the new window. It can be used to reference the window in subsequent calls to the gwin: 10.1.16 function. This syntax uses the default settings: 10.1.11.b for the arguments geometry: 10.1.13 , call back: 10.1.14 , and style: 10.1.15 . 10.1.12.b: Example If you enter clear caption = "Test Plot" id = gaddwin(caption) gplot(seq(3), seq(3)) O-Matrix will create a window caption "Test Plot" and plot a line in the window. If you then enter print id O-Matrix will respond 1 which is the identifier for the new graphic window. 10.1.13: Specifying A Graphics Window's Geometry Syntax gaddwin(caption, geometry) See Also delwin: 19.22 , gplot: 10.1.1 , and gaddwin(caption, geometry, call back): 10.1.14 Menu Command Graphics | Add Window 10.1.13.a: Description Adds a new graphics window with the specified caption: 10.1.12 and geometry: 26.s and selects it as the current window for plotting. The return value is an integer identifier for the new window. It can be used to reference the window in subsequent calls to the gwin: 10.1.16 function. This syntax uses the default settings: 10.1.11.b for the arguments call back: 10.1.14 , and style: 10.1.15 . 10.1.13.b: Example If you enter clear caption = "Test Plot" geometry = [200, 100, 200, 100] id = gaddwin(caption, geometry) gplot(seq(3), seq(3)) O-Matrix will create a square graphic window and plot a line in the window. If you then enter print id O-Matrix will respond 1 which is the identifier for the new graphic window. 10.1.14: Specifying A Graphics Window's Call Back Command Syntax gaddwin(caption, geometry, call back) See Also delwin: 19.22 , gplot: 10.1.1 , and gaddwin(caption, geometry, call back, style): 10.1.15 Menu Command Graphics | Add Window 10.1.14.a: Description Adds a new graphics window with the specified caption: 10.1.12 , geometry: 10.1.13 , call back: 26.a command, and selects it as the current window for plotting. The return value is an integer identifier for the new window. It can be used to reference the window in subsequent calls to the gwin: 10.1.16 function. The call back command is executed when the user attempts to close the window using its caption bar. This syntax uses the default setting: 10.1.11.b for the argument style: 10.1.15 . 10.1.14.b: Example If you enter clear caption = "Test Plot" geometry = [200, 100, 200, 100] callback = "beep" id = gaddwin(caption, geometry, callback) gplot(seq(3), seq(3)) O-Matrix will create a graphic window and plot a line in the window. If you attempt to close the window using its caption bar, O-Matrix will beep. You can delete the window by entering the command delwin(caption) to which O-Matrix will respond T 10.1.15: Specifying A Graphics Window's Initial Style Syntax gaddwin(caption, geometry, call back, style) See Also delwin: 19.22 , gplot: 10.1.1 Menu Command Graphics | Add Window 10.1.15.a: Description Adds a new graphics window with the specified caption: 10.1.12 , geometry: 10.1.13 , call back: 10.1.14 command, style and selects it as the current window for plotting. The character row vector style is either "normal" or "iconic" and specifies the initial style in which the window is displayed. The return value is an integer identifier for the new window. It can be used to reference the window in subsequent calls to the gwin: 10.1.16 function. 10.1.15.b: Example If you enter clear caption = "Test Plot" geometry = [200, 100, 200, 100] callback = "delwin(caption)" style = "iconic" id = gaddwin(caption, geometry, callback, style) gplot(seq(3), seq(3)) O-Matrix will create a graphic window and plot a line in the window but display it as an icon. You can see the plot by restoring the window to normal mode. 10.1.16: Using Identifier To Switch Between Graphic Windows Syntax gwin gwin(identifier) See Also gaddwin: 10.1.11 , glistwin: 10.1.17 , gwin: 10.1.16 10.1.16.a: Description If identifier is not present, returns the integer scalar identifier for the current graphic window. If identifier is present, sets the current graphic window to the one specified by identifier, where identifier is an integer scalar. 10.1.16.b: Example If you enter ginit gaddwin("My Graphic") O-Matrix will respond 1 in the Command window because this is the identifier for the new graphic window. If you then enter gwin O-Matrix will respond 1 because this the identifier for the current graphic window. If you then enter gwin(0) gplot(seq(5)) O-Matrix will draw a plot in the Graphic 0 window (which has the 0 identifier). If you then enter gwin(1) gplot(seq(5)) O-Matrix will draw a plot in the My Graphic window (which has the 1 identifier). If you click on a graphics window with the mouse, O-Matrix will automatically generate the appropriate gwin command for that window. For example, if you continue the example above by clicking on the Graphic 0 window, and then entering gtitle("Viewport Title") the title will be written in the Graphic 0 window. 10.1.17: Listing Graphic Window Identifiers Syntax glistwin See Also gaddwin: 10.1.11 , gwin: 10.1.16 , delwin: 19.22 10.1.17.a: Description Returns an integer column vector containing the graphic window identifiers. Graphic windows are numbered in the order that they are defined and the initial graphic window is number 0. 10.1.17.b: Example If you enter ginit id1 = gaddwin id2 = gaddwin print id1, id2 O-Matrix will respond 1 2 If you then enter sort(glistwin) O-Matrix will respond { 0 1 2 } which are the identifiers for the graphic windows. 10.1.18: Creating A New Viewport In The Current Graphic Window Syntax gaddview(right, up, width, height) See Also gview: 10.1.20 , glistview: 10.1.22 , ginitview: 10.1.23 , gborder: 10.1.27 Menu Command Graphics | Add Viewport . . . 10.1.18.a: Description Creates a plotting viewport of the size specified by width and height at the position specified by right and up, where right, up, width, and height are real or double-precision scalars. The function also returns a scalar integer that is the identifier of the new viewport. The position (right, up) and the size (width, height) are in relative coordinates: 26.af within the current plotting window. 10.1.18.b: Example The initial viewport is the entire "Graphic 0" window. The values right and up specify the location of the lower-left corner of the viewport as a fraction of the entire window (relative to the lower-left corner of the window). The values width and height specify the size of the viewport as a fraction of the entire window. To plot the line y = x in the upper-right quadrant of the window, enter ginit x = 0. : .1 : 1. upright = gaddview(.5, .5, .5, .5); gplot(x, x) You could continue the example above to include a plot of the parabola y = x^2 in the lower-left quadrant of the display by entering lowleft = gaddview(0., 0., .5, .5) gplot(x, x^2) The resulting plot would look like this: To add another viewport to the upper-left quadrant of the window, you could enter upleft = gaddview(0., .5, .5, .5) If you then enter print upright, lowleft, upleft O-Matrix will reply 1 2 3 which are the corresponding viewport identifiers. 10.1.19: Setting Various Viewport Options Syntax setview( option, flag) See Also gaddview: 10.1.18 10.1.19.a: Description Sets various display options for the current viewport: 26 . The character row vector option specifies the option to be set and the logical scalar flag specifies if the option is to be turned on or off. (A true value turns the option on.) The valid values for option are: option description "box" draws a box with tick marks around the plotting region in the x-y plane "border" draws a border around the viewport "xaxis" draws the x-axis "yaxis" draws the y-axis "zaxis" draws the z-axis All of the options except "box" can also be set in other graphics functions. 10.1.19.b: Example If you enter gplot(seq(5)) O-Matrix will plot the line y = x from 1 to 5. If you continue by entering setview("box", true) O-Matrix will include a box with tick marks around the plot. If you continue by entering setview("xaxis", false) O-Matrix will erase the x-axis and the part of the box that was in the x-axis direction. 10.1.20: Using Identifier To Switch Between Graphic Viewports Syntax gview gview(identifier) See Also gaddview: 10.1.18 glistview: 10.1.22 gwin: 10.1.16 , and gview(right, up): 10.1.21 Menu Command Graphics | Viewport | Select/Clear/Delete . . . | (Select) 10.1.20.a: Description If identifier is not present, returns the integer scalar identifier for the current viewport. If identifier is present, sets the current viewport to the one specified by identifier, where identifier is an integer scalar. In this case, the function returns the right, up, width, and height, which were used to create the viewport as a four-column real row vector. 10.1.20.b: Example If you enter ginit lower = gaddview(0., 0., 1., .5) print "lower =", lower O-Matrix will respond lower = 1 in the Command window because this is the identifier for the new viewport. If you then enter gview O-Matrix will respond 1 because the new viewport is the current viewport. If you then enter upper = gaddview(0., .5, 1., .5) gplot(seq(5)) O-Matrix will draw a plot in the upper half of the Graphic 0 window. If you then enter gview(lower) O-Matrix will respond [ 0 , 0 , 1., 0.5 ] because these are the right, up, width, and height, which were used to create the lower viewport. If you then enter gplot(seq(3)) O-Matrix will generate a plot in the lower viewport (because the last call to the gview function made it the current viewport). 10.1.21: Using Location To Switch Between Graphic Viewports Syntax gview(right, up) See Also gview: 10.1.20 , gaddview: 10.1.18 , glistview: 10.1.22 , gwin: 10.1.16 Menu Command Graphics | Viewport | Select/Clear/Delete . . . | (Select) 10.1.21.a: Description Sets the current viewport to the smallest one that contains the relative coordinates: 26.af (right, up) with in the current graphics window. The return value is the right, up, width, and height, which were used to create the viewport, as a four-column real row vector. 10.1.21.b: Example The following program titles each of two viewports and then waits for you select one using the mouse. When you use the mouse button to select one of the viewports, the program generates a plot in the viewport that you selected. clear begin text = {"Use the mouse", "to select a viewport"} id = gaddtext(text, [.5, 1.], [.5, 1.]) gaddview(.25, 0., .5, .4); gaddborder gtitle("Viewport 1") gaddview(.25, .4, .5, .4); gaddborder gtitle("Viewport 2") gupdate ru = gcoord gview(ru(1), ru(2)) gplot(seq(5)) end 10.1.22: Listing Viewport Identifiers For Current Graphic Window Syntax glistview See Also gaddview: 10.1.18 , gview: 10.1.20 , gdelview: 10.1.24 10.1.22.a: Description Returns an integer column vector containing the viewport identifiers for each of the viewports in the current graphic window. Viewports are numbered in the order that they are defined and the initial viewport, number 0, is the entire plotting window. 10.1.22.b: Example If you enter ginit id1 = gaddview(0., 0., 1., .5) id2 = gaddview(0., .5, 1., .5) print id1, id2 O-Matrix will respond 1 2 If you then enter list = sort(glistview) for i = 1 to rowdim(list) begin id = list(i) print id, gview(id) end O-Matrix will respond 0 [ 0 , 0 , 1 , 1 ] 1 [ 0 , 0 , 1 , 0.5 ] 2 [ 0 , 0.5 , 1 , 0.5 ] which is the identifier for each of the viewports followed by the arguments that were used to define the viewport. 10.1.23: Clearing The Current Viewport Syntax ginitview See Also delwin: 19.22 , ginit: 10.1.5 , clear: 3.2 Menu Command Graphics | Viewport | Select/Clear/Delete . . . | (Clear) 10.1.23.a: Description Clears the current viewport. 10.1.23.b: Example If you enter gaddview(0., 0., 1., .5) gplot(seq(3)) gaddview(0., .5, 1., .5) gplot(seq(3)) O-Matrix will draw two plots in the current graphic window. If you continue by entering ginitview The second plot will be erased. 10.1.24: Deleting A Viewport Syntax gdelview(identifier) See Also gaddview: 10.1.18 , ginitview: 10.1.23 , glistview: 10.1.22 , gview: 10.1.20 10.1.24.a: Description Deletes the viewport specified by identifier, where identifier is an integer scalar. The identifier for a viewport is returned when it is created by gaddview: 10.1.18 , the identifier for the current viewport can be obtained using gview: 10.1.20 , and a list of all the viewport identifiers for the current graphic window can be obtained using glistview: 10.1.22 . 10.1.24.b: Example If you enter ginit x = -1. : .1 : 1. line = gaddview(0., 0., 1., .5) gplot(x, x) parabola = gaddview(0., .5, 1., .5) gplot(x, x^2) O-Matrix will draw a line and a parabola. You can erase the line by entering gdelview(parabola) 10.1.25: Adding A Border Around The Current Viewport Syntax gaddborder See Also gborder: 10.1.27 , gdelborder: 10.1.26 , gaddview: 10.1.18 Menu Command Graphics | Viewport | Border | On 10.1.25.a: Description Draws a border around the current viewport. 10.1.25.b: Example If you enter ginit gaddview(.25, .25, .5, .5); gaddborder O-Matrix will draw a rectangle that is half the size of the Graphic 0 window in the center of the Graphic 0 window. 10.1.26: Removes The Border Around The Current Viewport Syntax gdelborder See Also gaddborder: 10.1.25 , gaddview: 10.1.18 Menu Command Graphics | Viewport | Border | Off 10.1.26.a: Description Deletes the border around the current viewport 10.1.26.b: Example If you enter ginit gaddview(.25, .25, .5, .5); gaddborder O-Matrix will draw a rectangle that is half the size of the Graphic 0 window in the center of the Graphic 0 window. If you then enter gdelborder O-Matrix will remove the border 10.1.27: Determining If There Is A Border Around Current Viewport Syntax gborder See Also gaddborder: 10.1.25 , gdelborder: 10.1.26 , gaddview: 10.1.18 10.1.27.a: Description Returns true, if the current viewport has a border and false if it does not. 10.1.27.b: Example If you enter id = gaddview(.25, .25, .5, .5) gaddborder gborder O-Matrix will respond T 10.1.28: Updating The Current Graphic Window Syntax gupdate See Also gplot: 10.1.1 10.1.28.a: Description Redraws the current graphics window. While processing a sequence of commands (such as those in a "begin/end" block), O-Matrix does not normally update the current graphics window. Adding gupdate to a sequence of commands causes O-Matrix to redraw the current graphics window in the middle of the sequence. (The current graphics window is automatically redrawn before another graphic window becomes current.) 10.1.28.b: Example If you enter clear for i = 1 to 5 begin gplot(seq(2) + i) gupdate sleep(1) end O-Matrix will plot five lines, with one second of delay between each line, in the Graphic 0 window. 10.2: Axis Labeling And Manipulation 10.2.a: Contents gtitle: 10.2.1 Defining A Title For Current Viewport gxyztitle: 10.2.2 Defining A Title For An Axis In The Current Viewport gxyzaxis: 10.2.3 Setting Axis Parameters gxyzaxis3: 10.2.4 Setting Axis Minimum and Maximum gxyzaxis4: 10.2.5 Setting Major Intervals On An Axis gxyzaxis5: 10.2.6 Setting Minor Intervals On An Axis axiscale: 10.2.7 Autoscaling Multiple Plots To Same Axis Limits g2scale: 10.2.8 Two Scalings For Both X and Y Axis gtickform: 10.2.9 Specifying Numeric Format For Tick Mark Labels gtickloc: 10.2.10 Specifying Tick Mark Locations gticklabel: 10.2.11 Specifying Nonnumeric Tick Mark Labels gxygrid: 10.2.12 Including A Grid In A Plot gintercept: 10.2.13 Setting The Axis Intercept Point For A Viewport gcoord: 10.2.14 Using The Mouse To Specify A Graphic Window Location gcoord2: 10.2.15 Converting Plotting Coordinates To A Graphic Window Location gaddtext: 10.2.16 Placing Text In The Current Graphic Window glisttext: 10.2.17 Listing Text In The Current Graphics Window gdeltext: 10.2.18 Removing Text From The Current Graphics Window gfont: 10.2.19 Setting Graphics Text Font Type Face gfont2: 10.2.20 Setting Graphics Text Font Size gfont3: 10.2.21 Setting Graphics Text Font Color gfont4: 10.2.22 Setting Graphics Text Font Styles gfontname: 10.2.23 Determining Available Font Names gspace: 10.2.24 Adjusting The Space Around The Plotting Region gaspect: 10.2.25 Setting Plotting Window Aspect Ratio 10.2.1: Defining A Title For Current Viewport Syntax gtitle(title) See Also title: 10.2.1.c , gxyztitle: 10.2.2 , gfont: 10.2.19 , gaddtext: 10.2.16 Menu Command Graphics | Viewport | Title . . . 10.2.1.a: Description Displays title at the top of the current viewport, where title is a character row vector. 10.2.1.b: Example If you enter ginit theta = 0. : .1 : 2 * pi gplot(theta, sin(theta)) gtitle("sin(theta)") O-Matrix will put a title at the top of a plot of the sine function. 10.2.1.c: Mlmode In Mlmode: 25 this function is called title instead of gtitle. If in Mlmode you enter, omginit; theta = 0. : .1 : 2 * pi; plot(theta, sin(theta)); title('sin(theta)'); O-Matrix will put a title at the top of a plot of the sine function. 10.2.2: Defining A Title For An Axis In The Current Viewport Syntax gxtitle(title) gytitle(title) gztitle(title) See Also xlabel ylabel zlabel: 10.2.2.c , gtitle: 10.2.1 , gfont: 10.2.19 , gaddtext: 10.2.16 Menu Command Graphics | Axis | Title . . . 10.2.2.a: Description Displays title below the specified axis in the current viewport, where title is a character row vector. 10.2.2.b: Example If you enter ginit theta = 0. : .1 : 2 * pi gplot(theta, sin(theta)) gxtitle("theta") gytitle("sin(theta)") O-Matrix will put the corresponding titles on the x and y axis. Note that if there is not enough room for the titles, they will not be seen in the graphics window. You can increase the room for the titles, using the gspace: 10.2.24 function as follows: left = .3 right = .02 below = .2 above = .02 gspace(left, right, below, above) 10.2.2.c: Mlmode In Mlmode: 25 these functions are called xlabel, ylabel and zlabel instead of gxtitle, gytitle and gztitle respectively. If in Mlmode you enter, omginit; theta = 0. : .1 : 2 * pi; plot(theta, sin(theta)); title('sin(theta)'); xlabel('theta'); ylabel('sin(theta)'); omgspace(.3, .02, .2, .02); O-Matrix will put the corresponding titles on the x and y axis. 10.2.3: Setting Axis Parameters Syntax gxaxis(type) gyaxis(type) gzaxis(type) See Also gintercept: 10.2.13 , axiscale: 10.2.7 , g2scale: 10.2.8 , and gxaxis(type, min, max): 10.2.4 Menu Command Graphics | Axis | Scale . . . 10.2.3.a: Description Sets the axis to logarithmic or linear, and determines whether the axis is displayed. The value type is "log", "linear", "offlog", or "offlin". 10.2.3.b: Example If you enter ginit gplot(seq(4)) O-Matrix will draw a plot. If you then enter gxaxis("offlin") the x-axis will be removed. 10.2.4: Setting Axis Minimum and Maximum Syntax gxaxis(type, gyaxis(type, gzaxis(type, min, max) min, max) min, max) gxaxis(type): 10.2.3 and gxaxis(type, min, max, major): 10.2.5 See Also Menu Command Graphics | Axis | Scale . . . 10.2.4.a: Description Sets the minimum and maximum values on the axis, where min and max are integer, real, or double-precision numbers. (type functions are described in the gxaxis(type): 10.2.3 ) 10.2.4.b: Example If you enter ginit gplot(seq(4)) O-Matrix will draw a plot. If you then enter gyaxis("linear", 0, 5) the resulting y-axis will be linear and ranging from 0 to 5 10.2.5: Setting Major Intervals On An Axis Syntax gxaxis(type, gyaxis(type, gzaxis(type, min, max, major) min, max, major) min, max, major) See Also gxaxis(type, min, max): 10.2.4 and gxaxis(type, min, max, major, minor): 10.2.6 Menu Command Graphics | Axis | Scale . . . 10.2.5.a: Description Divides the axis into the number of labeled intervals specified by major, where major is an integer scalar. (The value type functions are described in the gxaxis(type): 10.2.3 . The values min and max function are described in the gxaxis(type, min, max): 10.2.3 .) 10.2.5.b: Example If you enter ginit gplot(seq(4)) O-Matrix will draw a plot. If you then enter gyaxis("linear", 0, 5, 5) the resulting y-axis will linear and ranging from 0 to 5 with 5 major intervals. 10.2.6: Setting Minor Intervals On An Axis Syntax gxaxis(type, gyaxis(type, gzaxis(type, min, max, major, minor) min, max, major, minor) min, max, major, minor) See Also gxgrid: 10.2.12 , and gxaxis(type, min, max, major): 10.2.5 Menu Command Graphics | Axis | Scale . . . 10.2.6.a: Description Divides the axis into the number of labeled intervals specified by major, where major is an integer scalar. Each major interval is divided into the number of sub-intervals specified by minor, where minor is an integer scalar. (The value type functions are described in the gxaxis(type): 10.2.3 . The values min and max function are described in the gxaxis(type, min, max): 10.2.3 .) 10.2.6.b: Example Entering ginit gxaxis("linear", 0, 5, 5, 10) gyaxis("linear", 0, 25, 5, 5) gplot(seq(5), seq(5)^2) will result in the following plot 10.2.7: Autoscaling Multiple Plots To Same Axis Limits Syntax axiscale(data) See Also gxaxis(type): 10.2.3 10.2.7.a: Description Determine good linear axis scaling parameters for data that is in one or more plots. The integer, real, or double-precision matrix data contains all of data that needs to be included in the plotting limits. The return value is a double-precision column vector. Its first element is the minimum value for the axis. Its second element is the maximum value. Its third element is number of major divisions and the fourth is the number of minor divisions. 10.2.7.b: Example The following program plots both the exponential function and a sine wave in separate viewports with the same y-axis scaling. clear x y1 y2 scale # = = = = 0. : .01 : 1. sin(2 * pi * x) exp(x) axiscale([y1, y2]) gaddview(0., 0., gyaxis("linear", gplot(x, y1) # gaddview(.5, 0., gyaxis("linear", gplot(x, y2) .5, 1.); scale(1), scale(2), int(scale(3)), int(scale(4))) .5, 1.); scale(1), scale(2), int(scale(3)), int(scale(4))) 10.2.8: Two Scalings For Both X and Y Axis Syntax g2scale(x1, y1, style1, x2, y2, style2) See gxaxis: 10.2.3 , gaddview: 10.1.18 , gaddwin: 10.1.11 , Tecplot GUI (http://www.omatrix.com/manual/pltgui.htm) , SigmaPlot link Also (http://www.omatrix.com/splink.html) , 10.2.8.a: Description Plots multiple curves with two different scalings in the same region of a plotting window. The current viewport: 26.aq when g2scale is called is referred to as the initial viewport, and the curves corresponding to x1 and y1 are plotted in this viewport. The current viewport when g2scale returns is the final viewport, and the curves corresponding to x2 and y2 are plotted in this viewport. The initial and final viewports share the visible plotting region. Settings in the initial viewport, such as axis titles and scaling, should be made before the call to g2scale; settings of the final viewport should be made after the call. The matrix x1 specifies the x coordinates, y1 specifies the y coordinates, and style1 specifies the style for the curves using the initial scaling. The values x1 and y1 are integer, real, or double-precision matrices and have the same dimensions. The character matrix style1 has the same row dimension as the column dimension of x1. The j-th curve with the initial scaling corresponds to the j-th column of x1, the j-th column of y1, and the j-th row of style1. The matrix x2 specifies the x coordinates, y2 specifies the y coordinates, and style2 specifies the style for the curves using the final scaling. The values x2 and y2 are integer, real, or double-precision matrices and have the same dimensions. The character matrix style2 has the same row dimension as the column dimension of x2. The j-th curve with the final scaling corresponds to the j-th column of x2, the j-th column of y2, and the j-th row of style2. The arguments style1 and style2 have the same meaning as the first argument to the gstyle: 10.1.6 function. Any gintercept: 10.2.13 settings for the initial viewport are overridden by g2scale. 10.2.8.b: Example x1 = 0:.1:10. x2 = x1 / 2 y1 = x1^2 y2 = x2^3 gaddview(.25, .25, .5, .5) gxtitle("x1 solid") gytitle("y1 solid") g2scale(x1, y1, "solid", x2, y2, "dashed") gxtitle("x2 dashed") gytitle("y2 dashed") returns the following plot: 10.2.9: Specifying Numeric Format For Tick Mark Labels Syntax gxtick(form) gytick(form) gztick(form) See Also gxaxis: 10.2.3 , gxtickfont: 10.2.19 , gxtick(location): 10.2.10 , and gxtick(label): 10.2.11 10.2.9.a: Description Sets the numeric format for the tick marks labels on the appropriate axis, where form is a character row vector specifying a floating point format: 8.17.3 . This function affects only the tick mark labels in the current viewport. 10.2.9.b: Example If you enter ginit gplot(seq(10)) the tick marks are labeled using the free format. If you continue by entering gxtick("f10.1") the x-axis tick mark labels will use a fixed point format with one place after the decimal point. If you continue by entering gspace(.2, .1, .1, .1) gytick("e10.1") the y-axis tick mark labels will use an exponential format with one place after the decimal point (the gspace: 10.2.24 function was used to provide more room for the larger labels). 10.2.10: Specifying Tick Mark Locations Syntax gxtick(location) gytick(location) gztick(location) See Also gxaxis: 10.2.3 , gxtick(form): 10.2.9 , and gxtick(label): 10.2.11 10.2.10.a: Description Sets the location of the tick marks (for the axis specified in the function name) relative to the plotting region of the viewport. The character row vector location is "inside", "outside", or "across": "inside" places the tick marks inside the plotting region; "outside" places the marks outside the region; and "across" places the marks across the axis (i.e., both inside and outside the region). 10.2.10.b: Example If you enter ginit gplot(seq(10)) the tick marks are inside the plotting region. If you continue by entering gxtick("outside") the x-axis tick marks will be outside the plotting region. If you continue by entering gytick("across") the y-axis tick marks will be across the y axis. 10.2.11: Specifying Nonnumeric Tick Mark Labels Syntax gxtick(labels) gytick(labels) gztick(labels) See Also gxaxis: 10.2.3 , gxtick(form): 10.2.9 , and gxtick(location): 10.2.10 10.2.11.a: Description Specifies the labels to be used for each of the major tick marks on the appropriate axis, where labels is a character matrix of two or more rows. The ith major tick mark, starting with the one corresponding to the smallest value, is labeled with the contents of the i-th row of label. There is always one more major tick mark than there are major divisions on a given axis. 10.2.11.b: Example If you enter ginit gxaxis("linear", 1, 4, 3, 5) gplot(seq(4)) O-Matrix will draw a plot with the normal numeric labels. If you continue by entering gxtick({"one", "two", "three", "four"}) O-Matrix will change the x-axis labels for the first, second, third, and fourth tick marks to one, two, three, and four, respectively. 10.2.12: Including A Grid In A Plot Syntax gxgrid(grid gygrid(grid type) type) gxaxis(type, min, max, major, minor): 10.2.6 , See Also Menu Command Graphics | Axis | Grid . . . 10.2.12.a: Description Controls the drawing of grid lines. If grid type is "major", grid lines are drawn at each major tick mark. If grid type is "minor", grid lines are drawn at each major and minor tick mark. (see major: 10.2.5 and minor: 10.2.6 to control the corresponding interval sizes). If grid type is "off", no grid lines are drawn (this is the default setting). 10.2.12.b: Example If you enter ginit x = 0. : .1 : 10 y = 5. - abs(x - 5.) gplot(x, y) gxaxis("linear", 0, 10, 5, 2) gyaxis("linear", 0, 10, 5, 2) gxgrid("minor") gygrid("major") O-Matrix will draw a plot with 1 unit between the x grid line and 2 units between the y grid lines. 10.2.13: Setting The Axis Intercept Point For A Viewport Syntax gintercept(x-intercept, gintercept(x-intercept, y-intercept) y-intercept, z-intercept) See Also gxyzaxis: 10.2.3 Menu Command Graphics | Intercepts 10.2.13.a: Description Sets the point at which the x-axis, y-axis, and z-axis, intersect, where x-intercept, y-intercept, and z-intercept, are integer, real, or double-precision scalars or character row vectors. (If the z-intercept is not specified, it is 0 by default.) If the argument is a character row vector it must be either "min", "center", or "max". 10.2.13.b: Numeric Example If you enter ginit x = seq(11) - 6 gplot(x, 5 - x^2) O-Matrix will plot a parabola. You can set the x-axis along the top of the parabola by entering gintercept(0, 5) 10.2.13.c: Character Example If you enter ginit x = seq(11) - 6 gplot(x, 5 - x^2) gintercept("center", "max") O-Matrix will plot a parabola with the axis intercept point in the middle of the x-axis and at the top of the y-axis. 10.2.14: Using The Mouse To Specify A Graphic Window Location Syntax gcoord See Also gcoord(x, y): 10.2.15 and gaddwin: 10.1.11 10.2.14.a: Description Suspends O-Matrix execution until the button of the pointing device is pressed in the currently active graphic window. When the button is pressed, the relative coordinates: 26.af within the window of the pointing device is returned. 10.2.14.b: Example You can use this function to place text at a certain location within a graphic window. If you enter begin x = gcoord gaddtext("here", x) end Note that the status bar of the O-Matrix application contains the words "Mouse Input". O-Matrix will put the word "here" on the first spot you select in the currently active graphic window. 10.2.15: Converting Plotting Coordinates To A Graphic Window Location Syntax gcoord(x, y) See Also gcoord: 10.2.14 , gaddwin: 10.1.11 10.2.15.a: Description Returns the relative coordinates: 26.af within the current graphic window that corresponds to the (x,y) plotting locations in the current viewport: 26.aq , where x and y are integer, real, or double-precision column vectors of equal length. The return value is a two column real matrix with the same number of rows as x and y. The i-th row of the return value corresponds to the plotting location (x(i), y(i)). 10.2.15.b: Example You can use this function to place text at a certain location within a graphic plot. If you enter clear gplot(seq(3), seq(3)) x = 2 y = 2 p = gcoord(x, y) gaddtext("(2,2)", p) O-Matrix will label the point (2,2) with its Cartesian coordinates. 10.2.16: Placing Text In The Current Graphic Window Syntax gaddtext(text, window coordinates) gaddtext(text, window coordinates, text coordinates) gaddtext(text, window coordinates, text coordinates, direction) See Also gfont: 10.2.19 , gdeltext: 10.2.18 , gcoord: 10.2.14 10.2.16.a: Description Places the specified text at the specified location within the current graphic window, where text is a character matrix and the integer, real, or doubleprecision two element row vector window coordinates specifies a point using relative coordinates: 26.af within the window. If present, text coordinates specifies the point in the text that corresponds to the specified location in the window. It is an integer, real, or doubleprecision two element row vector specifying the relative coordinates within the text. If text coordinates is not present, the center of the text is used. If direction is not present, the text is placed on a horizontal baseline. If direction is present, it specifies the direction of the baseline for the text. It is a two element integer, real, or double-precision row vector with each of its elements between -1 and +1. The first element is a change in horizontal location and the second element is a change in vertical location that corresponds to the direction. The direction [1,1] corresponds to a line from the lower left corner of the window to the upper right, [1,0] corresponds to a line from the left side of the window to the right (horizontal), [0,1] corresponds to a line from the bottom of the window to the top (vertical), [-1,0] corresponds to a line from the right side of the window to the left (upside-down). The return value of gaddtext is an integer scalar which can be used in conjunction with the gdeltext: 10.2.18 function to delete a specific piece of text. 10.2.16.b: Examples 10.2.16.b.a: Two Arguments To place the center of the phrase Center Of Window in the center of the current graphic window, you would enter clear text = "Center Of Window" window_coord = [.5, .5] id = gaddtext(text, window_coord) O-Matrix would then respond with the following graph: 10.2.16.b.b: Three Arguments To place the upper right corner of the phrase Upper-right corner at the upper right corner of the current graphic window, you would enter clear text = {"Upper-right", "corner"} window_coord = [1., 1.] text_coord = [1., 1.] id = gaddtext(text, window_coord, text_coord) 10.2.16.b.c: Four Arguments To place the center of the phrase Diagonal text in the center of the current graphic window and along a baseline from the lower left to upper right of the current graphic window, you would enter clear text window_coord text_coord direction id = = = = = "Diagonal text" [.5, .5] [.5, .5] [1., 1.] gaddtext(text, window_coord, text_coord, direction) 10.2.17: Listing Text In The Current Graphics Window Syntax glisttext See Also gaddtext: 10.2.16 , gdeltext: 10.2.18 10.2.17.a: Description Returns a character matrix with each row corresponding to a text entry in the current graphic window. The first five columns contain the identification number of the text; the next five columns contain the "right" coordinate of the text; the third five columns contain the "up" coordinate of the text; and the first row of the text itself starts in the sixteenth column of the return value. A comma is added at the end of each row of text and the return matrix is padded with blank spaces so that all of its rows have the same length. 10.2.17.b: Example If you enter ginit gaddtext("One", [.5, .3]) O-Matrix will place the text "One" in the Graphic 0 window and echo the value 1 in the Command window. The value 1 is the identifier the text that was added. If you then enter gaddtext("Two", [.5, .6]) O-Matrix will place the text "Two" in the Graphic 0 window and echo the value 2 in the Command window. If you continue by entering glisttext O-Matrix will reply 1 0.50 0.30 One, 2 0.50 0.60 Two, 10.2.18: Removing Text From The Current Graphics Window Syntax gdeltext(identifier) See Also gaddtext: 10.2.16 , glisttext: 10.2.17 10.2.18.a: Description Deletes the text specified by identifier from the current graphic window, where identifier is integer identifier for the text. (The glisttext: 10.2.17 command can be used to list the identifiers for the text in the current graphic window.) 10.2.18.b: Example If you enter ginit gaddtext("One", [.5, .3]) O-Matrix will place the text "One" in the Graphic 0 window and echo the value 1 in the Command window. The value 1 is the identifier the text that was added. If you then enter gaddtext("Two", [.5, .6]) O-Matrix will place the text "Two" in the Graphic 0 window and echo the value 2 in the Command window. If you continue by entering gdeltext(1) O-Matrix will remove the "One" from the Graphic 0 window. 10.2.19: Setting Graphics Text Font Type Face Syntax functionfont(type face) See Also gaddtext: 10.2.16 , gxtitle: 10.2.2 , and gxtick(form): 10.2.9 10.2.19.a: Description Sets the font for subsequent calls to the specified function, where function is one of the following: gaddtext, gtitle, gxtitle, gytitle, gztitle, gxtick, gytick, or gztick. The argument type face is a character row vector specifying the name of the font (the available font names can be determined using gfontname: 10.2.23 ). If a graphic font is not specified using functionfont , the default font name is "Courier New". The size can be set using gtitlefont(type face, size): 10.2.20 and its default value is 12. The color can be set using gtitlefont(type face, size, color): 10.2.21 and its default value is "black". The special styles "bold", "italic", "underline", and "overstrike" can be turned on using gtitlefont(type face, size, color, styles): 10.2.22 and the default is for them to be turned off. 10.2.19.b: Example If you enter ginit gaddtextfont("symbol") gaddtext("abg", [.5, .5]) gtitle("abg") O-Matrix will place the Greek letters alpha, beta, and gamma in the center of the Graphic 0 window because they correspond to the call to gaddtext. On the other hand, the title at the top of the window will be "abg" because the font for the gtitle function was not changed. 10.2.20: Setting Graphics Text Font Size Syntax functionfont(type face, size) See Also gtitlefont(type face): 10.2.19 and gtitlefont(type face, size, color): 10.2.21 10.2.20.a: Description Sets the font for subsequent calls to the specified function, where function is one of the following: gaddtext, gtitle, gxtitle, gytitle, gztitle, gxtick, gytick, or gztick. The integer scalar size specifies the height of the font in points, the argument type face is described in gtitlefont(type face): 10.2.19 . This call uses the default color which is "black" and the special styles "bold", "italic", "underline", and "overstrike" are turned off. 10.2.20.b: Example If you enter ginit gtitlefont("symbol", 16) gtitle("abg") O-Matrix will place a large title in the Graphic 0 window consisting of the Greek letters alpha, beta, and gamma. 10.2.21: Setting Graphics Text Font Color Syntax functionfont(type face, size, color) See Also gtitlefont(type face, size): 10.2.20 and gtitlefont(type face, size, color, styles): 10.2.22 10.2.21.a: Description Sets the font for subsequent calls to the specified function, where function is one of the following: gaddtext, gtitle, gxtitle, gytitle, gztitle, gxtick, gytick, or gztick. The color of the font is specified by the character row vector color (see gcolor: 10.1.10 for a list of the valid colors). The argument type face is described in gtitlefont(type face): 10.2.19 , and the argument size is described in gtitlefont(type face, size): 10.2.20 . The special styles "bold", "italic", "underline", and "overstrike" are turned off. 10.2.21.b: Example If you enter ginit typeface = "symbol" size = 16 color = "red" gaddtextfont(typeface, size, color) gaddtext("abg", [.5, .5]) O-Matrix will place a large red version the Greek letters alpha, beta, and gamma in the center of the Graphic 0 window. 10.2.22: Setting Graphics Text Font Styles Syntax functionfont(type face, size, color, style, ...) See Also gtitlefont(type face, size, color): 10.2.21 10.2.22.a: Description Sets the font for subsequent calls to the specified function, where function is one of the following: gaddtext, gtitle, gxtitle, gytitle, gztitle, gxtick, gytick, or gztick. Any number of the special styles "bold", "italic", "underline", and "overstrike" can be specified by the style, ...) part of the syntax. The argument type face is described in gtitlefont(type face): 10.2.19 , the argument size is described in gtitlefont(type face, size): 10.2.20 , and the argument color is described in gtitlefont(type face, size, color): 10.2.21 . 10.2.22.b: Example If you enter ginit typeface = "symbol" size = 16 color = "red" gaddtextfont(typeface, size, color, "underline", "italic") gaddtext("abg", [.5, .5]) O-Matrix will place a large red underlined italic version the Greek letters alpha, beta, and gamma in the center of the Graphic 0 window. 10.2.23: Determining Available Font Names Syntax gfontname( device) See Also gfont: 10.2.19 10.2.23.a: Description Returns a character matrix in which each row contains the name of an available font on the specified device, where device is the character row vector "screen" or "printer". 10.2.23.b: Example If you enter gfontname("screen") O-Matrix will print a list of font names available in the graphic windows. 10.2.24: Adjusting The Space Around The Plotting Region Syntax gspace gspace(left, right, below, above) See Also gaddview: 10.1.18 , gxyztitle: 10.2.2 10.2.24.a: Description If no arguments are present, returns a real four-element row vector containing the values of left, right, below, and above that correspond to the current spacing for the current viewport. If the arguments are present, sets the amount of space, within the current viewport, that is excluded from the plotting region. This space is used for tick marks, tick mark labels, axis labels and the viewport title. Depending on the size of a viewport and the font used for labeling, it may be necessary to use this function to adjust the space allocated for labeling within a viewport. The arguments left, right, below, and above are integer, real, or double-precision scalars. They specify the space that is reserved (to the left, to the right, below, and above the plotting region) as a fraction of the viewport size. All of the arguments must be between 0 and 1. The width of the plotting region is equal to (1 - right - left) times the width of the viewport. The height of the plotting region is (1 - above - below) times the height of the viewport. If the plotting window has an aspect ratio of 1, and if the width of the viewport is equal to its height, and if right + left is equal to above + below, the plotting region will have an aspect ratio of 1. 10.2.24.b: Example If you enter ginit gspace(.1, .01, .1, .01) gplot(seq(2)) O-Matrix will draw a plot that has more labeling space to the left and below than it has to the right and above. 10.2.25: Setting Plotting Window Aspect Ratio Syntax gaspect(ratio) See Also gaddview: 10.1.18 , gspace: 10.2.24 10.2.25.a: Description Sets the proportion of height over width (the aspect ratio) for the current window, where ratio is an integer, real, or double-precision scalar. The largest possible rectangle, with in the graphic window and with the specified aspect ratio, is used for all relative coordinates: 26.af with in the window (for example, the relative coordinates used by the gaddview: 10.1.18 function). A ratio greater than 1 sets the rectangle to be taller than it is wide, and a ratio of less than 1 sets the rectangle to be wider than it is tall. A ratio of 1 yields a rectangle with equal width and height. Setting the aspect ratio to 0 allows the rectangle to expand to the size of the full window. 10.2.25.b: Example If you enter clear gaspect(1) x = 0. : .1 : 2 * pi gplot(x, [sin(x), cos(x)]) O-Matrix will generate a square plot no matter what the shape of the plotting window. 10.3: Plotting Functions Of Two Variables 10.3.a: Contents contour: 10.3.1 Contour Plots contour2: 10.3.2 Specifying Contour Levels contour4: 10.3.3 Specifying X And Y Values In A Contour Plot contour5: 10.3.4 Specifying Plane For A Contour Plot contour6: 10.3.5 Hiding Lines Behind A Contour Plot mesh: 10.3.6 Mesh And Surface Plots mesh2: 10.3.7 Specifying Line Color In Mesh And Surface Plots mesh4: 10.3.8 Specifying X and Y Values In Mesh And Surface Plots mesh5: 10.3.9 Specifying Plotting Style In Mesh And Surface Plots grotate: 10.3.10 Rotating Plotting Axis 10.3.1: Contour Plots Syntax contour( matrix) See Also mlmode_contour: 25.8.8 , surface, mesh: 10.3.6 , and contour(matrix, levels): 10.3.2 10.3.1.a: Description Displays a contour plot of matrix in the current viewport: 26.aq , where matrix has at least two rows and two columns and is integer, real, or doubleprecision. This syntax for contour uses the default settings for the arguments levels: 10.3.2 , x: 10.3.3 , y: 10.3.3 , z: 10.3.4 , and option: 10.3.5 . The number of contour levels is equal to the number of colors in the current color sequence as returned by gcolor: 10.1.10 and the levels are evenly spaced between the minimum and maximum value in matrix. The x-axis corresponds to the row index of matrix, and the y-axis corresponds to the column index of matrix. The contour plane corresponds to z = 0, and the contour does not hide lines behind it. 10.3.1.b: Example You can use contour to plot z = x y, where both x and y range from 1 to 8, by entering x = seq(8) y = x' matrix = x * y format int "3" write("screen", matrix) O-Matrix will respond 1 2 3 4 5 6 7 8 2 4 6 8 10 12 14 16 3 6 9 12 15 18 21 24 4 8 12 16 20 24 28 32 5 10 15 20 25 30 35 40 6 12 18 24 30 36 42 48 The first line above corresponds 7 14 21 28 35 42 49 56 to x = 8 16 24 32 40 48 56 64 1 and the last line corresponds to x = 8. If you continue the previous example by entering contour(matrix) O-Matrix will generate the following plot. 10.3.2: Specifying Contour Levels Syntax contour( matrix, levels) See Also mesh, surface: 10.3.6 , and contour(matrix, levels, x, y): 10.3.3 10.3.2.a: Description Displays the contour plot specified by matrix: 10.3.1 and levels in the current viewport: 26.aq , where levels contains the values for each contour line and is an integer, real, or double-precision column vector. The line corresponding to the i-th element of levels is drawn using the i-th color in the current color sequence as returned by gcolor: 10.1.10 and the length of levels must be less than or equal to the number of colors. 10.3.2.b: Example If you enter ginit x = seq(8) y = x' matrix = x * y levels = {10, 20, 30} contour(matrix, levels) O-Matrix will generate the following plot: 10.3.3: Specifying X And Y Values In A Contour Plot Syntax contour( matrix, levels, x, y) See Also mesh, surface: 10.3.6 , and contour(matrix, levels, x, y, z): 10.3.4 10.3.3.a: Description Displays the contour plot specified by matrix: 10.3.1 , levels: 10.3.2 , x and y in the current viewport: 26.aq . The integer, real, or double-precision column vector x has the same number of rows as matrix and the i-th element of x specifies the x-axis value corresponding to the i-th row of matrix. The integer, real, or double-precision row vector y has the same number of columns as matrix and the j-th element of y specifies the y-axis value corresponding to the j-th column of matrix. 10.3.3.b: Example If you enter ginit x = seq(11) - 6 y = x' matrix = x * y levels = {-20, -10, -5, 0, 5, 10, 20} contour(matrix, levels, x, y) O-Matrix will generate the following plot: 10.3.4: Specifying Plane For A Contour Plot Syntax contour( matrix, levels, x, y, z) See Also mesh, surface: 10.3.6 , and contour(matrix, levels, x, y, z, option): 10.3.5 10.3.4.a: Description Displays the contour plot specified by matrix: 10.3.1 , levels: 10.3.2 , x: 10.3.3 , y: 10.3.3 , and z in the current viewport: 26.aq . The integer, real, or double-precision scalar z specifies the z-axis value for the x-y plane in which the contour is drawn. 10.3.4.b: Example If you enter ginit x = seq(11) - 6 y = x' matrix = x * y levels = {-20, -10, -5, 0, 5, 10, 20} z = .5 contour(matrix, levels, x, y, z) grotate(30, 0, 50) gzaxis("linear", 0., 1.) O-Matrix will generate the following plot: 10.3.5: Hiding Lines Behind A Contour Plot Syntax contour( matrix, levels, x, y, z, option) See Also mesh and surface: 10.3.6 10.3.5.a: Description Displays the contour plot specified by matrix: 10.3.1 , levels: 10.3.2 , x: 10.3.3 , y: 10.3.3 , z: 10.3.3 , and option in the current viewport: 26.aq , where option is equal to "surface" and specifies that lines behind the contour are hidden from view. 10.3.5.b: Example If you enter ginit x = seq(11) - 6 y = x' matrix = x * y levels = {-20, -10, -5, 0, 5, 10, 20} z = .5 option = "surface" contour(matrix, levels, x, y, z, option) grotate(30, 0, 50) gzaxis("linear", 0., 1.) O-Matrix will generate the following plot: 10.3.6: Mesh And Surface Plots Syntax mesh( z) surface( z) See Also contour: 10.3.1 , gplot: 10.1.1 , and mesh(z, color option): 10.3.7 10.3.6.a: Description Displays a mesh or surface plot of z in the current viewport: 26.aq , where z has at least two rows and two columns and is integer, real, or doubleprecision. A surface plot differs from a mesh plot in that hidden lines are removed (and it requires more time to generate a plot). The syntax for mesh and surface uses the default settings for line color: 10.3.7 , x, y: 10.3.8 axis values and plotting style: 10.3.9 . The default line color for the plot is black. The default x-axis and y-axis values corresponding to z(i,j) are i and j respectively. The default plotting style is solid lines and the line width is determined by the previous call to the gstyle: 10.1.6 function. 10.3.6.b: Example The following program compares a mesh and surface plot of the function z(x, y) = x y / 10 clear x = -5. : 1. : 5. y = x' z = x * y / 10. # gtitle("mesh") gxtitle("x") gytitle("y") gztitle("z") mesh(z) # gaddwin gtitle("surface") gxtitle("x") gytitle("y") gztitle("z") surface(z) 10.3.7: Specifying Line Color In Mesh And Surface Plots Syntax mesh( z, surface( z, color option) color option) See Also glevel: 10.1.4 , gcolor: 10.1.10 , mesh(z): 10.3.6 and mesh(z, color option, x, y): 10.3.8 10.3.7.a: Description Displays the mesh or surface plot specified by z: 10.3.6 and color option, in the current viewport: 26.aq , where color option is one of the colors listed in gcolor: 10.1.10 or it is equal to "levels". If it is a color, the lines in the resulting plot have the specified color. If it is "levels", the lines in the resulting plot change color in the manner specified by the glevel: 10.1.4 function. 10.3.7.b: Example If you enter ginit x = -5. : 1. : 5. y = x' z = x * y / 10. glevel({-1.2, -.6, .6, 1.2}) gcolor({"red", "green", "black", "lime", "blue"}) gxtitle("x") gytitle("y") gztitle("z") surface(z, "levels") O-Matrix will generate a surface plot with red where z < -1.2, green .6 < z < 1.2, and blue where 1.2 < z . where -1.2 < z < -.6, black where -.6 < z < .6, lime where 10.3.8: Specifying X and Y Values In Mesh And Surface Plots Syntax mesh( z, surface( z, color option, x, y) color option, x, y) See Also gxyzaxis: 10.2.3 , mesh(z, color option): 10.3.7 and mesh(z, color option, x, y, style): 10.3.9 10.3.8.a: Description Displays the mesh or surface plot specified by z: 10.3.6 , color option: 10.3.7 , x, and y, in the current viewport: 26.aq . The integer, real, or doubleprecision column vector x has the same number of rows as z and x(i) is the x-axis value corresponding to the i-th row of z. The integer, real, or double-precision row vector y has the same number of columns as z and y(j) is the y-axis value corresponding to the j-th column of z. 10.3.8.b: Example If you enter ginit x = -5. : 1. : 5. y = x' z = x * y / 10. glevel({-1.2, -.6, .6, 1.2}) gcolor({"red", "green", "black", "lime", "blue"}) gxtitle("x") gytitle("y") gztitle("z") mesh(z, "levels", x, y) O-Matrix will generate the following plot 10.3.9: Specifying Plotting Style In Mesh And Surface Plots Syntax mesh( z, surface( z, color option, x, y, style) color option, x, y, style) See Also gstyle: 10.1.6 , and mesh(z, color option, x, y): 10.3.8 10.3.9.a: Description Displays the mesh or surface plot specified by z: 10.3.6 , color option: 10.3.7 , x, y: 10.3.8 and style, in the current viewport: 26.aq , where style is a character row vector specifying a valid plotting style as described in gstyle: 10.1.6 . The line width and symbol size are determined by the previous call to the gstyle: 10.1.6 function. 10.3.9.b: Example If you enter ginit x = -5. : 1. : 5. y = x' z = x * y / 10. glevel({-1.2, -.6, .6, 1.2}) gcolor({"red", "green", "black", "lime", "blue"}) gxtitle("x") gytitle("y") gztitle("z") gstyle("solid", 1, 20) surface(z, "blue", x, y, "star") O-Matrix will plot the star symbol at the points (x , y , z ) for i = 1 , ... , m and j = 1 , ... n i j i,j where m and n are the row and column dimensions of z respectively. The stars that are behind the surface will be hidden because this is a surface plot instead of a mesh plot. The argument 20 to gstyle: 10.1.6 determines the size of the star symbols and the other arguments have no effect in this plot. 10.3.10: Rotating Plotting Axis Syntax grotate( z, y, x) See Also mesh: 10.3.6 10.3.10.a: Description Rotates the z, y, and x plotting axis by the specified number of degrees, where x, y, and z are integer, real, or double-precision scalars. Before the rotation, the positive x direction is to the right, the positive y direction is up, and the positive z direction comes out of the screen. (The direction of rotation is clockwise when looking down the corresponding axis from its positive side.) 10.3.10.b: Example If you enter ginit v = seq(3) gplot(v, v, v) grotate(30, 0, 70) gxtitle("x") gytitle("y") gztitle("z") The first rotation is 30 degrees about the positive z direction. This leaves the positive z direction fixed, makes the positive x direction down and to the right, and makes the positive y direction up and to the right. The second rotation of 0 degrees about the positive y direction has no effect. The third rotation of 70 degrees about the positive x direction (which is now down and to the right) leaves the positive z direction up and out of the screen, the positive y direction to the right, up, and into the screen, and the positive x direction as it was, down and to the right in the plane of the screen. 10.4: Special Plots 10.4.a: Contents errorbar: 10.4.1 Plotting Error Bars garrow: 10.4.2 Plotting Vectors ghist: 10.4.3 Plotting Histograms gbar: 10.4.4 Plotting A Bar Graph With Different Width Bars bar: 10.4.5 Plotting A Bar Graph With Uniform Width Bars gstair: 10.4.6 Plotting A Stair Graph polar: 10.4.7 Plotting In Polar Coordinates smith: 10.4.8 Plotting a Smith Chart fcplot: 10.4.9 Plotting The Response Of A Continuous Filter fdplot: 10.4.10 Plotting The Response Of A Digital Filter 10.4.1: Plotting Error Bars Syntax errorbar(x, y, w, h) See Also gplot: 10.1.1 , gbar: 10.4.4 , ghist: 10.4.3 10.4.1.a: Description Plots error bars (with width w and height h) in the y direction for the curve defined by (x, y), where x and y are each integer, real, or double-precision column vectors, and w and h are each integer, real, or double-precision scalars or column vectors. The vectors x and y must have the same dimension. If w is not a scalar, it must have the same dimension as x. If h is not a scalar, it must have the same dimension as x. 10.4.1.b: Example x = seq(4) y = seq(4) w = .2 h = .4 errorbar(x, y, w, h) returns the following plot: 10.4.2: Plotting Vectors Syntax garrow(arrow) See Also contour: 10.3.1 , mesh and surface: 10.3.6 10.4.2.a: Description Plots a sequence of arrows in the current viewport: 26.aq , where arrow is an integer, real, or double-precision matrix. Each row of arrow corresponds to an arrow in the plot. The first element of a row specifies the x coordinate of the starting point of the arrow, the second element specifies the y coordinate of the starting point, the third element specifies the angle of the arrow in radians, and the fourth element specifies the length of the arrow. Both the angle and length are in (x,y) coordinates; that is, an angle of pi/4 and a length of sqrt(2) correspond to an x difference of 1 and a y difference of 1. The angle on the screen depends on the window size and graphing limits. Each arrow is plotted using as a separate call to gplot: 10.1.1 , and thus the colors progress through the color sequence which can be modified using the gcolor: 10.1.10 function. 10.4.2.b: Example x = {1., 2.} y = {1., 2.} angle = {pi/6., pi/3} length = {.2, .2} arrow = [x, y, angle, length] garrow(arrow) returns the following plot 10.4.3: Plotting Histograms Syntax ghist( y) ghist( y, nb) ghist( y, nb, color) ghist( y, nb, color, cindex) See Also gstair: 10.4.6 , gbar: 10.4.4 10.4.3.a: Description Plots a histogram with optional specification of the number of bins, the color, and grouping of elements by color. The histogram is scaled so that the height of each bin corresponds to the sample density for that bin. The size of the bins are adjusted to have the same number of samples in each bin with the exception that bins in the center may have one less sample than bins at the ends. If all of the entries in a bin have the same value, the entries are plotted as one cross for each entry above the value. The real or double-precision column vector y contains the data values that are being plotted. If the argument nb is present, the row dimension of y must be greater than or equal to nb. Otherwise, the row dimension of y must be greater than or equal to ten. If integer scalar nb is present, it specifies the number of bins in the histogram. Otherwise there are ten bins in the histogram. If the character matrix color is present, it specifies the plotting colors for the histogram. Each row of color must contain a valid O-Matrix plotting color; i.e., "black", "maroon", "green", "olive", "navy", "purple", "teal", "gray", "silver", "red", "lime", "yellow", "blue", "fuschia", or "aqua". If the integer column vector cindex is present, it specifies which elements of y correspond to which colors in the histogram. The element y(i) corresponds to the color color.row(cindex(i)). Each element of cindex must have a value between one and the row dimension of color. 10.4.3.b: Example If you enter y = rand(499, 1) nb = 20 ghist(y, nb) O-Matrix will plot a histogram of 499 samples that are uniformly distributed between zero and one. The following program plots a similar histogram in which the even indices correspond to "green" and the odd indices correspond to "red". clear # y = nb = color = even = odd = cindex = ghist(y, rand(499, 1) 20 {"red", "green"} mod(seq(499), 2) == 0 not even odd % fill(1, 499, 1) + even % fill(2, 499, 1) nb, color, cindex) 10.4.4: Plotting A Bar Graph With Different Width Bars Syntax gbar(y) gbar(y, x) See Also bar: 10.4.5 , ghist: 10.4.3 , gstair: 10.4.6 10.4.4.a: Description Plots a bar graph, where the integer, real, or double-precision column vector y specifies the height of the graph over each interval, and the column vector x specifies the interval limits and has one more row than y. 10.4.4.b: Width and Position of Bars The vector x must be strictly monotone increasing: 26.y and have one more element than the vector y. If m is the length of y, the value y(i) is plotted over the interval [x(i), x(i+1)] for i equal 1 to m. Thus the difference between the successive elements of x specifies the width of the bars. If x is not present, the value x(i) = i is used by default. 10.4.4.c: Example gtitle("Bar Plot of x^2") y = seq(10)^2 gbar(y) returns the following plot: 10.4.5: Plotting A Bar Graph With Uniform Width Bars Syntax bar(y) bar(x, y) See Also gbar: 10.4.4 , ghist: 10.4.3 , gstair: 10.4.6 10.4.5.a: Description Plots a bar graph, where the integer, real, or double-precision vector y specifies the height of each of the bars and the vector x specifies the horizontal location of each of the bars. If m is the length of both the vectors y and x, a bar of height y(i) is plotted centered over the horizontal location x(i) for i equal 1 to m. If x is not present, the value y(i) is plotted over the horizontal location i. The vector x must be strictly monotone: 26.y increasing or decreasing. 10.4.5.b: Example clear gtitle("Bar Plot of x^2") x = seq(5) y = x^2 bar(x, y) returns the following plot: 10.4.6: Plotting A Stair Graph Syntax gstair(y) gstair(y, x) See Also gbar: 10.4.4 , ghist: 10.4.3 10.4.6.a: Description Plots a stair graph, where the integer, real, or double-precision column vector y specifies the height of the graph over each interval, and the column vector x specifies the interval limits and has one more row than y. If r is the row dimension of y, the value y(i) is plotted over the interval [x(i), x(i+1)] for i equal 1 to r. If x is not present, the value y(i) is plotted over the interval [i-.5, i+.5]. The vector x should be monotone increasing; that is, x(i) < x(i+1) for all i. 10.4.6.b: Example gtitle("Stair Plot of x^2") y = seq(10)^2 gstair(y) returns the following plot: 10.4.7: Plotting In Polar Coordinates Syntax polar( r, theta, rmax, rmajor, tmajor, style, color) See Also smith: 10.4.8 , atan2: 6.2.15 , log: 6.2.7 , smith: 10.4.8 10.4.7.a: Description Draws a polar coordinate plot of radius versus angle in viewport number 0 of the current graphics window. The initial contents of the viewport are erased, and it is the current viewport when the plot is completed. The integer, real, or double-precision matrix r specifies the radius value for each point. The integer, real, or double-precision matrix theta specifies the angle in degrees for each point and has the same dimensions as r. The j-th column of r and theta is plotted as a separate curve with its own color. The integer, real, or double-precision scalar rmax specifies the maximum radius value for the plot. If rmajor is an integer scalar, it specifies the number of major divisions in the radius direction. In this case, the current format: 8.17.1 for the matrices with the same type as rmax is used to label the radius values. For example, if rmax is real and the current format for real is "f10.3", the radius labels will be in fixed point notation with three places behind the decimal point. If rmajor is a character matrix, the number of rows in rmajor specifies the number of major divisions in the radius direction and the value of each row specifies the label for the corresponding radius value. To be specific, the i-th row corresponds to a radius value of i rmax / nr where nr is the row dimension of rmajor. The last label in rmajor is not currently used but may be used in future versions of polar. If tmajor is an integer scalar, it specifies the number of major divisions in the radius direction. In this case, the current format: 8.17.1 for the matrices with the same type as theta is used to label the angle values. For example, if theta is real and the current format for real is "f10.3", the angle labels will be in fixed point notation with three places behind the decimal point. If tmajor is a character matrix, the number of rows in tmajor specifies the number of major divisions in the angle direction and the value of each row specifies the label for the corresponding angle value. To be specific, the i-th row corresponds to an angle value of (i-1) 360 / nr where nr is the row dimension of rmajor. The character row vector style specifies the style for plotting the curve and is one of the following: "solid", "dotted", "dashed", "triangle", "star", "square", "plus", "diamond", "dot", or "cross". The character matrix color specifies the color for plotting each of the curves. It must have the same number of rows as r and theta have columns. The color in the i-th row of color is used to plot the i-th column of r and theta. Each row of color must be one of the following: "black", "maroon", "green", "olive", "navy", "purple", "teal", "gray", "silver", "red", "lime", "yellow", "blue", "fuschia" or "aqua". The aspect ratio for the current graphic window is set to 1. If you change this, your polar plot will not be square. 10.4.7.b: Example r = 1. : 1. : 100. Theta = 360. * [r, -r] / 100. R = [r, r] rmax = 100 rmajor = 4 tmajor = 12 style = "solid" color = {"red", "blue"} polar(R, Theta, rmax, rmajor, tmajor, style, color) returns the following plot: 10.4.8: Plotting a Smith Chart Syntax smith( gamma, color) See Also polar: 10.4.7 10.4.8.a: Description A smith chart contains solid lines denoting constant real and imaginary part for the impedance (z) with labels corresponding to the value that is constant. Dashed lines are drawn denoting constant real and imaginary part for the admittance (y). These lines have the same values as the corresponding impedance lines but are not labeled. The lines are drawn in Gamma space where Gamma = (z - 1) / (z + 1) Gamma = (1 - y) / (1 + y) Gamma < 1. In addition, the unit circle and not labeled. is drawn and tick marks are included with a spacing of 10 degrees around the circle. These tick marks are The values specified by the complex matrix gamma are included in the plot. The character matrix color has row dimension equal to the column dimension of gamma and specifies the color used to plot each of the columns of gamma. Row number j of color corresponds to the column number j of gamma and each row of color must be a valid O-Matrix plotting color: 10.1.10 and If n is the row dimension of gamma. The elements of each column are plotted with a symbol that depends on their index within the column as follows: Last Index Symbol First Index 1 ... n / 5 triangle n/5+1 ... (2 * n) / 5 star (2 * n) / 5 + 1 ... (3 * n) / 5 plus (3 * n) / 5 + 1 ... (4 * n) / 5 diamond (4 * n) / 5 + 1 ... (5 * n) / 5 cross 10.4.8.b: Example theta = 0. : .2 : 2 * pi r = theta / (2 * pi) gamma = r % exp(1i0 * theta) color = "red" smith(gamma, color) returns the following plot 10.4.8.c: Reference The initial contents of viewport: 26.aq zero, in the current graphic window, are erased and it is the current viewport when the plot is completed. The current graphic text font is rest to its default value. The aspect: 10.2.25 ratio for the current graphic window is set to 1. If you change this your smith chart will not be "square". 10.4.9: Plotting The Response Of A Continuous Filter Syntax fcplot(xmin, xmax, ymin, ymax, cutoff, num, den) See Also fdplot: 10.4.10 10.4.9.a: Description Plots the response of a continuous filter in the current viewport, where xmin is an integer, real, or double-precision scalar specifying the minimum value on the x-axis; xmax is an integer, real, or double-precision scalar specifying the maximum value on the x-axis; ymin is an integer, real, or doubleprecision scalar specifying the minimum value on the y-axis; ymax is an integer, real, or double-precision scalar specifying the maximum value on the y-axis; cutoff is an integer, real, or double-precision row vector denoting the cutoff frequencies; num is an integer, real, or double-precision column vector specifying the numerator polynomial: 26.ac for the filter; and den is an integer, real, or double-precision column vector specifying the denominator polynomial for the filter. The x- and y-axis are log-scaled, and xmin, xmax, ymin, and ymax must be powers of 10 (e.g., 1, 10, 100). The response function plotted is | __ |2 | num[ \/-1 w ] | -----------------| __ |2 | den[ \/-1 w ] | where w is between xmin and xmax. 10.4.9.b: Example The following program plots a normalized 2 pole Butterworth filter. clear # num = 1. den = {1., sqrt(2.), 1.} ymin = 1e-3 ymax = 1e2 xmin = 1e-1 xmax = 1e1 cutoff = 1. fcplot(xmin, xmax, ymin, ymax, cutoff, num, den) 10.4.10: Plotting The Response Of A Digital Filter Syntax fdplot(dt, ymin, ymax, cutoff, num, den) See Also fdplot: 10.4.10 10.4.10.a: Description Plots the response of a digital filter in the current viewport, where dt is an integer, real, or double-precision scalar specifying the time between sample points; ymin is an integer, real, or double-precision scalar specifying the minimum value on the y-axis; ymax is an integer, real, or double-precision scalar specifying the maximum value on the y-axis; cutoff is an integer, real, or double-precision row vector denoting the cutoff frequencies; num is an integer, real, or double-precision column vector specifying the numerator polynomial: 26.ac for the filter; and den is an integer, real, or doubleprecision column vector specifying the denominator polynomial for the filter. The y-axis is log-scaled, and the scaling of the x-axis is based on its current settings. Both ymin and ymax must be powers of 10 (e.g., 1, 10, 100). The response function plotted is | __ |2 | num[ exp( \/-1 dt w ) ] | ---------------------------| __ |2 | den[ exp( \/-1 dt w ) ] | where w is between pi / (100 dt) and pi / dt. 10.4.10.b: Example The example below does not plot any cutoff frequencies because the row vector cutoff has zero column dimension. clear # dt = 1. ymin = 1e-4 ymax = 1e2 cutoff = fill(0, 1, 0) num = {1, 2, 1} den = 1 fdplot(dt, ymin, ymax, cutoff, num, den) 10.5: Line Plots Using One Command Syntax plotcmd(y) plotcmd(x, y) plotcmd(x, y, s) plotcmd(x1, y1, s1, x2, y2, s2, ... ) Where plotcmd is plot, loglog, semilogx, or semilogy See Also gplot: 10.1.1 , axis: 10.2.3 , gstyle: 10.1.6 10.5.a: Description Clears the current graphics viewport: 10.1.23 and then plots one or more x-y curves in the viewport with the following scaling: plotcmd x scaling y scaling plot linear linear loglog log log semilogx log linear semilogy linear log If you enter x = seq(4) - 1 y = 10^x plot(x, y, "x") O-Matrix will draw crosses at the points (0, 1), (1, 10), (2, 100), and (3, 1000), using linear scaling for both the x and y axis. If you continue by entering semilogy(x, y, "x") O-Matrix will draw crosses at the same points but with the x-axis linear scaled and the y-axis log scaled. 10.5.b: x and y Argument Types The arguments x, and y can be integer, real or double-precision matrices. In the one argument syntax, the argument y can be complex. 10.5.c: Plotcmd(y) If y is complex, this is equivalent to the syntax plotcmd(double( y), imag(y)) If you enter theta = 0. : .1 : (2 * pi + .1) y = 1r0 * cos(theta) + 1i0 * sin(theta) plot(y) O-Matrix will plot a circle. If y is integer, real, or double-precision vector of length m, this plots one curve corresponding to the x-y values (i, y(i)), i = 1 , ... , m If you enter y = (seq(11) - 6)^2 plot(y) O-Matrix will plot a parabola. If y is not complex or a vector, for each j between 1 and the column dimension of y this plots a curve corresponding to the x-y values (i, y(i, j)), i = 1 , ... , m where m is the row dimension of y If you enter y = [ seq(10), 2 * seq(10)] plot(y) O-Matrix will plot the lines y = x and y = 2 * x. 10.5.d: Plotcmd(x, y) with x a Vector If m is the length of vector x, either the row or column dimension of y must also be m. If m is the row dimension of y, for each j between 1 and the column dimension of y this plots a curve corresponding to the x-y values (x(i), y(i, j)), i = 1 , ... , m If you enter x = 0. : .1 : (2 * pi + .1) y = [sin(x), cos(x)] plot(x, y) O-Matrix will plot one cycle of the sine and cosine functions. If m is the column dimension of y, for each i between 1 and the row dimension of y this plots a curve corresponding to the x-y values (x(j), y(i, j)), j = 1 , ... , m If you continue the example above by entering of the following lines: plot(x, y) plot(x', y) plot(x, y') plot(x', y') O-Matrix will redraw the same plot. 10.5.e: Plotcmd(x, y) with y a Vector If m is the length of the vector y, either the row or column dimension of x must also be m. If m is the row dimension of x, for each j between 1 and the column dimension of x this plots a curve corresponding to the x-y values (x(i, j), y(i)), i = 1 , ... , m If m is the column dimension of x, for each i between 1 and the row dimension of x this plots a curve corresponding to the x-y values (x(i, j), y(j)), j = 1 , ... , m 10.5.f: Plotcmd(x, y) Neither a Vector If neither x or y is a vector, their dimensions must be equal. In this case, for each j between 1 and the column dimension of x this plots a curve corresponding to the x-y values (x(i, j), y(i, j)), i = 1 , ... , m where m is the column dimension of x. If you enter theta = 0. : .1 : 2 * pi + .05 x = [cos(theta) - 1, cos(theta), cos(theta) + 1] y = [sin(theta) - 1, sin(theta), sin(theta) + 1] plot(x, y) O-Matrix will plot three circles with centers at (1, 1), (0, 0) and (-1, -1). 10.5.g: Plotcmd(x, y, s) The argument s is a character row vector specifying the style with which each of the curves is plotted. It may contain one of the following color codes code Meaning y yellow m magenta c cyan r red g green b blue w white k black If you enter x = seq(5) y = x s = "g" plot(x, y, s) O-Matrix will draw a green line. If a color is not specified for a plot, a color is chosen from the list above with black coming first and the color white omitted. The argument s may contain one of the following symbol codes code . o x + * s d Meaning dot circle cross plus star square diamond ^ triangle If a symbol code is present, the corresponding symbol is plotted at each x-y pair. If you enter x = seq(5) y = x s = "g+" plot(x, y, s) O-Matrix will plot green plus signs at the points (i,i) for i = 1, 2, 3, 4, 5. The argument s may contain one of the following line styles code Meaning solid : dotted -- dashed If a line type is present, the x-y pairs are connected by the specified type of line. If you enter x = seq(5) y = x s = "r+-" plot(x, y, s) O-Matrix will plot red plus signs at the points (i,i) for i = 1, 2, 3, 4, 5 and a red line connecting the points. 10.5.h: Plotcmd(x1, y1, s1, x2, y2, s2, ... ) The line plots specified by plotcmd(x1, y1, s1), plotcmd(x2, y2, s2), ... , are all included in the current plotting window. If you enter x = seq(5) y = x plot(x, y, "", x, y + 1, "g", x, y + 2, "") O-Matrix will plot a black line, then a green line above the black line, and then a blue line above the green line. (Note black is the default for the first color and the color blue comes after green in the list of colors above.) 10.6: Using Tecplot with O-Matrix 10.6.a: Description The following functions enable O-Matrix to transfer data and results to and from Tecplot (http://www.tecplot.com) . O-Matrix can create, read, and manipulate Tecplot data. Functions are provided to create Tecplot graphs of O-Matrix 10.6.b: Installation Use of these functions require that a current version of Tecplot Focus or Tecplot 360 and O-Matrix be installed on your system. After Tecplot and OMatrix have been installed copy the file omlink.dll from the tecplot directory of your O-Matrix installation, (e.g. C:\OMWIN\TECPLOT) to the bin directory of your Tecplot installation. Add the following line to the tecplot.add file in your Tecplot home directory.!Loadaddon "omlink"
10.6.c: Plotting Functions
tpplot: 10.6.16
Creating XY Plots
tpsurface: 10.6.23 Creating Surface Plots
tpcontour: 10.6.3 Creating Contour Plots
tpcolors: 10.6.2
Line Color Sequence for XY Plots
tphist: 10.6.10
Creating Histograms
tpsymbols: 10.6.24 Setting Symbol Style for XY Plots
tpxyzaxes: 10.6.27 Setting X, Y and Z Axes Minimum, Maximum, and Type
10.6.d: Data and Tecplot Manipulation Functions
tpopen: 10.6.15
Opening Tecplot Data, Layout and Style Files
tpget: 10.6.8
Transferring Data from Tecplot to O-Matrix
tpput: 10.6.19
Transferring Data from O-Matrix to Tecplot
tpmacrostring: 10.6.12 Running a Tecplot Macro String
tpplottype: 10.6.17
Setting and Retrieving Current Frame Plot Type
tpframe: 10.6.7
Popping, Creating and Obtaining Frame Names
Adding a Zone to an Existing Dataset
tpdataset: 10.6.4
Creating Tecplot Data Sets
tpzone: 10.6.28
Setting the Zone for Plot Functions
tpmacrofile: 10.6.11 Running a Tecplot Macro File
tpmapcount: 10.6.14 Determining the Number of Maps in the Current Frame
tpmapcopy: 10.6.13 Copying Maps in a Data Set
tpdims: 10.6.5
Getting Dataset and Zone Dimensions
tpvarname: 10.6.25
Obtaining a Variable Name from Variable Number
tpvarnum: 10.6.26
Obtaining a Variable Number from Variable Name
tpzonename: 10.6.29 Obtaining a Zone Name from Zone Number
tpzonenum: 10.6.30 Obtaining a Zone Number from Zone Name
tpget3D: 10.6.9
Transferring Volume Data from Tecplot to O-Matrix
tpput3D: 10.6.20
Transferring Data from O-Matrix to a Tecplot Volume
tpexport: 10.6.6
Creating Image Files
tpprint: 10.6.18
Printing the Current Frame
tpstart: 10.6.22
Connecting with a Tecplot Server
tprunning: 10.6.21
Checking if Tecplot is Running
10.6.e: Function Reference
The following table lists all of the O-Matrix client functions for interacting with the Tecplot server.
Adding a Zone to an Existing Dataset
tpcolors: 10.6.2
Line Color Sequence for XY Plots
tpcontour: 10.6.3
Creating Contour Plots
tpdataset: 10.6.4
Creating Tecplot Data Sets
tpdims: 10.6.5
Getting Dataset and Zone Dimensions
tpexport: 10.6.6
Creating Image Files
tpframe: 10.6.7
Popping, Creating and Obtaining Frame Names
tpget: 10.6.8
Transferring Data from Tecplot to O-Matrix
tpget3D: 10.6.9
Transferring Volume Data from Tecplot to O-Matrix
tphist: 10.6.10
Creating Histograms
tpmacrofile: 10.6.11 Running a Tecplot Macro File
tpmacrostring: 10.6.12 Running a Tecplot Macro String
tpmapcopy: 10.6.13 Copying Maps in a Data Set
tpmapcount: 10.6.14 Determining the Number of Maps in the Current Frame
tpopen: 10.6.15
Opening Tecplot Data, Layout and Style Files
tpplot: 10.6.16
Creating XY Plots
tpplottype: 10.6.17
Setting and Retrieving Current Frame Plot Type
tpprint: 10.6.18
Printing the Current Frame
tpput: 10.6.19
Transferring Data from O-Matrix to Tecplot
tpput3D: 10.6.20
tprunning: 10.6.21
tpstart: 10.6.22
tpsurface: 10.6.23
tpsymbols: 10.6.24
tpvarname: 10.6.25
tpvarnum: 10.6.26
tpxyzaxes: 10.6.27
tpzone: 10.6.28
tpzonename: 10.6.29
tpzonenum: 10.6.30
Transferring Data from O-Matrix to a Tecplot Volume
Checking if Tecplot is Running
Connecting with a Tecplot Server
Creating Surface Plots
Setting Symbol Style for XY Plots
Obtaining a Variable Name from Variable Number
Obtaining a Variable Number from Variable Name
Setting X, Y and Z Axes Minimum, Maximum, and Type
Setting the Zone for Plot Functions
Obtaining a Zone Name from Zone Number
Obtaining a Zone Number from Zone Name
10.6.f: Tecplot Application Samples
The reference pages for the examples above provide concise examples to illustrate the syntax and usage of each function. More detailed, applicationoriented illustrations of using O-Matrix with Tecplot can be found in the omwin\example\tecplot directory of your distribution.
10.6.1: Adding a Zone to an Existing Dataset
See Also tpdataset: 10.6.4 , tpzone: 10.6.28 , tpframe: 10.6.7 , tpmapcopy: 10.6.13 , tpput: 10.6.19 , tpget: 10.6.8 , tpopen: 10.6.15
10.6.1.a: Description
Add a new zone to the dataset of the currently active Tecplot frame. The arguments I, J, and K must be integer scalars that specify the I, J and K values
of the new zone. If the variable K is not specified, K is set to 1. The return value zoneNumber is an integer scalar that specifies the number of the zone
that was created. If present, the argument name must be a character row vector which is used as the name of the zone created.
10.6.1.b: Examples
If from the Tecplot menu you select "File | New Layout" and then select "Data | Create Zone | Rectangular", Tecplot will create a new data set that
contains 1 zone and variables X, Y, and Z. If at the O-Matrix prompt you enter
O-Matrix will echo 2 in the command window which is the number of the new zone created and Tecplot will now have a new zone with IMax = 3, and
JMax = 4, and KMax = 1.
If at the O-Matrix prompt you enter
tpopen
tpdataset({"Sample 1", "Sample 2", "Sample 3"})
O-Matrix will create a new dataset with 3 variables Sample 1, Sample 2, and Sample 3. If you continue by entering
O-Matrix will add 2 zones to the data set with names Experiment 1, and Experiment 2, each with I = 20, J = 1, and K = 1.
See the tpmapcopy: 10.6.13 function for additional examples that use the tpaddzone function.
10.6.2: Line Color Sequence for XY Plots
Syntax tpcolors()
tpcolors(colors)
See Also tpplot: 10.6.16 , tpsymbols: 10.6.24 , tpopen: 10.6.15 , tpmacrostring: 10.6.12
10.6.2.a: Description
If the character matrix colors is present, tpcolors sets the current color sequence to the specified colors. If colors is not present, tpcolors returns the
current color sequence. Unless specified by tpcolors, O-Matrix uses the following sequence of colors for plotting in Tecplot: "BLACK", "RED",
"GREEN", "BLUE", "CYAN","YELLOW", and "PURPLE". That is, the first line plotted with tpplot: 10.6.16 will be black, the second will be red,
and so on. The sequence starts over after a purple plot. The color "WHITE" can be added to the color sequence, but it is not part of the default
sequence. It is primarily useful for erasing lines from a plot.
10.6.2.b: Examples
If you enter
clear
print tpcolors
O-Matrix will print the default color sequence. If you enter
tpcolors({"RED","GREEN","RED","BLUE"})
tpcolors
O-Matrix will change the color sequence to the specified colors and print the following result
RED
GREEN
RED
BLUE
If you continue the example by entering
y = 1:1:5
for i = 1 to 2*rowdim(tpcolors) begin
tpplot(y+i);
end
O-Matrix will generate the following graph in Tecplot
10.6.3: Creating Contour Plots
Syntax tpcontour( Z)
tpcontour( Z, floodStyle)
tpcontour( Z, X, Y)
tpcontour( Z, X, Y, floodStyle)
10.6.3.a: Description
Creates contour plots in Tecplot of O-Matrix data. The argument Z must be an integer, real, or double-precision matrix. If present, the argument
floodStyle must be a character row vector which specifies the type of flooding. The value of floodStyle must be one of: "Flood", "Lines", or
""Lines&Flood". If present, the arguments X and Y must be integer, real or double-precision matrices whose row and column dimensions are
equivalent to Z
10.6.3.b: Examples
If, at the O-Matrix prompt you enter
Z = {[1,1,1],[1,2,2],[1,2,3]}
tpcontour(Z)
O-Matrix will transfer the values of Z to Tecplot and create the following plot
If you continue the example by entering
tpopen
tpcontour(Z,"Lines&Flood")
O-Matrix will clear the current layout in Tecplot and re-generate the plot with both Lines and Flood.
If the values of X and Y are not specified O-Matrix creates and transfers to Tecplot values for X and Y which provide a regular grid for the contour of
Z. For example, if contouring a 3 by 3 matrix, the following value will be transferred for X
{
[ 1, 2 , 3 ]
[ 1, 2 , 3 ]
[ 1, 2 , 3 ]
}
And the following value will be transferred for Y
{
[ 1 , 1 , 1 ]
[ 2 , 2 , 2 ]
[ 3 , 3 , 3 ]
}
If the values of X and Y are specified they can be used to define a grid that is not regular for the contour of Z. If at the O-Matrix prompt you enter,
Z = {[1,1,1],[1,2,2],[1,2,3]}
X = {[1,2,3],[1,2,3],[1,2,3]}
Y = {[1,2,1],[2,2,2],[3,3,3]}
tpframe("Irregular Y")
tpcontour(Z,X,Y)
Tecplot will create a new frame, "Irregular Y" and generate the following plot which defines an irregular grid for Y.
If you continue the example by entering,
X = {[1,2,3],[1,2,2],[1,2,3]}
Y = {[1,1,1],[2,2,2],[3,3,3]}
tpframe("Irregular X")
tpcontour(Z,X,Y)
Tecplot will create a new frame, "Irregular X" and generate the following plot which defines an irregular grid for X.
The tpcontour function can use various zones of a single data set which can be useful for such features as creating animations. If, at the O-Matrix
prompt you enter
clear
tpcontour(rand(10,10))
for i = 1 to 9 begin
tpzone(i);
tpcontour(rand(10,10))
end
O-Matrix will create a Tecplot data set that contains 10 zones, where each zone contains a different 10 by 10 random valued matrix.
10.6.4: Creating Tecplot Data Sets
Syntax tpdataset( variables)
tpdataset( variables, I, J, K)
10.6.4.a: Description
Creates a new data set. The argument variables is a character matrix where each row contains the name of a variable to use for the new dataset. The
number of variables created equals the rowdim: 3.15 of variables. If the arguments I, J, and K are present then tpdataset also creates a new zone with
the specified dimensions.
If the argument I, J, and K are not present, tpdataset does not create any zones and you must call the tpaddzone: 10.6.1 function before interacting
with Tecplot or transferring data from the O-Matrix client.
If the current frame contains a data set when you call tpdataset, it is deleted.
10.6.4.b: Examples
If you enter,
tpdataset({"Depth","Pressure","Salinity"})
Tecplot will create a new data set that contains the 3 variables Depth, Pressure, and Salinity. Note that at this point the data set does not contain any
zones. You must create at least 1 zone in the data set before interacting with Tecplot. If you continue the example above by entering,
O-Matrix will add 2 zones, Sample1, and Sample2, both with I = 20, J = 1, and K = 1.
You can also create a zone at the time that a data set is created, If you continue the example above by entering
tpframe("Oceans Two")
vars = {"Depth", "Conductivity", "Oxygen", "Temperature"}
tpdataset(vars, 100, 1, 1)
Tecplot will create a new frame named Oceans Two with a new data set that contains one zone with the variables Depth, Conductivity, Oxygen, and
Temperature.
10.6.5: Getting Dataset and Zone Dimensions
Syntax [nZones, nVars] = tpdims()
[I,J,K] = tpdims(zone)
See Also tpget: 10.6.8 , tpput: 10.6.19 , tpaddzone: 10.6.1 , tpplottype: 10.6.17 , tpzonename: 10.6.29 , tpvarname: 10.6.25
10.6.5.a: Description
Determines the number of zones and variables in a data set and the I, J, and K values of a specified zone. If tpdims is called without arguments, the
value nZones is the number of zones in the current data set and nVars is the number of variables. If nZones equals 0, the current frame does not have a
data set. If called with the argument zone, the value must be an integer scalar greater than 0. The values I, J, and K specify the maximum dimension of
the given plane.
10.6.5.b: Examples
If at the O-Matrix prompt you enter,
tpopen
[nZones, nVars] = tpdims
print "nZones = ", nZones, " nVars = ", nVars
O-Matrix will respond,
nZones =
0
nVars =
0
If you continue the example by entering
tpopen([OM_INSTALL,"\example\tecplot\rainfall.plt"])
[nZones, nVars] = tpdims
print "nZones = ", nZones, " nVars = ", nVars
[I, J, K] = tpdims(1)
O-Matrix will respond
nZones = 5 nVars = 6
IMax = 12 JMax = 1 KMax =
1
10.6.6: Creating Image Files
Syntax tpexport(file, format)
10.6.6.a: Description
Creates image files of Tecplot graphs. The argument file must be a character row vector which specifies the name of the file to be created. If a
complete path is not given with the file name the file is created in the O-Matrix cwd: 6.5.5 . The argument format must be a character row vector
which specifies the format of the image file to be created. The value of format must be one of: TIFF, EPS, BMP, PNG, or JPEG.
10.6.6.b: Examples
If at the O-Matrix prompt you enter,
clear
tpopen
x = 0. : .1 : 2 * pi
y1 = sin(x)
y2 = 2 * sin(x)
y3 = 3 * sin(x)
tpplot(x,[y1, y2, y3], "SOLID", 0.5)
tpexport([OM_INSTALL,"\programs\sin1.png"], "PNG")
Tecplot will create a PNG format image file of the following image in the programs directory of your O-Matrix installation.
If you continue the example by entering
tpopen
tpplot(x,y1, "SOLID", 0.5)
tpplot(x,y2, "SOLID", 0.5)
tpplot(x,y3, "SOLID", 0.5)
tpexport([OM_INSTALL,"\programs\sin2.bmp"], "BMP")
Tecplot will create a BMP format image file of the following image in the programs directory of your O-Matrix installation.
10.6.7: Popping, Creating and Obtaining Frame Names
Syntax tpframe()
tpframe( frame)
See Also tpopen: 10.6.15 , tpput: 10.6.19 , tpplottype: 10.6.17 , tpmacrostring: 10.6.12
10.6.7.a: Description
Pops or creates a specified Tecplot frame. The tpframe function returns a character row vector specifying the name of the frame that is active in
Tecplot. If specified, the character row vector frame specifies the name of a frame to pop. If a frame with the title frame does not exist, it is created.
10.6.7.b: Examples
If you enter,
clear
tpopen
tpFrame = tpframe
print tpFrame
O-Matrix will echo
Frame 001
which is the default name of the first frame created by Tecplot. If you continue by entering
for i = 1 to 5 begin
f = tpframe(["O-Matrix Frame #", ntoa(i)])
tpFrame = {tpFrame, f}
end
tpFrame
O-Matrix will create 5 new frames, saving the names in the character matrix tpFrame and echo the result
O-Matrix
O-Matrix
O-Matrix
O-Matrix
O-Matrix
Frame
Frame
Frame
Frame
Frame
#1
#2
#3
#4
#5
If you continue the example by entering,
tpframe(tpFrame.row(3))
Tecplot will pop the second frame created by O-Matrix,
10.6.8: Transferring Data from Tecplot to O-Matrix
Syntax X = tpget( variable)
X = tpget( variable, zone)
See Also tpput: 10.6.19 , tpget3D: 10.6.9 , tpopen: 10.6.15 , tpvarname: 10.6.25 , tpzonename: 10.6.29 , tpmacrostring: 10.6.12 , tpdims: 10.6.5
10.6.8.a: Description
Transfers data from a Tecplot data set to O-Matrix. The current frame must contain a data set with data of type Double or Float. The argument variable
must be an integer scalar or character row vector that specifies the variable number or variable name to retrieve. If present, the argument zone must be
an integer scalar or character row vector that specifies the zone number or zone name to retrieve. If zone is not specified, data are retrieved from the
first zone of the current data set. The returned value X is a double-precision valued matrix where the number of rows in X equals the I value of variable
and the number of columns in X equals the J value of variable.
10.6.8.b: Examples
10.6.8.b.a: Retrieving Data from Tecplot
If you enter,
clear
tpopen
x = {1.0,1,2,4,8}
y1 = sqrt(x)
tpplot(x,y1)
Tecplot will create an XY plot of x and y1. If you continue by entering
y2 = tpget(2)
y2' - y1'
O-Matrix will transfer the values of the second variable, (Y), in the current data set to the variable y2, and then print the difference between y1 and y2
illustrating that the values transferred are equivalent to those received.
[ 0 , 0 , 0 , 0 , 0 ]
Variables can also be retrieved by name, If you continue by entering
y3 = tpget("Y")
y3' - y1'
O-Matrix will echo the same result.
If you enter,
clear
tpopen([OM_INSTALL,"\example\tecplot\SixZones.lay"])
Tecplot will open the SixZones.lay sample file from the distribution which contains six zones named, Test One, Test Two, ... Test Six, with variables X,
sine, and cosine. If you continue the example above by entering
tpget("cosine", "Test Six")
O-Matrix will echo the value of the variable cosine in the zone name Test Six. The following script can be used to display, or retrieve all variables in
all zones of the current data set.
ix = 1
while( tpzonename(ix) <> " ") begin
jx = 1
while( tpvarname(jx) <> " ") begin
tpget(jx, ix)
jx = jx + 1
end
ix = ix + 1
end
The tpget and tpput: 10.6.19 functions can also be used to work with finite element data. If you enter,
clear
tpopen([OM_INSTALL,"\example\tecplot\DuctFlow.lay"])
D = tpget("U(M/S)")
O-Matrix will retrieve the variable U(M/S) from the finite element sample file. If you continue by entering,
sum( D > 250)
O-Matrix will echo
3391
which is the number of values in the variable that are greater than 250.
10.6.8.b.b: Updating Results
Use of the tpget and tpput: 10.6.19 functions together is very powerful for updating data sets, either generated by O-Matrix or originally in Tecplot. If
you enter,
clear
tpopen
s = -pi:0.2:pi
X = fillcols(s,rowdim(s))
Y = fillrows(s',rowdim(s))
M = sin(X) + cos(Y)
tpsurface(M,X,Y)
Tecplot will generate the following surface plot,
If you continue, by entering
ix = 1.0
while( ix < 3.0 ) begin
M = sin(X)*ix + cos(Y)*ix
tpput(M,"Z")
ix = ix + 0.1
tpmacrostring("$!REDRAWALL") end O-Matrix will update the value of Z created in the surface plot above and generate an animation that ends with the following image If you enter, clear tpopen tpopen([OM_INSTALL,"\example\tecplot\rainfall.plt"]) month = tpget("Month") dallas = tpget("Dallas Rainfall") seattle = tpget("Seattle Rainfall") tpframe("Seattle - Dallas Rainfall") tpplot(month, seattle - dallas) O-Matrix will open, and transfer the Dallas and Seattle rainfall data values. A new frame will be created that plots the difference between Dallas and Seattle rainfall. If you want to change the Seattle rain data you can continue the example by entering, tpframe("Frame 001") tpput(seattle+1, "Seattle Rainfall") and the plot will now look like 10.6.9: Transferring Volume Data from Tecplot to O-Matrix Syntax X = tpget3D( variable, zone, plane, planeNumber) See Also tpget: 10.6.8 , tpput3D: 10.6.20 , tpdims: 10.6.5 , tpplottype: 10.6.17 , tpxyzaxes: 10.6.27 , tpdataset: 10.6.4 10.6.9.a: Description Transfers planes of a Tecplot 3D ordered data set to O-Matrix. The current frame must contain a data set with data of type Double or Float. The argument variable must be an integer scalar that specifies the variable number to retrieve. The argument zone must be an integer scalar that specifies the zone number to retrieve. The argument plane must equal "I", "J", or "K" and specifies the desired plane to retrieve. The argument planeNumber is the desired plane number for the specified plane. The returned value X is a double or float precision valued matrix. 10.6.9.b: Examples 10.6.9.b.a: Retrieving Volume Data If you enter, clear tpopen([OM_INSTALL,"\example\tecplot\astrojet.lpk"]) Tecplot will open the astrojet.lpk sample file from the distribution which contains a 3D volume with IMax = 40, JMax = 40, and KMax = 9. Your display will now look like If you continue by entering I20 = tpget3D(tpvarnum("/dset"), 1, "I", 20) tpframe("IPlane = 20 Contour") tpcontour(I20) tpxaxis(1, 9) tpyaxis(0, 40) O-Matrix will retrieve the data for I plane number 20 for variable /dset. This result is then plotted as a contour in a new frame and your display will now look like This result may also be obtained by explicitly retrieving and contouring with the spatial variables from the original volume. If you enter, tpopen([OM_INSTALL,"\example\tecplot\astrojet.lpk"]) I20 = tpget3D(tpvarnum("/dset"), 1, "I", 20) ZI20 = tpget3D(tpvarnum("Z"), 1, "I", 20) YI20 = tpget3D(tpvarnum("Y"), 1, "I", 20) tpframe("With Variables") tpcontour(I20, ZI20, YI20) Tecplot will create the contour presented above. 10.6.9.b.b: Modifying Volume Data Use of the tpput3D: 10.6.20 function with tpget3D enables various data altering and numerical analysis of Tecplot data sets. If you enter, clear tpopen([OM_INSTALL,"\example\tecplot\FluidVolume.lpk"]) Tecplot will open the FluidVolume.lpk sample file from the distribution and create the following display If you continue by entering the following, O-Matrix will retrieve each J plane of the variable RHO-V from the sample data and replace each plane that contains any values less than the threshold value of -45 with a constant valued plane of -45. [I,J,K] = tpdims(1) for j = 1 to J begin P = tpget3D(4,1,"J", j) if( any(P < -45) ) then begin P = fill(-45,I,K) tpput3D(P,4,1,"J",j) end end 10.6.9.b.c: Organizing Volume Data The tpget3D and tpput3D: 10.6.20 functions provide flexible and automated techniques for re-arranging, or changing the form of Tecplot data sets. If you enter, clear tpopen([OM_INSTALL,"\example\tecplot\FluidVolume.lpk"]) Tecplot will load the FluidVolume.lpk sample file which contains 1 zone and 5 variables with IMax = 9, JMax = 12, and KMax = 11. The following sample will create 11 new zones with IMax = 9, JMax = 12 and KMax = 1 with the same 5 variables, each containing a single K plane from the original zone. [nZones,nVars] = tpdims() [I,J,K] = tpdims(1) for k = 1 to K begin zNum = tpaddzone(I,J,1,["KPlane:",ntoa(k)]) for v = 1 to nVars begin P = tpget3D(v,1,"K", k) tpput(P,v,zNum) end end The revised data set structure can be reviewed in the Tecplot Zone Style dialog 10.6.10: Creating Histograms Syntax [y, ry] = tphist(x, K) [y, ry] = tphist(x, K, relativeFrequencies) See Also tpplot: 10.6.16 , tpput: 10.6.19 10.6.10.a: Description Create a histogram plot of the data in the numeric vector, x. The argument K specifies the number of bins to be used. If the value of K is 0, then the tphist function will determine the bin count automatically. If present, the argument relativeFrequencies, must equal true, and specifies that relative frequencies should be plotted. The returned value y is the calculated frequency vector, and the returned argument ry is the relative frequency vector. 10.6.10.b: Examples If at the O-Matrix prompt you enter, r = snormal(128000,1) tphist(r, 40); Tecplot will create the following histogram plot for the normal distribution, r. If you continue the example above by entering tpframe("Relative Frequencies") tphist(r, 30, true); Tecplot will create a histogram plot for the relative frequencies 10.6.11: Running a Tecplot Macro File Syntax tpmacrofile( file) See Also tpmacrostring: 10.6.12 , tpsurface: 10.6.23 , tpplot: 10.6.16 , tpcontour: 10.6.3 10.6.11.a: Description Executes the Tecplot macro contained in the file file, where file is a character row vector. 10.6.11.b: Examples If you create a file CreateData.mcr in your cwd: 6.5.5 that contains #!MC 1100$!CREATERECTANGULARZONE
IMAX = 10
JMAX = 10
KMAX = 10
X1 = 0
Y1 = 0
Z1 = 0
X2 = 1
Y2 = 1
Z2 = 1
XVAR = 1
YVAR = 2
ZVAR = 3
$!PLOTTYPE = CARTESIAN2D and then enter clear tpopen tpmacrofile("CreateData.mcr") Tecplot will run the macro defined in CreateData.mcr and create a new data set with a new zone. The current working directories for O-Matrix and Tecplot are not necessarily the same. If the argument file does not include a complete path the current working directory is added to the file name before executing in Tecplot. If a complete path is given, that is passed directly to Tecplot. The tpmacrofile function can be used to run Tecplot provided, or user defined macros that provide additional customization to a sequence of OMatrix analysis. If you enter, clear tpopen include example\demo\rosen.oms X = fillcols(x, rowdim(x)) Y = fillrows(y, coldim(y)) tpsurface(R, X, Y) tpmacrofile([OM_INSTALL, "\example\tecplot\Rotate360.mcr"]) O-Matrix will run the Rosenbrock example from the O-Matrix distribution, create a surface plot of the function in Tecplot and then run the Rotate360.mcr macro that is provided with the distribution. The last image of the rotation sequence will appear as, 10.6.12: Running a Tecplot Macro String Syntax tpmacrostring( macro) See Also tpmacrofile: 10.6.11 10.6.12.a: Description Executes a Tecplot macro that is defined by the character row vector macro. 10.6.12.b: Examples If you enter, clear tpopen tpplot(1:0.2:10) tpmacrostring("$!LINEMAP [1] NAME = 'MyMap'")
Tecplot will generate a line plot and then change the name of the first line map to 'MyMap'.
Many Tecplot macros require that arguments to the macro be on separate lines, but the tpmacrostring functions require that the macro command sent
to Tecplot be a character vector. These types of commands can be constructed as in the following example. Note that multiple line macros can be
combined into a single line as illustrated in this example, but the tpmacrostring command can only execute one macro at a time. If you enter,
clear
tpopen
mlmode sombrero.m
Z = sombrero(20)
tpsurface(Z)
O-Matrix will use the mlmode: 25 function sombrero to create the following surface plot.
If you continue the example by entering
cmd = ["$!CONTOURLEVELS RESETTONICE", NEW_LINE," tpmacrostring(cmd) CONTOURGROUP = 1", NEW_LINE, " APPROXNUMVALUES = 3"] O-Matrix will run a Tecplot macro to re-scale the number of contour levels to 3 and update the surface plot to look like, 10.6.13: Copying Maps in a Data Set Syntax newMap = tpmapcopy(zone,map) See Also tpopen: 10.6.15 , tpget: 10.6.8 , tpput: 10.6.19 , tpplot: 10.6.16 , tpaddzone: 10.6.1 10.6.13.a: Description Creates a new line map by copying an existing line map which is specified by the integer scalar map. The integer scalar zone specifies an existing zone number that is to be used for the new map. The tpmapcopy function returns the number of the map that is created. 10.6.13.b: Examples Use of the tpmapcopy function with the tpaddzone: 10.6.1 function is very useful for updating existing data sets. If you enter, clear fName = [OM_INSTALL,"\example\tecplot\rainfall.plt"] tpopen(fName) Tecplot will open the rainfall sample data file from your distribution. If you continue by entering rain = tpget("Dallas Rainfall") month = tpget("Month") O-Matrix will transfer the data values for the Tecplot variables "Dallas Rainfall" and "Month" to O-Matrix. At this point the data set has 5 line maps and 5 zones. You can modify the rain variable in O-Matrix and update the plot by entering for i = 1 to 4 begin newZone = tpaddzone(rowdim(rain), coldim(rain) ) tpmapcopy(newZone, 2); rain = rain + .25 tpput(rain, "Dallas Rainfall", newZone) tpput(month, "Month", newZone) end This will create 4 new maps, where each map is created from the existing map number 2 which is the Dallas Rainfall map, and 4 new zones which contain the updated values for the rain variable in each iteration of the loop. When the file was opened, the Seattle Rainfall map was activated by default. This map can be disabled by entering tpmacrostring("$!ACTIVELINEMAPS -= [1]")
At which point you have the following updated plot
10.6.14: Determining the Number of Maps in the Current Frame
Syntax tpmapcount()
10.6.14.a: Description
Returns an integer scalar specifying the number of maps in the current Tecplot frame.
10.6.14.b: Examples
If you enter
clear
tpopen
x = 0. : .1 : 2 * pi
y = cos(x)
ix = 0.2
while (ix < 6.0) begin
m =tpplot(x+ix,y)
ix = ix + 1
print "tpplot() created map number: ", m
end
O-Matrix will create 6 curves, with 6 line maps and echo the number of each map as it is created,
tpplot()
tpplot()
tpplot()
tpplot()
tpplot()
tpplot()
created
created
created
created
created
created
map
map
map
map
map
map
number:
number:
number:
number:
number:
number:
1
2
3
4
5
6
If you continue by entering
tpmapcount
O-Matrix will echo 6 which is the number of maps in the current frame after executing the example above.
The tpmapcount function can also be used to determine the number of maps in existing data sets or files. If you enter,
tpopen([OM_INSTALL,"\example\tecplot\rainfall.plt"])
print "Number of maps in rainfall.plt = ", tpmapcount
O-Matrix will echo
Number of maps in rainfall.plt =
5
which is the number of map in the rainfall.plt sample data file.
10.6.15: Opening Tecplot Data, Layout and Style Files
Syntax tpopen()
tpopen(file)
10.6.15.a: Description
If called without any arguments, the tpopen command creates a new layout in Tecplot. That is it has the same effect as selecting "File | New Layout"
from the Tecplot menu. If present, the argument file must be a character row vector that specifies the name of a valid, existing layout, data or style file.
The file suffix must be .LAY, .LPK, .PLT, or .STY.
10.6.15.b: Examples
If, at the O-Matrix prompt you enter,
clear
fName = [OM_INSTALL,"\example\tecplot\rainfall.plt"]
tpopen(fName)
Tecplot will open the rainfall data file from the O-Matrix example directory. You can obtain the displayed data from Tecplot by entering,
rain = tpget("Seattle Rainfall")
month = tpget("Month")
If you continue, by modifying the data and transferring the result back to Tecplot by entering,
rain = rain - 1.0
tpput(rain,"Seattle Rainfall")
You will get the following updated result in Tecplot
Using Tecplot to visualize data from O-Matrix solutions often involves interactively manipulating and customizing plots that have been generated with
O-Matrix plotting functions or generated from data transferred from O-Matrix. You can save these interactive customizations as Tecplot style files and
the re-apply them later from O-Matrix analysis scripts. If you enter,
tpopen
x = 0. : 0.1 : 2 * pi
y = [sin(x), cos(x)]
tpplot(y)
Tecplot will generate a simple line plot. You might make some interactive customizations of the plot which are saved in sinestyle.sty. If you continue
the example by entering
tpopen([OM_INSTALL,"\example\tecplot\sinestyle.sty"])
Tecplot will apply the saved style file and update the plot. After entering Ctrl-F in Tecplot, the plot will now look like,
10.6.16: Creating XY Plots
Syntax map = tpplot(Y)
map = tpplot(X, Y)
map = tpplot(X, Y, pattern)
map = tpplot(X, Y, pattern, thickness)
See
tpput: 10.6.19 , tpget: 10.6.8 , tpopen: 10.6.15 , tpsymbols: 10.6.24 , tpcolors: 10.6.2 , tpxyzaxes: 10.6.27 , tpframe: 10.6.7 , tpmapcopy:
Also
10.6.13
10.6.16.a: Description
Creates XY plots in Tecplot, of O-Matrix data. Plots a curve for each column of Y, where Y is an integer, real, or double-precision matrix specifying
the Y value for each point. The first column corresponds to a curve with the next color in the current color sequence defined by tpcolors: 10.6.2 , the
second column corresponds to the following color and so on. If X is not present, i is the X value corresponding to y(i,j).
If X is present, it must be is an integer, real, or double-precision matrix and have same number of rows as Y. If X is a column vector, each column of Y
is plotted against the vector X. Otherwise X also must have the same number of columns as Y and each column, Y(i) is plotted against X(i).
If present, the argument pattern must be a character row vector equal to "SOLID", "DASHED", "DASHDOT", "DOTTED", "LONGDASH", or "DASHDOTDOT".
The Tecplot line pattern for the current plot is set to this pattern.
If present, the argument thickness must a real-valued scalar with a value between 0.0 and 1.0. The Tecplot line thickness for the current plot is set to
this value.
If the current frame does not contain a data set, or if the current data set does not contain at least 2 variables, a new frame is created with variables X,
and Y. If the current frame does contain a data set with at least 2 variables, the plot is created by adding a new zone and transferring the X data to the
first variable in the zone and the Y data to the second variable. The first map is copied to the end of the maps, activated, and assigned the zone that
received the X and Y data from O-Matrix.
The returned value map is an integer scalar specifying the number of the map used for the current plot.
10.6.16.b: Examples
If at the O-Matrix prompt you enter,
tpopen
x = 0. : 0.1 : 2 * pi
y = [sin(x), cos(x)]
tpplot(y)
Tecplot will create the following plot
If you continue the example above by enter
tpplot(y*3)
tpplot(y*5)
Tecplot will create two new maps in the current frame which are copies of the first map, and will update the plot to include four additional curves.
The tpplot function can also specify the X values to be used for the given Y. If you enter the commands
tpframe("My X Values")
tpplot(x/2, y)
Tecplot will create a new frame title, "My X Values", that looks like
If you continue the example by entering,
tpframe("Multiple X Values")
tpplot( [x, x/2], y)
Tecplot will create a new frame named "Multiple X Values", where the first column of y is plotted vs. x and the second column of y is plotted vs. x/2
The Tecplot line pattern and thickness can be specified at the time that plots are created by O-Matrix. If you enter
tpopen
x = seq(100) / 10.0
y = besselj(2, x)
tpplot(x, y, "DASHDOT", 0.5)
Tecplot will create the following plot of the J2 Bessel function
10.6.17: Setting and Retrieving Current Frame Plot Type
Syntax type = tpplottype()
type = tpplottype(type)
10.6.17.a: Description
Determines and optionally sets the plot type for the current frame. The value type is a character row vector that equals "CARTESIAN2D",
"CARTESIAN3D", "XYLINE", "SKETCH", or "POLARLINE". If the type is not given as an argument, the tpplottype function returns the current plot type
without changing it.
10.6.17.b: Examples
If you enter,
tpopen
print tpplottype()
O-Matrix will echo
SKETCH
which is the default plot type for new frames. If you continue the example by entering
tpcontour(rand(10,12))
tpplottype("CARTESIAN3D")
Tecplot will create a contour plot and change the plot type to 3D.
10.6.18: Printing the Current Frame
Syntax tpprint()
10.6.18.a: Description
Prints the frame that is currently active.
10.6.19: Transferring Data from O-Matrix to Tecplot
Syntax tpput( expression)
tpput( expression, variable)
tpput( expression, variable, zone)
See Also tpget: 10.6.8 , tpput3D: 10.6.20 , tpaddzone: 10.6.1 , tpframe: 10.6.7 , tpopen: 10.6.15 , tpplottype: 10.6.17 , tpdims: 10.6.5
10.6.19.a: Description
Transfers data from O-Matrix to a Tecplot data set. The argument expression must be an integer, real, or double-precision valued expression. The
arguments variable and zone specify the variable and zone name or number that data are transferred to. If no data set exists when this command is
executed, a data set is created with variables X, Y, and Z. If no data set exists when this command is executed, the arguments variable and zone must be
integer scalars if present. If the argument variable is not specified data are transferred to the first variable in the data set. If the variable zone is not
specified data are transferred to the first zone. If the current frame does not contain a data set, the new dataset is created with Tecplot type Double. The
tpput function can transfer data to Tecplot data sets of type Double or Float, other data types are not supported. O-Matrix will convert the value of
expression to Double or Float if necessary before transferring.
10.6.19.b: Examples
10.6.19.b.a: Creating Data Sets and Transferring Data
If you enter,
clear
tpopen
tpput([1,2,3])
Tecplot will create a new data set with variables X, Y and Z with IMax = 1, JMax = 3, and KMax = 1. If you continue the example by entering
v = {1,1,1,1}
tpput(v)
tpput(v*2, 2)
tpput(v*3, 3)
Tecplot will re-dimension the existing data set with IMax = 4, JMax = 1, and KMax = 1, with variables 1, 2, and 3 containing the values illustrated
below.
Data can also be transferred to a specified zone. If you enter,
clear
tpopen
x = 0. : 0.1 : 2 * pi
y = [sin(x), cos(x)]
tpput(x,1)
tpput(y,2)
O-Matrix will create a new data set in Tecplot where the first variable contains the value of x and the second variable contains the value of y. If you
continue by entering
for i = 1 to 5 begin
tpput(x,1,zone)
tpput(y*i, 2, zone)
end
five new zones will be created where the values of Y contain increasing amplitudes of y.
10.6.19.b.b: Transferring Using Variable and Zone Names
If a data set exists in the current frame the value of expression and be transferred by giving a variable and zone name. If the variable or zone name is
not unique, the first name with the specified value is used. If you create a new data set by entering
x = 0. : 0.1 : 2 * pi
tpput(x)
and then manually change the name of the Y variable in this data set to cos, you can transfer to this variable by entering,
tpput(cos(x), "cos")
If you enter,
clear
tpopen([OM_INSTALL,"\example\tecplot\SixZones.lay"])
Tecplot will open the SixZones.lay sample file from the distribution which contains six zones named, Test One, Test Two, ... Test Six, with variables X,
sine, and cosine. If you continue the example above by entering
sine = tpget("sine", "Test Four")
nr = rowdim(sine)
sine = sine + (rand(nr,1)-0.5)/3.0
tpput(sine,"sine", "Test Four")
O-Matrix will transfer the values from the variable with name sine from the zone named Test Four add a noise signal to the value, and return the
updated value to the same location. The plot will update to look like,
10.6.20: Transferring Data from O-Matrix to a Tecplot Volume
Syntax tpput3D( expression, variable, zone, plane, planeNumber)
See Also tpget3D: 10.6.9 , tpput: 10.6.19 , tpvarname: 10.6.25 , tpzonename: 10.6.29
10.6.20.a: Description
Transfers data from a O-Matrix to an existing Tecplot data set. The current frame must contain a data set with data of type Double or Float. The
argument expression must be a real or double precision value. The argument variable must be an integer scalar that specifies the variable number set.
The argument zone must be an integer scalar that specifies the zone number to set. The argument plane must equal "I", "J", or "K" and specifies the
desired plane to set. The argument planeNumber is the desired plane number for the specified plane.
10.6.20.b: Examples
10.6.20.b.a: Transferring Data to Tecplot
If you enter,
clear
tpopen([OM_INSTALL,"\example\tecplot\astrojet.lpk"])
tpput3D( fill(250d0,40,9), tpvarnum("/dset"), 1, "I", 30)
O-Matrix will open the astrojet.lpk sample file from the distribution and change all values in I plane 30, for variable /dset to 250. The updated plot will
appear as.
The tpput3D function can also be used to create new volume data in Tecplot. The following example creates a new data set with variables X, Y, and R
with IMax = 5, JMax = 6, and KMax = 10.
clear
tpopen
tpdataset({"X","Y","R"}, 5, 6, 10)
X = fillrows(seq(6)', 5)
Y = fillcols(seq(5), 6)
for k = 1 to 10 begin
tpput3D(X, 1, 1, "K", k)
tpput3D(Y, 2, 1, "K", k)
R = rand(5,6)
tpput3D(R+k, 3, 1, "K", k)
end
At this point you can interactively select a plot type and desired attributes, or if you continue the example by entering,
tpplottype("CARTESIAN3D")
tpmacrostring("$!FIELDLAYERS SHOWCONTOUR = YES") tpmacrostring("$!FIELDLAYERS SHOWMESH = NO")
You will get the following result
See the tpget3D: 10.6.9 function for additional examples of transferring data to and from 3D ordered data sets.
10.6.21: Checking if Tecplot is Running
Syntax tprunning()
10.6.21.a: Description
Returns true if Tecplot is running and the omlink server is installed, false otherwise.
10.6.22: Connecting with a Tecplot Server
Syntax tpstart()
10.6.22.a: Description
Establishes O-Matrix as a client with Tecplot. If O-Matrix has already established communication with Tecplot this command has no effect. Most of
the Tecplot interface functions verify that communication has been established with Tecplot and this command should not need to be called directly.
10.6.23: Creating Surface Plots
Syntax tpsurface( Z)
tpsurface( Z, meshStyle)
tpsurface( Z, meshStyle, contourStyle)
tpsurface( Z, X, Y)
tpsurface( Z, X, Y, meshStyle)
tpsurface( Z, X, Y, meshStyle, contourStyle)
See Also tpaddzone: 10.6.1 , tpzone: 10.6.28 , tpframe: 10.6.7 , tpopen: 10.6.15 , tpcontour: 10.6.3 , tpxyzaxes: 10.6.27
10.6.23.a: Description
Creates surface plots in Tecplot of O-Matrix data. The argument Z must be an integer, real, or double-precision matrix. If present, the argument
meshStyle must equal "NONE", "WIREFRAME", "OVERLAY", or "HIDDENLINE". If the value of meshStyle is "NONE", the mesh layer is disabled, otherwise
the mesh layer is enabled and the mesh style is set to the given value. If present, the argument contourStyle must equal "NONE", "FLOOD", "LINES",
"BOTHLINESANDFLOOD", "AVERAGECELL", or "PRIMARYVALUE". If the value of contourStyle is "NONE", the contour layer is disabled, otherwise the
contour layer is enabled and the contour type is set to the given value.
If present, the arguments X and Y must be integer, real or double-precision matrices with row and column dimensions equivalent to Z
If the current Tecplot frame contains a data set that contains variables X, Y, and Z, the tpsurface function creates the surface plot by transferring data
to the first zone of the existing data set. If the value of tpzone: 10.6.28 has been changed to a value other than 1 and that zone exists from the use of
tpaddzone: 10.6.1 or otherwise, the data for the surface plot is transferred to that zone.
10.6.23.b: Examples
10.6.23.b.a: Mesh and Contour Types
If, at the O-Matrix prompt you enter
clear
tpopen
Z = rand(5,4)
tpsurface(Z)
Tecplot will create a surface plot of the random matrix Z, which looks like,
If you continue by entering
tpsurface(Z,"HIDDENLINE")
The plot will be re-generated with mesh lines hidden. The mesh and contour styles may be viewed and changed interactively with the Tecplot Zone
Style dialog. If you continue by entering
tpsurface(Z,"NONE","PRIMARYVALUE")
The plot will be re-generated with the Tecplot mesh layer disabled a contouring with the contour value of PRIMARYVALUE and look like
10.6.23.b.b: Providing X and Y Values
If X and Y values are not provided, the tpsurface function creates and implicit X, Y grid where the values of X are fillrows(seq(nc)', nr) and
the values of Y are fillcols(seq(nr), nc). An alternate grid can be defined by providing X and Y values. If at the O-Matrix prompt you enter,
tpopen
nr = 10
nc = 15
Z = rand(nr,nc)
X = fillrows(seq(nc)', nr) + 10
Y = fillcols(seq(nr), nc) + 20
tpsurface(Z, X, Y)
Tecplot will create the following surface that uses the alternative X Y grid. The data may also be inspected from the Tecplot "Data | Spreadsheet"
dialog.
10.6.23.b.c: Using Zones with Surface Plots
It is frequently useful to generate multiple surface plots in a single frame. You can use the tpaddzone: 10.6.1 and tpzone: 10.6.28 functions to enable
this with tpsurface. If at the O-Matrix prompt you enter,
clear
tpopen
x = -5. : 1. : 5.
y = x'
z = x * y / 10.
tpsurface(z)
Tecplot will create a new surface plot with the value of z. If you continue the example by entering
tpzone(zNum)
z = (x * y/5) + 5
tpsurface(z,"none")
Tecplot will create a new zone, with number zNum in the current frame and generate an additional plot and now look like
10.6.23.b.d: Using Frames with Surface Plots
A series of surface plots can be created in individual frames. If you enter
clear
tpopen
x = -5. : 1. : 5.
y = x'
for i = 1 to 4 begin
tpframe(["tpsurface(); iteration = ", ntoa(i)])
z = x*y / (i*2)
tpsurface(z)
end
Tecplot will create 4 new frames, where each frame contains the solution from one iteration of the loop. The Cascade Frames option from the Tecplot
Quick Macro panel can be used to see the following solution
10.6.24: Setting Symbol Style for XY Plots
Syntax tpsymbols( map, on)
tpsymbols( map, shape, size)
10.6.24.a: Description
Sets the symbols state, shape and size for XY plot maps. The argument map must be an integer scalar that specifies a map number that exists in the
current frame. The argument on must be a logical scalar that specifies if the Tecplot symbol layer is to be turned on or off. If present, the argument
shape must be a character row vector that equals "DEL", "GRAD" , "RTRI", "LTRI", "DIAMOND", "CIRCLE" , or "SQUARE". The argument size must be a
real-valued scalar between 0.0 and 8.0 inclusively. If the arguments shape and size are present the symbols layer is turned on.
10.6.24.b: Examples
If you enter,
clear
tpopen
y = 1:2:20
tpplot(y);
map2 = tpplot(y+5)
tpplot(y+10)
tpsymbols(map2, "CIRCLE", 4.0)
Tecplot will create the following graph with 3 curves, where the second curve includes circle symbols of size 4.
If you continue the example by entering,
tpsymbols(map2, false)
Tecplot will turn off symbols for the second curve.
10.6.25: Obtaining a Variable Name from Variable Number
Syntax name = tpvarname(variable)
See Also tpvarnum: 10.6.26 , tpzonename: 10.6.29 , tpzonenum: 10.6.30 , tpmapcount: 10.6.14
10.6.25.a: Description
Returns the Tecplot variable name for the given variable number. The argument variable must be a positive integer scalar. The return value name is a
character row vector that specifies the name of the requested variable. If the return value name equals " " then the requested variable does not exist in
the current data set.
10.6.25.b: Examples
If you enter
clear
fName = [OM_INSTALL,"\example\tecplot\rainfall.plt"]
tpopen(fName)
tpvarname(3)
Tecplot will open the rainfall sample file from your distribution and print "Dallas Rainfall" which is the name for variable number 3. You can use
the tpvarname function to determine all of the variable names in a file. If you continue the example above by entering
ix = 1
while( tpvarname(ix) <> " ") begin
print tpvarname(ix)
ix = ix+1
end
O-Matrix will echo the following
Month
Seattle Rainfall
Dallas Rainfall
Miami Rainfall
Error 1
Error 2
10.6.26: Obtaining a Variable Number from Variable Name
Syntax variable = tpvarnum( name)
10.6.26.a: Description
Returns the Tecplot variable number for the variable name specified by the character row vector name in the current data set. If the return value
variable is less than 1 then the specified variable name does not exist in the current data set.
10.6.26.b: Examples
If you enter
clear
fName = [OM_INSTALL,"\example\tecplot\rainfall.plt"]
tpopen(fName)
tpvarnum("Dallas Rainfall")
Tecplot will open the rainfall sample file from your distribution and print 3 which is the variable number for "Dallas Rainfall"
10.6.27: Setting X, Y and Z Axes Minimum, Maximum, and Type
Syntax tpxaxis( min, max)
tpxaxis( type, min, max)
tpyaxis( min, max)
tpyaxis( type, min, max)
tpzaxis( min, max)
tpzaxis( type, min, max)
See Also tpplot: 10.6.16 , tpsymbols: 10.6.24 , tpcolors: 10.6.2 , tpplottype: 10.6.17 , tpmacrostring: 10.6.12
10.6.27.a: Description
Sets the minimum and maximum values of the X and Y axes, where min and max are integer, real, or double-precision scalars. If present, the argument
type must be "log", "linear", "offlog", or "offlin" and sets the axis to logarithmic or linear, and determines if the axis is displayed.
10.6.27.b: Examples
10.6.27.b.a: Using with XY Plots
If, at the O-Matrix prompt you enter
clear
tpopen
x = 1:0.1:4*pi
y = atan(x)
tpplot(y)
Tecplot will create the following plot
If you continue the example by entering,
tpyaxis(0, 2)
tpxaxis("offlin", 0, 150)
Tecplot will create the following plot
If you continue by entering
tpyaxis("log", .1, 10)
tpxaxis("linear", 0, 150)
Tecplot will scale the Y axis logarithmically from 0.1 to 10, and turn the X axis back on with the same scaling.
10.6.27.b.b: Using with Contour Plots
If you enter,
clear
tpopen
tpcontour(rand(10,10))
Tecplot will create the following contour plot.
If you continue by entering,
tpxaxis("offlin", 4, 8)
tpyaxis("offlin", 5, 9)
Tecplot will scale the X axis from 4 to 8, the Y axis from 5 to 9, and turn off the display of both axes.
10.6.28: Setting the Zone for Plot Functions
Syntax zone = tpzone()
zone = tpzone( name)
10.6.28.a: Description
Sets the zone number to be used for plotting functions that create Tecplot graphs of O-Matrix data. By default, the O-Matrix functions for creating
Tecplot graphs transfer the plot data to the first zone of the current data set. The tpzone function can be used to set which zone should be used for plot
functions. The tpzone function returns an integer scalar which specifies the zone being used. If present, the argument zone is a positive integer scalar
that specifies the zone to be used for subsequent plot commands.
10.6.28.b: Examples
See the tpcontour: 10.6.3 and tpsurface: 10.6.23 functions for examples of using the tpzone function.
10.6.29: Obtaining a Zone Name from Zone Number
Syntax name = tpzonename( zone)
10.6.29.a: Description
Returns the Tecplot zone name for the given zone number. The argument zone must be a positive integer scalar. The return value name is a character
row vector that specifies the name of the requested zone. If the return value name equals " " then the requested zone does not exist in the current data
set.
10.6.29.b: Examples
If you enter the following,
fName = [OM_INSTALL,"\example\tecplot\rainfall.plt"]
tpopen(fName)
tpzonename(2)
O-Matrix will open the rainfall sample data file from your distribution and display the zone name, for zone number 2.
ZONE 2
10.6.30: Obtaining a Zone Number from Zone Name
Syntax zone = tpzonenum(name)
10.6.30.a: Description
Returns the Tecplot zone number for the zone name specified by the character row vector name in the current data set. If the return value zone is less
than 1 then the specified zone name does not exist in the current data set.
10.6.30.b: Examples
If you enter the following,
fName = [OM_INSTALL,"\example\tecplot\rainfall.plt"]
tpopen(fName)
tpzonenum("ZONE 2")
O-Matrix will open the rainfall sample data file from your distribution and display the zone number, for zone, ZONE 2.
2
10.6.31: wtecplot - Writing and Creating Tecplot Files
Syntax
dll dll\tecplot.dll, wtecplot
wtecplot (file, version, title, vname, zname,
imax, jmax, kmax, point, elem)
ezone, zcolor, ...
10.6.31.a: Description
The wtecplot function provides low-level capabilities for writing Tecplot .PLT files in O-Matrix. Arguments use the same conventions as in Tecplot.
See your Tecplot documentation for details on the structure and content of .PLT files.
10.6.31.b: Arguments
All arguments to wtecplot are input values and are not modified by the function. See the documentation for rtecplot: 10.6.32 for a description of each
of the arguments.
10.6.31.c: Example
The following example demonstrates creating and reading a Tecplot .PLT data file.
clear
dll dll\tecplot.dll, rtecplot, wtecplot
#
x = seq(11) - 5.
y = x^2
z = x^3
#
rmfile("TEMP.OUT");
#
file = "TEMP.OUT"
title = "Demonstrating Tecplot I/O"
tecVersion = 6.5
vname = {"x", "y", "z"}
zname = "zone 1"
zcolor = "undef "
ezone = false
imax = 11
jmax = 1
kmax = 1
point = [x, y, z]
elem = fill(0, 0, 8)
wtecplot(file, ...
tecVersion, ...
title, ...
vname, ...
zname, ...
ezone, ...
zcolor, ...
imax, ...
jmax, ...
kmax, ...
point, ...
elem ...
);
Version = novalue
Title = novalue
Vname = novalue
Zname = novalue
Ezone = novalue
Zcolor = novalue
Imax = novalue
Jmax = novalue
Kmax = novalue
Point = novalue
Elem = novalue
rtecplot(file, ...
Version, ...
Title, ...
Vname, ...
Zname, ...
Ezone, ...
Zcolor, ...
Imax, ...
Jmax, ...
Kmax, ...
Point, ...
Elem ...
);
10.6.32: rtecplot - Reading Tecplot Files
Syntax
dll dll\tecplot.dll, rtecplot
rtecplot(file, version, title, vname, zname,
imax, jmax, kmax, point, elem)
ezone, zcolor, ...
10.6.32.a: Description
The rtecplot function provides low-level capabilities for reading Tecplot .PLT files in O-Matrix. Arguments use the same conventions as in Tecplot.
See your Tecplot documentation for details on the structure and content of .PLT files. Trailing blanks are removed from all character data read from
the input file. When multiple strings are combined in a single matrix, such as vname, trailing blanks are added so that all rows have the same length as
the longest string.
10.6.32.b: Arguments
The argument file is the only input value and is not changed by rtecplot. The input value of the other variables does not matter.
10.6.32.c: file
The first argument file is a character row vector specifying the name of the Tecplot file to read.
10.6.32.d: version
The second argument version is a real scalar representing the version number of Tecplot used to create this plot file. If the forward byte order version
number is not between 1 and 100, it is assumed that the byte order of each 4-byte value in the file is reversed.
10.6.32.e: title
The title argument is a character row vector.
10.6.32.f: vname
The vname argument is a character matrix with row dimension equal to the number of variables in the file. The i-th row of vname contains the name of
the i-th variable left justified and blank filled on the right.
10.6.32.g: zname
The zname argument is a character matrix with row dimension equal to the number of zones in the Tecplot file. The i-th row of zname contains the
name of the i-th zone left justified and blank filled on the right.
10.6.32.h: ezone
The argument ezone is a logical column vector with row dimension equal to the number of zones in the Tecplot file. If ezone(i) is true, the i-th zone is
a finite element block zone.
10.6.32.i: zcolor
The argument zcolor is character matrix with row dimension equal to the number of zones in the Tecplot file. The column dimension of zcolor is 6.
Possible values for a row are "black", "red", "green", "blue", "cyan", "yellow", "purple", "white" and "undef". The color name is right justified within
each row and blanks are used to fill out each row to 6 characters.
10.6.32.j: imax
The argument imax is an integer column vector with row dimension equal to the number of zones in the Tecplot file. If ezone(i) is true, imax(i)
specifies the number of rows of point that correspond to zone number i If ezone(i) is false, imax(i) specifies the maximum i index for the i-th zone. In
this case imax(i) * jmax(i) * kmax(i) is the number of rows of point that correspond to zone number i
10.6.32.k: jmax
The argument jmax is an integer column vector with row dimension equal to the number of zones in the Tecplot file. If ezone(i) is true, jmax(i)
specifies the number of rows of elem that correspond to zone i. If ezone(i) is false, jmax(i) specifies the maximum j index for the i-th zone.
10.6.32.l: kmax
The argument kmax is an integer column vector with row dimension equal to the number of zones in the Tecplot file. If ezone(i) is true, kmax(i)
specifies the type of the elements in zone i. The value 0 specifies triangles, 1 specifies quadrilaterals, 2 specifies tetrahedrons, and 3 specifies bricks. If
ezone(i) is false, kmax(i) specifies the maximum k index for the i-th zone.
10.6.32.m: point
The argument point is a real matrix with column dimension equal to the number of variables. Each row of point contains the value for all the variables
at a single data point. The data is stored in zone order. The data for zone 1 is first, then zone 2, etc. See imax above for how many rows of point
correspond to each zone.
10.6.32.n: elem
The argument elem is an integer matrix with column dimension equal to 8. Each row of elem defines an element for a finite element zone. The
elements for the first finite element zone come first, then the elements for the second finite element zone, etc. See jmax above for how many elements
are in each zone. The first column of elem specifies the index within the corresponding zone of the first point in the element. The second column
specifies the index of the second point and so on. The indices within each zone are numbered starting at one. If an element corresponds to a triangle
finite element zone (see kmax), only the first 3 columns of elem are significant for that element. For quadrilaterals and tetrahedrons only the first 4
columns are significant. For bricks, all 8 columns are significant.
10.6.32.o: Example
See the example in wtecplot: 10.6.31 for an illustration of creating and reading .PLT files.
10.6.33: A GUI for Manipulating Tecplot Data Files
Syntax include pltgui.oms
10.6.33.a: Description
interface by entering ReadTecplotDialog from the command line or selecting Read Tecplot Data from the Tools menu.
10.6.33.b: Example
If you enter
include pltgui.oms
O-Matrix will load functions for displaying the GUI for manipulating Tecplot files. If you continue the example by selecting
from the Tools menu O-Matrix will display the following dialog
The directory demo\plt in your Tecplot installation directory contains several sample .PLT files. If you continue the example above by pressing the
File button O-Matrix will display a file browser dialog. If you select the file cylinder.plt from the PLT directory the dialog will appear as:
The fields X:, Y:, and Zone: can be used to select variables from the selected file for creating plots. If you continue the example above by changing the
zone to d2, the x variable to X(M), the y variable to Y(M) and press the Plot button, O-Matrix will display the following plot:
The Load button can be used to display the contents of the current file in the Command window.
10.7: Data Visualizer for O-Matrix
10.7.a: Contents
Getting Started with Data Visualizer: 10.7.1
Transferring Data: 10.7.2
Saving Plots with Data: 10.7.3
Creating XY Plots: 10.7.4
Creating Image Plots: 10.7.5
Modifying the Data Visualizer Color Palette: 10.7.6
Creating Surface Plots: 10.7.7
Setting the Object to be Displayed by Data Visualizer: 10.7.8
10.7.1: Getting Started with Data Visualizer
10.7.1.a: Overview
The Data Visualizer (http://www.omatrix.com/datavis.html) is an add-on for O-Matrix (http://www.omatrix.com/overview.html) that enables the OMatrix language to transfer data to and interact with the Array Viewer visualization environment. This provides many ease-of-use and enhanced
graphic generation capabilities to the O-Matrix user:
Interactively create plots of O-Matrix data
Create attractive two- and three- dimensional plots that can be interactively rotated, scaled, and zoomed.
Display and edit data in a scrollable spreadsheet
Inquire about specific plot values using the mouse
Save data and graphs together in a single compact file
Save data in HDF or XML formats
Use HTML and HTML scripting languages to create dynamic applications for interacting with O-Matrix data and solutions
The Array Viewer is an interactive application for graphing and viewing structured, or hierarchical data sets. The Array Viewer component is bundled
Obtaining the full benefits of the O-Matrix Data Visualizer add-on requires at least a basic understanding of the Array Viewer data model. After you
have installed Array Viewer it is recommended that you review the documentation and examples that are installed with the Array Viewer
10.7.2: Transferring Data
Syntax avput(x, varName)
10.7.2.a: Description
Transfers the value of the integer, real, or double-precision -valued expression x to the Data Visualizer. The character vector varName specifies the
fully-qualified, hierarchy name to be used for x within the Data Visualizer.
10.7.2.b: Example
If, at the O-Matrix prompt you enter
avput( seq(3), "/X" )
the Data Visualizer will create a dataset named X at the root of the hierarchy. If the dataset X already exists it is overwritten. You may also create
variables nested within groups. For example, if you enter
avput(rand(2,2), "/MyData/Test1" )
the Data Visualizer will create a dataset named Test1 in the group /MyData. If a group within a specified hierarchy does not exist it is created.
10.7.3: Saving Plots with Data
Syntax avsave(fileName)
10.7.3.a: Description
Saves the current contents of the Data Visualizer to the file specified by the character row vector fileName. The suffix of the file name specified by
fileName must be either .h5 or .xml. If the suffix of the given file name is .h5, the contents of the viewer are saved as an HDF5 data file, or if the
suffix given is .xml, the contents are saved as an XML file.
When saving data, the Data Visualizer saves all data and information necessary for re-constructing the produced plots. This provides a convenient and
portable format for transferring and editing plots and data outside of O-Matrix. Data can be accessed by other tools and data and plots can be
previewed and modified with the free previewer without using O-Matrix.
10.7.4: Creating XY Plots
Syntax avplot(plotName, x, y)
10.7.4.a: Description
Creates a Data Visualizer plot for each column of y, where y is an integer, real, or double-precision matrix. The value x is an integer, real, or doubleprecision vector with the same row dimension as y. The character vector, plotName specifies the name of the group in which each data set and the
corresponding graph will be stored. If the group already exists its contents are overwritten, otherwise it is created. If the value of plotName is "/" then
all objects will be created in the root directory, otherwise the value of plotName must be a valid group name such as "/MyGroup" .
10.7.4.b: Example
If, at the O-Matrix prompt you enter
x = {1, 2, 3}
y = [{1, 2, 3}, {1, 4, 9}]
avplot("/Simple Plot", x, y)
The Data Visualizer will be invoked if not already open and display the following
The previewer simplifies the creation of custom plots by providing interactive dialogs for modifying plot styles and attributes. If you select the Edit
check box in the upper-left corner of the previewer, all of the editable objects of the graph are displayed.
See the Array Viewer documentation that was installed with the previewer for detailed instructions on interactively editing graphs.
10.7.5: Creating Image Plots
Syntax avimage(color source)
avimage(plotName, color source)
avimage(plotName,
color source, color format)
10.7.5.a: Description
Creates a Data Visualizer image plot of the matrix color source. The character row vector plotName specifies the name of the group in which the
image graph object is created. If the value of plotName is "/" then the graph is created in the root directory, otherwise the value of plotName must be a
valid group name such as "/ImagePlots".
If the type of data plotted by avimage is logical then the color palette for the group containing the plot is converted to a black and white palette. If
the type of data plotted by avimage is char then the color palette for the group containing the plot is converted to a gray scale palette.
By default avimage uses the Array Viewer color format type of "Range". (See the Array Viewer documentation for detailed description of color
formats.) If present, the argument color format must equal, "INDEX", "RANGE", "MONO", "RGBA", "RGBX", "ABGR", or "XBGR".
10.7.5.b: Example
If at the O-Matrix prompt you enter
avimage(rand(4,5));
The Data Visualizer will create the following graph
If you continue the example by entering
R = rand(12,18) * 1000
R = char( mod(R,256) )
avimage("/GrayScale", R)
The following graph will be created
10.7.6: Modifying the Data Visualizer Color Palette
Syntax avpalette(groupName, R, G, B)
10.7.6.a: Description
Modifies the color palette for the Array Viewer group specified by the character row vector groupName. The arguments R, G, and B must be 256
element column vectors with values between 0 and 256.
10.7.7: Creating Surface Plots
Syntax avsurface(plotName, color source)
10.7.7.a: Description
Creates a Data Visualizer surface plot of the data set specified by the character row vector color source. The character row vector plotName specifies
the name of the group in which the surface graph object is created. If the value of plotName is "/" then the graph is created in the root directory,
otherwise the value of plotName must be a valid group name such as "/SurfacePlots".
10.7.7.b: Example
If at the O-Matrix prompt you enter
avput({[1, 2], [3, 4]}, "/x")
avsurface("/SurfacePlots", "/x");
The Data Visualizer will create the following graph
Once you have created, and possibly edited a graph you can update the display by modifying its referenced data either interactively with the previewer,
or with the avput command. This enables the creation of animations and iterative data analysis. If you run the following script
clear
# total time, g(t1, t2) is "small" for |(t1, t2)| > T / 2
T = 4.
N = 512
dt = T / N
df = 1 / T
t = (seq(N) - N / 2 - 1) * dt
alpha = 5.
h = exp( - alpha * abs(t))
g = fillcols(h, N) % fillrows(h', N)
# the continuous transform of g(t1, t2) is given by
# G(f1, f2) = H(f1) * H(f2)
# where H(f) = 2 * alpha / ((2 * PI * f)^2 + alpha^2)
# is the discrete transform of g
G = real(fft2d(complex(g))) * dt * dt
D = maxs(G) - mins(G)
pPath = "/O-Matrix Surface/"
avput(log(G), [pPath,"log(G)"])
avsurface([pPath,"Log 2D fft"], [pPath,"log(G)"])
for i = 1 to 6 begin
M = log(G) + (rand(N,N)*i)/5.
avput(M, [pPath,"log(G)"])
avpath(["graph:",pPath,"Log 2D fft"])
sleep(1)
end
O-Matrix will create an animation of the 2-D FFT plot that concludes with the following graph.
10.7.8: Setting the Object to be Displayed by Data Visualizer
Syntax avpath(pathString)
10.7.8.a: Description
Sets the object specified by the character row vector pathString to be displayed in the Data Visualizer. The avpath function can be used to display
data, graph, or page objects within the viewer. If pathString starts with the characters, graph: the specified object must be a plot. If pathString begins
with page: the specified object must be a page object, otherwise pathString must begin with the character /.
10.7.8.b: Examples
If at the O-Matrix prompt you enter
avpath("/")
The Data Visualizer will displayed the root group of the currently displayed hierarchy. If at the O-Matrix prompt you enter
avput(rand(10,10), "/Data/rand")
avpath("/Data/rand")
the previewer will display the following
If you have created an image plot with the name /Image1/2D fft and you enter
avpath("graph:/Image1/2D fft")
the given image plot will be displayed.
The avpath command can be used to display, or run objects that contain embedded HTML code which can be used for creating dynamic, visual
datasets. If at the O-Matrix prompt you enter
avopen("AVsinecompute.h5")
avpath("page:/SineCompute")
the previewer will display a dynamic HTML page which uses data and graphs embedded in the file to create a dynamic graph. (Note that if the Edit
check box in the upper-left of the previewer is selected the previewer will display the page code, otherwise the page will be run)
11: User-Defined Functions
11.a: Contents
Defining Functions: 11.1
Returning from a Function: 11.2
Clearing Functions: 11.3
Defining Functions With Arguments: 11.4
Number of Arguments in a Function Call: 11.5
Defining Functions With Variable Numbers Of Arguments: 11.6
Using Variables And Constants With Functions: 11.7
Using Recursion: 11.8
Forward And Joint Reference Of Functions: 11.9
Functions As Arguments: 11.10
Defining Functions With Multiple Return Values: 11.11
Number of Return Values Corresponding to a Function Call: 11.12
Functions As Variables: 11.13
Local Variables: 11.14
Defining Local Functions: 11.15
Local Variable Functions: 11.16
Executing The Function Corresponding To A String: 11.17
Timing User-Defined Function Execution: 11.18
11.1: Defining Functions
Syntax function name()block
See Also function arguments: 11.10 , local functions: 11.15 , multiple return values: 11.11
11.1.a: Description
Defines the function name, which executes the commands in block: 5.2 .
11.1.b: Tutorial
A function is a set of commands that can be executed by entering the function name. Entering
will
clear
function f() begin
print "Hello World!"
end
define the function f. If you continue this
f
example by entering
O-Matrix will respond
Hello World!
11.2: Returning from a Function
Syntax return
return value
11.2.a: Description
The return statement terminates execution of the current function: 11.1 and returns execution to the routine that called the function. If value is
present, it is the value corresponding to the function in the calling routine.
11.2.b: Example
11.2.b.a: Multiple Return Points
There is an automatic return at the end of every function. You can define other return points using the return statement. If you enter
clear
function f(n) begin
if n == 0 then begin
print "cannot divide by", n
return
end
print "1. / n =", 1. / n
end
f(0)
O-Matrix will respond
cannot divide by 0
If you continue by entering
f(1)
O-Matrix will respond
1. / n = 1
11.2.b.b: Returning A Value
If value is present, it will be the value of the function name in the calling routine. If you enter
clear
function f() begin
return 5 * 6
end
print f
O-Matrix will respond
30
11.2.c: Reference
A return value cannot be specified in the return statement if the multiple return value: 11.11 syntax is used to define the function.
11.3: Clearing Functions
Syntax clear function name
11.3.a: Description
Allows the specified function name to be used for another purpose.
11.3.b: Tutorial
If you enter
clear
function f() begin
return 5
end
print f
O-Matrix will respond
5
If you continue by entering
clear f
f = 6
print f
O-Matrix will respond
6
11.4: Defining Functions With Arguments
Syntax function name(arguments) block
11.4.a: Description
Defines a function with one or more arguments.
The arguments list contains variables that are used to pass information to and from a function.
11.4.b: Tutorial
Entering
clear
function square(x) begin
return x * x
end
defines a function that returns the square of its argument. To evaluate the function at x = 3, enter
print square(3)
and O-Matrix will respond
9
A function can have any number of arguments. If you enter
clear
function hypotenuse(a, b) begin
return sqrt(a^2 + b^2)
end
hypotenuse(3., 4.)
O-Matrix will respond
5
11.4.c: Reference
If a variable name is passed as an argument (not a constant: 3.3 or an expression) the value of the variable can be changed inside of the function. For
example, entering
clear
x = 5
function f(y) begin
y = 6
end
f(x)
print x
results in
6
because the value of x is changed inside of the function. On the other hand, if you continue the example above by entering
const z = 4
f(z)
print z
O-Matrix will respond
4
because z is a constant. In addition, if you continue this example by entering
w = 3
f(w(1))
print w
O-Matrix will respond
3
because w(3) is an expression and not simply a variable name.
Note that in all cases above, the value of y, after the assignment of the function f, is 5.
11.5: Number of Arguments in a Function Call
Syntax nargin
11.5.a: Description
Returns the number of arguments in a function call. If you enter
clear
function f(a, b, c, d, e) begin
print nargin
end
f(2, 4, 6)
O-Matrix will respond
3
11.6: Defining Functions With Variable Numbers Of Arguments
Syntax arg(value)
11.6.a: Description
References the specified function argument, where value is an non-negative integer scalar.
11.6.b: Number Of Arguments
If a function call does not have multiple return values: 11.11 , the expression arg(0) is equal to the number of arguments in a function reference. If
you enter
clear
function f(a, b, c, d, e) begin
print arg(0)
end
f(2, 4, 6)
O-Matrix will respond
3
11.6.c: Referencing Arguments By Index
The expression arg(1) is equal to the first argument of the function, arg(2) is equal to the second argument, and so on.
If you enter
clear
function maximum() begin
imax = 1
for i = 2 to arg(0) begin
if arg(i) > arg(imax) then imax = i
end
return arg(imax)
end
maximum(1., 5, 2., 6)
O-Matrix will respond
6
11.6.d: Reference
If an argument is a simple variable name, you can assign a new value to the argument using this notation (see arguments, Reference: 11.4.c for a
discussion of a simple variable). For example, if you enter
clear
function f() begin
arg(2) = 3
end
x = 5
y = 6
f(x, y)
print x, y
O-Matrix will respond
5 3
11.7: Using Variables And Constants With Functions
Syntax global variable list
11.7.a: Description
Enables a function to access previously defined variables.
11.7.b: Tutorial
Variables that have global scope: 26.aj are not accessible within a function unless they are specified in a global statement. If you enter
clear
x = 5
function f() begin
x = 3
print x
end
f
O-Matrix will respond
3
The statement that assigned 3 to x created a variable x that has function scope: 26.aj ; i.e., its scope is limited to the function f. Outside of the function,
x has the value 5. Thus, if you continue the example above by entering
print x
O-Matrix will respond
5
You can use the global statement to access and modify variables that have global scope. If you enter
clear
x = 5
function f() begin
global x
x = 3
end
f
print x
O-Matrix will respond
3
Constants defined outside of any function do not need a global statement to be accessed within a function. If you enter
clear
const x = 5
function f() begin
print x
end
f
O-Matrix will respond
5
If a global statement is not within a function, it will make the corresponding variables accessible in all the subsequent functions within the current
file. If the file TEMP.OMS contains
global X, Y
function f() begin
print X
end
function g() begin
print Y
end
and at the command line you enter
clear
X = 1
Y = 2
include TEMP.OMS
f
O-Matrix will respond
1
If you then enter
g
O-Matrix will respond
2
11.7.c: Reference
If a global statement is not within a function, it must be within a file (not at the command line).
11.8: Using Recursion
See Also forward: 11.9 , for: 5.3 , while: 5.4 , goto: 5.6
11.8.a: Description
A recursive function references itself. The following function uses recursion to calculate the factorial of a number.
clear
function factorial(n) begin
if n==1 then return 1
return n * factorial(n - 1)
end
If you then enter the text above followed by
print factorial(3)
O-Matrix will respond
6
The reference factorial(3) caused the following evaluations:
function factorial(3) begin
if 3==1 then return 1
return 3 * factorial(2) # factorial(2) returns 2*1
end
function factorial(2) begin
if 2==1 then return 1
return 2 * factorial(1) # factorial(1) returns 1
end
function factorial(1) begin
if 1==1 then return 1
# returns 1
return 1 * factorial(0)
end
11.9: Forward And Joint Reference Of Functions
11.9.a: Description
A function can reference another function that is defined after it provided that the definitions are enclosed within a block: 5.2 . The following text
defines two functions that reference each other and are enclosed within one block:
clear
begin
function fac1(n) begin
if n==1 then return
return n * fac2(n end
function fac2(n) begin
if n==1 then return
return n * fac1(n -
1
1)
1
1)
end
end
If you then enter the text above followed by
print fac1(3)
O-Matrix will respond
6
The reference fac1(3) caused the following evaluations:
function fac1(3) begin
if 3==1 then return 1
return 3 * fac2(2)
end
function fac2(2) begin
if 2==1 then return 1
return 2 * fac1(1)
end
function fac1(1) begin
if 1==1 then return 1
return 1 * fac2(0)
end
# fac2(2) returns 2 * 1
# fac1(1) returns 1
# returns 1
11.10: Functions As Arguments
Syntax function argument name
11.10.a: Description
Defines an argument as a user-defined function.
11.10.b: Tutorial
A function definition: 11.4 may contain user-defined functions in its argument list. If you enter
clear
function trigdeg(function trigfun, degrees) begin
rad = PI * degrees / 180
end
function secant(x) begin
return 1. / cos(x)
end
you can then find the secant of 45 degrees by entering
print trigdeg(function secant, 45)
to which O-Matrix will respond
1.41421
Only user-defined functions can be arguments. For example, to use the sin function as an argument, you must make it a user-defined function. If you
enter
function sine(x) begin
return sin(x)
end
you then can find the sine of 45 degrees by entering
print trigdeg(function sine, 45)
to which O-Matrix will respond
0.707107
If a function is an argument, it cannot be accessed using arg: 11.6 notation. If you continue the example above by entering
function h() begin
print arg(1)
end
h(function secant)
O-Matrix will respond with an error message.
11.11: Defining Functions With Multiple Return Values
Syntax function [ variables ] = name ( arguments ) block
local function [ variables ] = name ( arguments ) block
[ variables ] = name ( arguments )
See Also defining functions: 11.1 , local functions: 11.15 , arg(0): 11.6 , nargin: 11.5 , nargout: 11.12
11.11.a: Description
Defines the function name, which executes the commands in block: 5.2 . The argument list: 11.4 for the function is specified by arguments. If the
local: 11.15 keyword is present in the syntax, the function can only be referenced in the present file; i.e. it has file scope: 26.aj .
Using the function definition syntax above, the return values of the function are specified by variables. Using the function definition syntax described
in Defining Functions: 11.1 a single return value is specified in the return: 11.2 statement.
11.11.b: Multiple Return Values
If you enter
clear
function
x =
y =
end
[u, v] =
print u,
[x, y] = f(a, b) begin
a^2
b^3
f(2, 3)
v
O-Matrix will respond
4 27
11.11.c: Determining Number Of Arguments And Return Values
The arg(0): 11.6 notation can be used to determine the number of arguments and return values for this call to the function. If you enter
clear
function [x, y] = f(a, b) begin
print arg(0)
x = a
end
[u, v] = f(5)
O-Matrix will respond
[ 1 , 2 ]
because there is one arguments and two return values in the call to the function f. If you continue by entering
[u] = f(5, 6)
O-Matrix will respond
[ 2 , 1 ]
because there are two arguments and one return value in the call to the function f. If you continue by entering
u = f(5, 6)
O-Matrix will respond
2
which is just the number of arguments because the number of return values is not specified in the call to the function. In this case only the first return
value is used. You can see this by entering
print u
to which O-Matrix will respond
5
11.11.d: Unspecified Return Values
If you assign a return value that is not requested by the call to the function, the operation will have no effect. In addition, if a return value is not
assigned a value, it will have the type "novalue" by default. For example, if you enter
clear
function
x =
z =
end
[u, v] =
print u,
[x, y, z] = f(a, b, c) begin
a
c
f(5, 6, 7)
v
O-Matrix will respond
5 novalue
11.11.e: Call By Value
Using the function definition syntax above, the value in the calling routine of the variables corresponding to arguments cannot be modified. This is
often referred to as call by value. On the other hand, using the function definition syntax described in arguments: 11.4.c , the value in the calling
routine of the variables corresponding to its This is often referred to as call by address.
If you enter
clear
function f(x) begin
x = 5
return x
end
function [y] = g(x) begin
x = 5
y = x
end
x = 4
print f(x)
O-Matrix will respond
5
If you continue by entering
print x
O-Matrix will respond
5
If you then enter
x = 4
print g(x)
O-Matrix will respond
5
if you continue by entering
print x
O-Matrix will respond
4
because only the local value of x with in the function g(x) was modified.
11.12: Number of Return Values Corresponding to a Function Call
Syntax nargout
11.12.a: Description
Returns the number of return values in a function call. If you enter
clear
function [x, y] = f(a, b) begin
x = nargout
end
[u, v] = f(5)
print u
O-Matrix will respond
2
because there are two return values in the call to the function f. If you continue by entering
f(5)
O-Matrix will respond
1
because there is only one return value corresponding to the call to f.
11.13: Functions As Variables
Syntax function new function = existing function ( implicit arguments )
See Also arguments: 11.4 , local variable functions: 11.16 , strings to functions: 11.17
11.13.a: Description
Creates a new function with the same or fewer arguments as an existing function. The implicit arguments are an identifier list: 26.t that is passed to the
new function without being specified in the call.
11.13.b: Tutorial
If you enter
clear
function residual(d, t, x) begin
return d - x * t
end
Time
= seq(3)
Data
= 2 * Time
function f = residual(Data, Time)
print f(1)
O-Matrix will respond
{
1
2
3
}
because f(1) is evaluated as residual(Data, Time, 1).
11.13.c: Reference
Functions defined in this way are referred to as variable functions: 26.r . The implicit arguments in a function assignment statement can themselves be
functions.
This feature is useful when using a general purpose utility that expects a function of a specific type. For example, you could use the variable function f
defined above to solve the problem
2
minimize |f(x)|
with respect to x
as follows
level
= 0
maxit
= 20
x0
= 1.
scale
= 1.
result = nlsq(function f, x0, scale, maxit, level)
xout
= result.col(coldim(result))
print xout
to which O-Matrix would respond
2
11.14: Local Variables
Syntax local variable = value
11.14.a: Description
Creates a new variable that has file scope: 26.aj and assigns it a value.
11.14.b: Tutorial
Local variables are limited in scope to the files in which they are defined. Suppose the file TEMP.OMS contains the commands
local y = 7
print y
and you enter the commands
y = 8
include TEMP.OMS
O-Matrix will respond
7
because the value of y within the file TEMP.OMS is 7. If you continue by entering
print y
O-Matrix will respond
8
If a function is defined after a local variable, the local variable is visible within the function. This is different variables that are not defined as local
because they require a global: 11.7 statement to make them visible within a function.
If the file TEMP.OMS contains
clear
local z = 10
function f() begin
print z
end
f
and you enter
include TEMP.OMS
O-Matrix will respond
10
11.14.c: Reference
A local statement can only appear in a file (not at the command line) and it cannot be inside of any function.
11.15: Defining Local Functions
Syntax local function name ( arguments ) block
See Also local variables: 11.14 , call back commands: 26.a , multiple return values: 11.11
11.15.a: Description
Defines a new function with the specified name that has file scope: 26.aj .
11.15.b: Tutorial
Local functions are limited in scope to the files in which they are defined. Suppose the file TEMP.OMS contains the commands
local function f() begin
return 1
end
print f
and at the O-Matrix prompt you enter
clear
function f() begin
return 2
end
include TEMP.OMS
O-Matrix will respond
1
because the version of f within the file TEMP.OMS returns the value 1. If you continue by entering
print f
O-Matrix will respond
2
because the f within TEMP.OMS is no longer visible.
11.16: Local Variable Functions
Syntax local function new function = existing function ( identifier list )
11.16.a: Description
Creates a new variable function: 11.13 with file scope: 26.aj .
11.16.b: Tutorial
Local variable functions are limited in scope to the file in which they are defined. If the file TEMP.OMS contains
local function f = g(x)
print f
and you enter the commands
clear
function g(x) begin
return x
end
function f() begin
return 2
end
x = 1
include TEMP.OMS
O-Matrix will respond
1
because the function call f within the file TEMP.OMS returns the value of g(x), which is 1. If you continue by entering
print f
O-Matrix will respond
2
because the function f within TEMP.OMS is no longer visible.
11.16.c: Reference
This syntax can only be used inside of a file (not at the command line).
11.17: Executing The Function Corresponding To A String
Syntax feval( function name, arg1, arg2, ... , argn)
11.17.a: Description
Executes the function with the specified name and with the arguments arg1, arg2, ... , argn.
11.17.b: Example
If you enter
function square(x) begin
return x^2
end
feval("square", 2)
O-Matrix will respond
4
11.17.c: Argument Functions
Using this syntax, you can use strings in place of functions both as variables: 11.13 and as arguments: 11.10 to other functions. If you continue the
example above by entering
function g(fun) begin
return feval(fun, 2)
end
g("square")
O-Matrix will respond
4
11.17.d: Multiple Returns
The feval syntax can be used with multiple return values. If you enter
function
x =
y =
end
[u, v] =
print u,
[x, y] = f(a, b) begin
a
b
feval("f", 1, 2)
v
O-Matrix will respond
1 2
11.17.e: Reference
The function name cannot correspond to a variable function and it cannot be local: 11.15 to a file. The argument function: 11.10 and variable function:
11.13 syntax do not have this restriction. In addition, using strings instead of functions as arguments and variables may not as fast to execute when
there is a very large number of functions defined in a program.
11.18: Timing User-Defined Function Execution
Syntax profile
profile( option)
time: 6.5.1
11.18.a: Description
If profiling is turned on, each time that a function returns, the amount of time that was spent in the function is added to the profiling time for that
function. This includes the time spent by other functions that were called by the function. O-Matrix function calls and returns will be slightly slower
when profiling is turned on.
11.18.b: No Option
If option is not present, the return value of the profile function is the current profiling information as a character matrix. Each row of the return value
corresponds to a function and contains three fields separated by commas. The first field is the total time corresponding to the function in seconds. The
second field is the name of the function. If the function is local to a file, the third field is the name of the file. If the function is not local to a file, the
third field is blank. The align: 9.1 function can be used to line up the fields in the return value. The sort: 9.20 function can be used to sort this
information.
11.18.c: On Option
If option is the character row vector "on", profiling is turned on and the total time for each function is initialized as zero.
11.18.d: Off Option
If option is the character row vector "off", profiling is turned off. This will free the memory that is used for profiling and it will make function calls
and returns slightly faster.
11.18.e: Example
If you enter
clear
function fac1(n) begin
if n == 1 then return 1d0
return n * fac1(n - 1)
end
function fac2(n) begin
fac = 1d0
for i = 1 to n begin
fac = fac * i
end
return fac
end
profile("on")
fac1(200);
fac2(200);
print profile
O-Matrix will respond
0.140,fac1,
0.010,fac2,
(Note that the times on your system will probably be different.) This shows that the fac2 function computes factorials faster than the fac1 function.
11.18.f: Reference
The clear: 3.2 and load: 20.8 commands turn profiling off.
If you call the profile function with no arguments when profiling is turned off, an error message will result.
You cannot call the profile function from within another function.
12: Linear Algebra
12.a: Contents
kron: 12.1
inv: 12.2
trace: 12.3
det: 12.4
logdet: 12.5
rank: 12.6
cond: 12.7
Kronecker Tensor Product
Inverting A Square Matrix
Computing The Trace Of A Matrix
The Determinant Function
Log Of The Determinant Of A Matrix
Computing The Rank Of A Matrix
Computing The Condition Number Of A Matrix
null: 12.8
Orthogonal Basis for Null Space of a Matrix
orth: 12.9
Orthogonal Basis for Range Space of a Matrix
pinv: 12.10
Moore-Penrose Pseudo Inverse of a Matrix
cholesky: 12.11
Cholesky Factoring Of A Matrix
lu: 12.12
Computing The LU Factorization Of A Matrix
svd: 12.13
Singular Value Decomposition
qr: 12.14
Simple Syntax for QR factorization
qred: 12.15
Alternate Syntax for Computing the QR Factorization
eigen: 12.16
Eigenvalues and EigenVectors of a General Matrix
geneig: 12.17
Generalized Eigenvalues and Eigenvectors of a General Matrix
eigsym: 12.18
Eigenvalues And Eigenvectors Of A Symmetric Matrix
symeig: 12.19
Computing The Eigenvectors Of A Symmetric Matrix
schur: 12.20
Schur Factorization
levinson: 12.21
Solving A Symmetric Toeplitz System Using Levinson's Algorithm
tridiag: 12.22
Solving A Tridiagonal System Of Linear Equations
BlockTriDiag: 12.23 Solves a Symmetric Block Tri-Diagonal System of Equations
12.1: Kronecker Tensor Product
Syntax kron(a,b)
12.1.a: Description
Returns the Kronecker tensor product of a and b where a and b are an integer, real, double-precision or complex matrices. The return value is a matrix
with the type that results from coercion: 4.4 between the types of a and b, its row dimension is equal to the product of the row dimensions of a and b,
and its column dimension is equal to the product of the column dimensions of a and b. If m is the row dimension of a and n is the column dimension of
a, the return value is equal to
a(1, 1) b
a(2, 1) b
:
a(m, 1) b
a(1, 2) b
a(2, 2) b
:
a(m, 2) b
...
...
a(1, n) b
a(2, n) b
:
:
...
a(m, n) b
12.1.b: Example
If you enter
a = {[1, 2], [3, 4]}
b = identity(2)
kron(a, b)
O-Matrix will respond
{
[
[
[
[
}
1
0
3
0
,
,
,
,
0
1
0
3
,
,
,
,
2
0
4
0
,
,
,
,
0
2
0
4
],
],
],
]
12.2: Inverting A Square Matrix
Syntax inv(x)
See Also \: 4.12 eigen: 12.16 , svd: 12.13 , qred: 12.15
12.2.a: Description
Returns the inverse of the matrix x, where x is a square: 26.ak real, double-precision, or complex matrix. The return value has the same type and
dimension as x.
12.2.b: Example
x = {[2., 1.], [1., 1.]}
inv(x)
returns
{
[ 1 , -1 ]
[ -1 , 2 ]
}
12.2.c: Algorithm
This function first forms a LU factorization of the matrix x and then solves for the inverse.
12.3: Computing The Trace Of A Matrix
Syntax trace( x)
See Also diag: 6.3.13 , cond: 12.7 , det: 12.4 , cond: 12.7
12.3.a: Description
Returns the sum of the diagonal elements of x, where x is an integer, real, complex or double-precision matrix. The return value is a scalar with the
same type as x.
12.3.b: Example
x = {[1, 2, 3], [4, 5, 6], [7, 8, 9]}
trace(x)
returns
15
12.4: The Determinant Function
Syntax det(A)
12.4.a: Description
Returns the determinant of the matrix A, where A is an integer, real, double-precision, or complex square matrix: 26.ak . The return value has the same
type as A.
If A is an integer matrix, the result is rounded to the nearest integer.
12.4.b: Example
x = {[1, 0], [0, 2]}
det(x)
returns
2
12.4.c: Algorithm
This function uses the logdet: 12.5 function which in turn uses an LU factorization to calculate the determinant.
12.5: Log Of The Determinant Of A Matrix
Syntax [s, d] = logdet(A)
12.5.a: Description
Computes the log of the determinant of the matrix A, where A is an real, double-precision, or complex square matrix: 26.ak .
s
is set to the sign of the determinant as a scalar with the same type as A. If the determinant is zero, s is zero, otherwise the absolute value of s is equal to
one and the determinant of A is equal to s * exp(d).
d
is set to the log of the absolute value of the determinant as a scalar with the same type as A. (If s is zero, the value of d is not defined.)
12.5.b: Example
x = {[1, 0], [0, 2]}
[s, d] = logdet(real(x))
print s * exp(d)
returns
2
12.5.c: Algorithm
This function uses an LU factorization of A, to compute the log of the determinant The function qred: 12.15 use as QR factorization to compute the
determinant.
12.5.d: Discussion
It is possible that the determinant can be a number outside the limits corresponding to the type of A, but the log of the determinant is with in the limits
(see REAL_MAX, REAL_MIN, DOUBLE_MAX, and DOUBLE_MIN, in autoexec: 24.1 for these limits).
12.6: Computing The Rank Of A Matrix
Syntax rank(x)
rank(x, tol)
12.6.a: Description
Returns the integer scalar that equals the rank of the matrix x, where x is an integer, real, double-precision, or complex matrix. The rank of a matrix is
computed as the number of absolute singular values of x that are larger than tol where tol is an integer, real, or double-precision scalar. If tol is not
present,
tol = maxdim * maxabs * eps
is used where, matdim is the maximum of the row and column dimension of x, maxabs is the maximum absolute singular value: 12.13 of x, and eps is
machine epsilon: 24.1 . If x is a real matrix, machine epsilon corresponds to single precision, otherwise it corresponds to double-precision.
12.6.b: Example
x = {[1, 0], [0, 2]}
rank(x)
returns
2
12.7: Computing The Condition Number Of A Matrix
Syntax cond(x)
12.7.a: Description
Returns the condition number of x, where x is a real, double-precision, or complex matrix. If x is complex, the return value is double-precision,
otherwise the return value has the same type as x.
12.7.b: Example
x = {[1., 0.], [0., 2.]}
cond(x)
returns
2
12.8: Orthogonal Basis for Null Space of a Matrix
Syntax y = null(x)
12.8.a: Description
Computes an orthogonal basis for the null space of the integer, real, double-precision or complex matrix x. Thus x * y is numerically near zero.
If x is an integer matrix, y is double-precision. Otherwise y has the same type as x. The number of rows in y is equal to the number of columns in x and
the number of columns in y is equal to the dimension of the null space of x. Each of the columns of the matrix y has norm: 4.15 one and the columns
are orthogonal; i.e.;
I = conj(y)' * y
where I is the identity matrix with the same number of columns as y.
12.8.b: Example
If you enter
x = { [1 , 1 , 1], [1 , 2 , 3] }
y = null(x)
y
{
0.408248
-0.816497
0.408248
}
Continuing with
y' * y
results in
1
and
x * y
results in
{
0
0
}
12.9: Orthogonal Basis for Range Space of a Matrix
Syntax
y = orth( x)
12.9.a: Description
Computes an orthogonal basis for the range space of the integer, real, double-precision or complex matrix x. Thus if z = x * w for some column
vector w, there is a column vector u such that z = y * u.
If x is an integer matrix, y is double-precision. Otherwise y has the same type as x. The number of rows in y is equal to the number of rows in x and the
number of columns in y is equal to the dimension of the range space of x. Each of the columns of the matrix y has norm: 4.15 one and the columns are
orthogonal; i.e.;
I = conj(y)' * y
where I is the identity matrix with the same number of columns as y.
12.9.b: Example
If you enter
x = {1 , 1 , 1}
y = orth(x)
y
{
-0.57735
-0.57735
-0.57735
}
Continuing with
y' * y
results in
1
12.10: Moore-Penrose Pseudo Inverse of a Matrix
Syntax
y = pinv( x)
y = pinv( x, tol)
12.10.a: Description
Computes the Moore-Penrose pseudo inverse of the integer, real, double-precision or complex matrix x. Thus
and
x * y * x = x
y * x * y = y
both x * y and y * x
are Hermitian.
If x is an integer matrix, y is double-precision. Otherwise y has the same type as x. The dimensions of y are equal to the dimensions of the transpose of
x.
12.10.b: Tolerance
If the integer, real or double-precision argument tol is present, it specifies the minimum absolute singular value of x that will be considered nonzero. If
tol is not present, the value
eps * max([rowdim(x), coldim(x)]) * smax
is used where smax is the maximum absolute singular value of x.
12.10.c: Example
If you enter
x = { [1 , 1], [2 , 2] }
y = pinv(x)
y
{
[ 0.1 , 0.2 ]
[ 0.1 , 0.2 ]
}
Continuing with
x * y * x
results in
{
[ 1 , 1 ]
[ 2 , 2 ]
}
and
y * x * y
results in
{
[ 0.1 , 0.2 ]
[ 0.1 , 0.2 ]
}
12.11: Cholesky Factoring Of A Matrix
Syntax cholesky(B)
[C, p] = cholesky( B)
12.11.a: Description
Returns an upper triangular: 26.ao matrix C that is a Cholesky factor for the matrix B; i.e.,
H
C
C = B
where B is a real, double-precision, or complex conjugate symmetric: 26.d matrix and the superscript H denotes the complex conjugate transpose. The
return value has the same type as B.
The matrix B is positive definite if
H
x
B x > 0
whenever x is a nonzero column vector with row dimension equal to the column dimension of B. If the argument p is not present and the matrix B is
not positive definite, and error message will result. If the argument p is present and the matrix B is positive definite, p is the integer scalar zero.
Otherwise, p is the smallest integer scalar such that B(1::p, 1::p) is not positive definite. In this case the return value C is a Cholesky factor for the
upper left (p-1) by (p-1) block of B.
12.11.b: Example
B = {[2., 1.], [1., 2.]}
cholesky(B)
returns
{
[ 1.41421 , 0.707107 ]
[ 0 , 1.22474 ]
}
12.11.c: Mlmode
In Mlmode: 25 , this function is called chol instead of cholesky. If you continue the example above by entering
mlmode
chol(B)
O-Matrix will respond
{
[ 1.41421 , 0.707107 ]
[ 0 , 1.22474 ]
}
omatrix
12.12: Computing The LU Factorization Of A Matrix
Syntax [L,U] = lu(X)
[L,U, P] = lu(X)
12.12.a: Description
Computes matrices L and U such that
X = L * U
where X is a real, double-precision or complex square matrix: 26.ak .
L
is a matrix with the same type and dimension as X. If the argument P is present, L is a lower triangular: 26.x matrix with ones along the diagonal. If the
argument P is not present, there is a permutation matrix: 26.ab P such that P * L is lower triangular with ones along the diagonal.
U
is an upper triangular: 26.ao matrix with the same type and dimension as X.
P
If the argument P is present, it is a permutation matrix: 26.ab and
P * X = L * U
(Note that this equation can also be written as X = (P' * X) * U and P' corresponds to the permutation matrix mentioned for the case where the
argument P is not present.)
12.12.b: Example
If you enter
x = {[1., .5], [.5, 1.]}
[l, u] = lu(x)
print l * u
O-Matrix will respond
{
[ 1 , .5 ]
[ .5 , 1 ]
}
which is equal to the matrix x. If you continue by entering
print l
O-Matrix will respond
{
[ 1 , 0 ]
[ .5 , 1 ]
}
If you then enter
print u
O-Matrix will respond
{
[ 1 , .5 ]
[ 0 , .75 ]
}
12.13: Singular Value Decomposition
Syntax svd(x)
svd(x, u, v)
[u, s, v] = svd(x)
[u, s, v] = svd(x, full)
See Also eigen: 12.16 , eigsym: 12.18 , schur: 12.20 , qred: 12.15 , lu: 12.12 , cholesky: 12.11
12.13.a: Description
Computes the singular values corresponding to the matrix x, where x is real, double-precision, or complex.
svd(x)
if this syntax is used, the return value is a column vector containing the singular vectors in descending magnitude order. It has the same type as x and
its length is equal to the minimum of the row and column dimension of x.
svd(x,
u, v)
if this syntax is used, the return value is the same as described above. In addition, the columns of u are set to the left singular vectors and the columns
of v are set to the right singular vectors. The input values of u and v have no effect and their output values have the same type as x.
[u,
[u,
s, v] = svd(x)
s, v] = svd(x, full)
if this syntax is used, the matrices u, and v are as described above. In addition, the diagonal matrix s has the singular values along its diagonal and in
descending magnitude order. If the argument full is the logical value true, or if it is not present, the full decomposition is computed. Otherwise the
economy decomposition is computed.
If m and n are the row and column dimensions of x, there is an m by m unitary matrix: 26.an U, an m by n diagonal matrix: 26.l S, and an n by n unitary
matrix V such that
x = U S conj(V)'
where conj(V)' is the complex conjugate transpose of V. In addition, the matrix S can be chosen so that its diagonal elements are
monotone decreasing: 26.y in absolute value; i.e.,
| S
|
>
| S
i, i
|
i+1, i+1
In the full decomposition case, if the arguments u and v are present, they are set to the matrices U and V respectively. If the argument s is present, it is
set to the matrix S, otherwise the return value of svd is equal to the diagonal of S.
In the economy decomposition case, the matrix u is set to the first min(m, n) columns of U, the matrix s is set to the submatrix defined by the
intersection of the first min(m, n) rows and columns of S, and the matrix v is set to the first min(m, n) columns of V. Thus it still holds that
'
x = u s conj(v)
12.13.b: Example
To find the singular values and vectors of the matrix
/ 2 1 \
\ 1 2 /
enter
x = {[2., 1.], [1., 2.]}
u = novalue
v = novalue
[u, s, v] = svd(x, u, v)
print s, u
which returns
{
[
[
}
{
[
[
}
3 , 0 ]
0 , 1 ]
-0.707107 , -0.707107 ]
-0.707107 , 0.707107 ]
If you continue this example by entering
u * s * v'
O-Matrix will respond
{
[ 2 , 1 ]
[ 1 , 2 ]
}
(Note that because x is not complex, v is not complex and it is not necessary to take the complex conjugate of v in the example above.)
12.13.c: Notes
12.14: Simple Syntax for QR factorization
Syntax [Q, R] = qr(X)
[Q, R] = qr(X, full)
[Q, R, E] = qr(X)
[Q, R, E] = qr(X, full)
See Also qred: 12.15 , lu: 12.12 , svd: 12.13 , schur: 12.20
12.14.a: Description
Computes matrices Q and R, such that
X = Q * R
where X is a real, double-precision or complex matrix.
Q
If the argument full is not present, or if it is true, Q is a unitary matrix: 26.an with the same type and row dimension as X. (See below for a discussion
of the case where full is false.)
R
is an upper triangular: 26.ao matrix with the same type and dimension as X.
E
If both E and full are present, E is a row vector with the same type and column dimension as X such that
X(:,E) = Q * R
(if E is complex, you will have to first convert it to integer, real or double-precision before using it in the expression above). If E is present and full is
not present, E is a permutation matrix: 26.ab with the same column dimension as X such that
X = Q * R * E
full
The argument full if a logical scalar If it is false and the column dimension of X is less than its row dimension, the output value of Q has the same
dimension as X and contains only the initial columns of a unitary matrix. Otherwise the entire unitary matrix is returned in Q.
12.14.b: Example
If you enter
x = {[.5, 1.], [1., .5]}
[q, r, e] = qr(x)
print q' * q
O-Matrix will respond
{
[ 1 , 0 ]
[ 0 , 1 ]
}
If you continue
q * r * e
O-Matrix will respond
{
[ 0.5 , 1 ]
[ 1 , 0.5 ]
}
12.14.c: Mlmode
In Mlmode: 25 , the argument full can be integer, real, or double-precision in which case non-zero corresponds to true and zero corresponds to false.
12.15: Alternate Syntax for Computing the QR Factorization
Syntax [Q, R, E, det] = qred(X, full)
qred(X, Q, R, E, det)
See Also qr: 12.14 , lu: 12.12 , svd: 12.13 , schur: 12.20
12.15.a: Description
Computes matrices Q, R, such that
X = Q * R
where X is a real, double-precision or complex matrix. Because there are so many forms for the syntax, only the two types of return forms are listed
above and the arguments E, det, and full are optional. The argument Q, R, E, and det are outputs and their input values do not matter.
Q
If the argument full is not present, or if it is true, Q is a unitary matrix: 26.an with the same type and row dimension as X. (See below for a discussion
of the case where full is false.)
R
is an upper triangular: 26.ao matrix with the same type and dimension as X.
E
If both E and full are present, the output value of E is a row vector with the same type and column dimension as X such that
X(:,E) = Q * R
(if E is complex, you will have to first convert it to integer, real or double-precision before using it in the expression above). If E is present and full is
not present, E is a permutation matrix: 26.ab with the same column dimension as X such that
X = Q * R * E
det
is a scalar with the same type as X and equal to the determinant of X.
full
The argument full if a logical scalar. If the argument full is false and the column dimension of X is less than its row dimension, the output value of Q
has the same dimension as X and contains only the initial columns of a unitary matrix. Otherwise the entire unitary matrix is returned in Q.
12.15.b: Example
If you enter
x = {[.5, 1.], [1., .5]}
[q, r, e, d] = qred(x)
print d
O-Matrix will respond
-.75
which is the determinant of x. If you continue by entering
q * r * e
O-Matrix will respond
{
[ 0.5 , 1 ]
[ 1 , 0.5 ]
}
12.16: Eigenvalues and EigenVectors of a General Matrix
Syntax eigen( x)
eigen( x,e)
[e,d] = eigen(x)
See Also eig: 12.16.c , geneig: 12.17 , eigsym: 12.18 , symeig: 12.19 , schur: 12.20 , svd: 12.13
12.16.a: Description
Computes the eigenvalues of the matrix x, where x is a square: 26.ak real, double-precision or complex matrix.
If the return value d is not present, the return value of eigen is a complex column vector, with the same row dimension as x, containing the
eigenvalues of x. If the return value d is present, it is set to a complex diagonal: 26.l matrix with the same dimension as x and with the eigenvalues
along its diagonal.
If the argument e is present the eigenvectors of x are also computed. The input value of e does not matter and its output value is a complex matrix
containing the eigenvectors. It has the same dimension as x. Each of the columns of e has norm one; i.e., for j between 1 and the row dimension of x
1 =
__________________________
2
2
\/ e(i, 1) + ... + e(i, n)
/
where n is the row dimension of x.
The eigenvalues and eigenvectors satisfy the equation
e * d = x * e
12.16.b: Example
If you enter
x = {[1., 1.], [2., 2.]}
[e, d] = eigen(x)
print e, d
O-Matrix will respond
{
[
[
}
{
[
[
(0.447214,0) , (-0.707107,0) ]
(0.894427,0) , (0.707107,0) ]
(3,0) , (0,0) ]
(0,0) , (2.22045e-016,0) ]
}
12.16.c: Mlmode
In Mlmode: 25 , this function is called eig instead of eigen. If in Mlmode you enter
x = [1., 1.; 2., 2.]
eig(x);
O-Matrix will respond
{
(3, 0)
(0, 0)
}
12.17: Generalized Eigenvalues and Eigenvectors of a General Matrix
Syntax lam = geneig(A, B)
[E, Lam] = geneig(A, B )
[E, Alp, Beta] = geneig(A, B )
12.17.a: Description
Computes the generalized eigenvalues of the matrix pair A, B, where a and b are square: 26.ak real, double-precision or complex matrix. The matrices
A and B must have the same dimension.
The return value lam is a complex column vector, with the same row dimension as A, containing the generalized eigenvalues.
The return value Lam is a complex diagonal: 26.l matrix with the same dimensions as A and with the generalized eigenvalues along its diagonal.
The return values Alp and Beta are a complex diagonal: 26.l matrices with the same dimensions as A and with
Beta * Lam = Alp
This is a more stable form for representing the generalized eigenvalues.
The return value E is a matrix with the same dimensions as A and with each of its columns corresponding to a generalized eigenvector. For each
eigenvector is scaled so that its Euclidean norm: 4.15 is one; i.e., for each i,
1 =
__________________________
2
2
\/ E(i, 1) + ... + E(i, n)
/
where n is the row dimension of A.
The return values satisfy the following two equations
A * E = B * E * Lam
A * E * Beta = B * E * Alp
and the vector lam is equal to the diagonal of Lam.
12.17.b: Example
If you enter
A
B
[E, Lam]
print E,
= {[1., 2.], [3., 4.]}
= identity(2)
= geneig(A, B)
Lam
O-Matrix will respond
{
[
[
}
{
[
[
}
(0.824565,0) , (0.415974,0) ]
(-0.565767,0) , (0.909377,0) ]
(-0.372281,0) , (0,0) ]
(0,0) , (5.37228,0) ]
Note that coercion: 4.4 converted the argument B from an integer matrix to a real matrix before the calculation was done.
12.17.c: Mlmode
In Mlmode: 25 , this function is called eig instead of geneig. If in Mlmode you enter
A
= {[1., 2.], [3., 4.]}
B
= eye(2)
[E, Lam] = eig(A, B)
E, Lam
O-Matrix will respond
{
[
[
}
{
[
[
}
(0.824565,0) , (0.415974,0) ]
(-0.565767,0) , (0.909377,0) ]
(-0.372281,0) , (0,0) ]
(0,0) , (5.37228,0) ]
12.18: Eigenvalues And Eigenvectors Of A Symmetric Matrix
Syntax eigsym(x)
eigsym(x,e)
12.18.a: Description
Computes the eigenvalues of the matrix x, where x is a real, double-precision or complex conjugate symmetric matrix: 26.am .
If the argument e is present the eigenvectors of x are also computed. The input value of e does not matter and its output value is a unitary matrix:
26.an , with the same type and dimension as x, containing the eigenvectors.
The return value is a column vector with the same type and row dimension as x containing the eigenvalues. If r is the return value,
e * diag(r) = x * e
where diag(r) is the diagonal matrix with r along its diagonal.
This routine computes the eigenvalues and eigenvectors directly. The routine symeig: 12.19 uses an SVD factorization to compute the eigenvectors.
12.18.b: Example
If you enter
x = {[3., 1.], [1., 3.]}
e = novalue
eigsym(x, e)
O-Matrix will respond
{
2
4
}
If you continue by entering
e * e'
O-Matrix will respond
{
[ 1 , 0 ]
[ 0 , 1 ]
}
(Note that the complex conjugate is not necessary because e has the same type as x and hence is a real matrix.) If you continue by entering
e * diag({2, 4}) - x * e
O-Matrix will respond
{
[ 0 , 0 ]
[ 0 , 0 ]
}
12.19: Computing The Eigenvectors Of A Symmetric Matrix
Syntax symeig(z)
See Also eigsym: 12.18 , svd: 12.13 , qred: 12.15 , cholesky: 12.11
12.19.a: Description
Computes the eigenvectors of z, where z is a conjugate symmetric matrix: 26.am . The return value is a unitary matrix: 26.an and each of its columns is
an eigenvector of z
This routine uses an SVD factorization to compute the eigenvectors. The routine eigsym: 12.18 computes the eigenvectors directly.
12.19.b: Example
z = {[1, 1 + 1i0], [1 - 1i0, 1]}
e = symeig(z)
(z * e.col(1)) / e.col(1)
returns
{
(2.41421,0)
(2.41421,0)
}
Note that this demonstrates that z times the first column of e is a scalar multiple of the first column of e.
12.20: Schur Factorization
Syntax B = schur(X)
[U, B] = schur(X)
See Also eigen: 12.16 , svd: 12.13 , qred: 12.15 , lu: 12.12
12.20.a: Description
Computes a schur factorization of the matrix square matrix: 26.ak x, where X is real, double-precision, or complex. A schur factorization of X is a pair
of matrices U and B such that
X = U B conj(U)'
where U is a unitary matrix: 26.an , the matrix B is in Schur form, and conj(U)' denotes the complex conjugate transpose of U.
The return values B and U have the same type and dimension as the matrix X. Note that because U is a unitary matrix, the matrices X and B have the
same eigenvalues.
12.20.b: Real Schur Form
A real or double-precision matrix is in schur form if it is block diagonal with each diagonal block either a 1 x 1 or 2 x 2 matrix. In addition each of
the 2 x 2 blocks has the form
/ a b \
\ c a /
where b c < 0. The eigenvalues
+
----a - \/ b c
corresponding to such a block is
The eigenvalues corresponding to a 1 x 1 blocks is the value on the diagonal.
12.20.c: Complex Schur Form
A complex matrix is in schur form if it is upper triangular: 26.ao with its eigenvalues on the diagonal of the matrix.
12.20.d: Example
You can compute a schur factorization of the matrix
/ 2 1 \
\ 1 2 /
by entering
X = {[2., 1.], [1., 2.]}
[U, B] = schur(X)
print B
which returns
{
[ 3 , 0 ]
[ 0 , 1 ]
}
If you continue this example by entering
U * B * U'
O-Matrix will respond
{
[ 2 , 1 ]
[ 1 , 2 ]
}
(Note that because X is not complex, U is not complex and it is not necessary to take the complex conjugate of U in the example above.)
12.21: Solving A Symmetric Toeplitz System Using Levinson's Algorithm
Syntax levinson(r, b)
12.21.a: Description
Uses Levinson's algorithm to solve the equation T x = b for x, where T is the Toeplitz matrix defined by
T
/
1
\
r
if i = j
= {
i,j
otherwise
|i - j|
The column vectors r and b must be real or double-precision and have the same length. The return value has the same number of rows as b and is real,
if both b and r are real and double-precision otherwise.
12.21.b: Example
The following is a Toeplitz system of equations:
/ 1 .5 \ / x
|
| | 1
|
| |
\ .5 1 / \ x
2
\
|
|
/
/ 1 \
= |
|
|
|
\ 2 /
If you enter
r = {.5d0, .25}
b = {1.d0, 2.}
levinson(r, b)
O-Matrix will respond
{
0
2
}
which is the value of the vector x that solves the equation above. Note that the vectors r and b must be of the same length even though the last
component of r is not used.
12.22: Solving A Tridiagonal System Of Linear Equations
Syntax tridiag( a, b, c, d)
12.22.a: Description
Returns a column vector x, with the same type and dimension as a, that solves the tridiagonal system of linear equations
a
x
+ b x
+ c x
= d
(i = 1, ... , n)
i i-1
i i
i i+1
i
n is the number of rows in a. The column vector a is real, double-precision,
where
dimension as a.
or complex. The vector b, c, and d have the same type and
For i = 1 the term involving a is not included in the equation above. Similarly, for i = n the term involving c is not included in the equation above.
Thus the values of a(1) and c(n) have no effect.
Warning: This method may result in division by 0 unless
|b | > |a
| + |c
|.
i
i-1
i+1
12.22.b: Example
a = {0., .2, .5}
b = {1., 1., 1.}
c = {.5, .2, .0}
d = {2., 3., 5.}
x = tridiag(a, b, c, d)
print x
returns
{
1
2
4
}
If you continue by entering
i = 2
a(i) * x(i - 1) + b(i) * x(i) + c(i) * x(i + 1)
O-Matrix will respond
3
12.23: Solves a Symmetric Block Tri-Diagonal System of Equations
Syntax [E, lam] = BlockTriDiag(B, C, R)
[E, lam] = BlockTriDiag(B, C, R, level)
12.23.a: Description
Solves for the sequence of matrices {e(k)} in the system of equations
/ b(1)
c(2)' 0
... 0 \ / e(1) \
/ r(1) \
| c(2) b(2) c(3)'
|
.
|
.
\ 0
...
0
c(N)
. | | e(2) |
| r(2)
. | | .
| = | .
| | .
|
| .
b(N) / \ e(N) /
\ r(N)
|
|
|
/
where each b(k) is a symmetric positive definite n by n matrix, each c(k) is an n by n matrix, each e(k) is an n by m matrix, and each r(k) is an n by
m matrix.
12.23.b: Assumptions
The sequence of matrices {d(k)}, generated by the algorithm, are assumed to be invertible. This is guarantee if the block tri-diagonal matrix above is
positive definite (see Vassilevski's article).
B
The real, or double-precision matrix B has n * N rows and n columns. The value of b(k) is equal to the following submatrix of B:
B.row((k-1) * n + 1, n)
C
The real, or double-precision matrix C has n * N rows and n columns. The value of c(k) is equal to the following submatrix of C:
C.row((k-1) * n + 1, n)
Note that the first n rows of C are not used.
R
The real, or double-precision matrix R has n * N rows and m columns. The value of r(k) is equal to the following submatrix of R:
R.row((k-1) * n + 1, m)
E
The real, or double-precision matrix E has n * N rows and m columns. The value of e(k) is equal to the following submatrix of E:
E.row((k-1) * n + 1, m)
lam
The real or double-precision scalar lam is set to the log of the determinant of the tri-diagonal matrix in the system of equations above.
level
Is an integer scalar specifying the level of tracing to do. If level < 0, no tracing is done. This is the default value for level if it is not present. The
block tri-diagonal matrix above is formed in memory and referred to a T below. This can be a very large matrix and is not formed unless level > 0.
Level
Label
Description
level > 1 type(T)
type of the matrix T
level > 1 cond(T)
condition number of the matrix T
level > 1 lam
block tri-diagonal calculation of logdet(T)
level > 1 logdet(T) direct calculation of logdet(T)
level > 2 E
block tri-diagonal calculation of solution of equation
level > 2 T \ R
direct calculation of solution of equation
level > 3 T
the large block tri-diagonal matrix
12.23.c: Example
clear
include BlockTriDiag.oms
#
function RandomPositive(n) begin
F = rand(n, n)
return F' * F
end
#
# dimensions of the problem
N = 4
n = 2
m = 1
#
# dimension values
T = fill(0d0, n * N, n * N)
Y = fill(0d0, n * N, m)
B = fill(0d0, n * N, n)
C = fill(0d0, n * N, n)
R = fill(0d0, n * N, m)
#
# Generate the sequences q(k), a(k), u(k), b(k), and c(k)
# as per the conditions in Lemma 7
#
# q(0) and a(0)
qkm = RandomPositive(n)
akm = rand(n, n)
for k = 1 to N begin
# generate random u(k), q(k), a(k), r(k)
uk = RandomPositive(n)
qk = RandomPositive(n)
ak = rand(n, n)
rk = rand(n, m)
#
bk = uk + inv(qkm) + ak * ( qk \ ak' )
ck = qkm \ akm'
#
# Fill in block tri-diagonal system of equations
kn = (k - 1) * n + 1
T.blk(kn, kn, n, n) = bk
if k > 1 then begin
T.blk(kn, kn - n, n, n) = ck
T.blk(kn - n, kn, n, n) = ck'
end
Y.blk(kn, 1, n, m) = rk
#
# store b(k), c(k), and r(k) in form for BlockTriDiag
kn = (k - 1) * n + 1
B.row(kn, n) = bk
C.row(kn, n) = ck
R.row(kn, n) = rk
end
#
# solve the block Tri-Diagonal System
level
= 3
[E, lam] = BlockTriDiag(B, C, R, level)
12.23.d: Reference
Algorithm 5 in Bell, B.M., The marginal likelihood corresponding to a discrete Gauss-Markov process IEEE Transactions on Signal Processing,
March 2000.
13: Curve Fitting, Optimization, and Derivatives
13.a: Curve Fitting
interp: 13.1 Piecewise Linear Interpolation In One Dimension
interp1: 13.2 Piecewise Linear Interpolation In One Dimension
lagrange: 13.3 Lagrange Polynomial Interpolation
polyfit: 13.4 Least Squares Fit of a Descending Polynomial to Data
smospl: 13.5 Smoothing Splines Of Arbitrary Order And Dimension
cubespl: 13.6 Compute Cubic Spline Coefficients
cubeval: 13.7 Evaluate A Cubic Spline
interp2: 13.8 Two Dimensional Piecewise Bilinear Interpolation
interp2: 13.9 Two Dimensional Piecewise Bilinear Interpolation (Mlmode)
13.b: Nonlinear Equations
snewton: 13.10 Newton's Method For Multiple Nonlinear Equations In One Variable
brent: 13.11
Brent's Method for Multiple Nonlinear Equations Without Derivatives
13.c: Optimization
conjdir: 13.18
Optimization Without Derivatives Using Conjugate Directions
linlsq: 13.12
Singular Linear Least Squares
linlsqb: 13.13
Linear Least Squares With Box Constraints
nlsq: 13.14
Nonlinear Least Squares
dnlsq: 13.15
Nonlinear Least Squares With Derivatives
nlsqbox: 13.16
Nonlinear least Squares With Box Constraints
dnlsqb: 13.17
Nonlinear Least Squares With Box Constraints and Derivatives
minline: 13.21
Minimization Along A Direction In A Vector Space
lemke: 13.22
Solving Linear Complementarity Problems
qpos: 13.23
Quadratic Programming with Inequality and Positive Constraints
qbox: 13.24
Quadratic Programming with Inequality and Box Constraints
qpro: 13.25
Quadratic Programming with Equality and Inequality Constraints
sqp: 13.26
Nonlinear Constrained Optimization by Successive Quadratic Programming
relative: 13.27
Extended Least Squares
13.d: Derivative Approximation and Testing
fordiff: 13.28 Forward Difference Derivative Approximation
cendiff: 13.29 Central Difference Derivative Approximation
autodiff: 13.30 Numerical Derivatives With Automatic Step Size Control
testder: 13.31 Testing Calculation of The Derivative of a Function
testhess: 13.33 Testing Calculation of The Hessian of a Function
13.1: Piecewise Linear Interpolation In One Dimension
Syntax interp(new_grid, old_table)
interp(new_grid, old_table, ind)
See Also interp1: 13.2 , interp2: 13.8 , lagrange: 13.3 , cubespl: 13.6
13.1.a: Description
Interpolates multiple variables onto a new grid of values. (The function interp1: 13.2 can handle the complex case with only one variable.) The
argument old_table is a real or double-precision matrix and each column corresponds to one of the variables on the old grid. The argument new_grid is
a real or double-precision column vector that contains the new grid of values for the independent variable. The argument ind is an integer scalar
between one and the column dimension of old_table that specifies the column corresponding to the independent variable in both table_old and the
return value. If ind is not present, the first column is used for the independent variable. The return value has the same row dimension as new_grid and
the same column dimension as old_table. The type of the return value is real, if both arguments are real, and double-precision otherwise.
Both the new and old grid of independent variables values (both new_grid and the independent variable column of old_table) must be
strictly monotone increasing: 26.y .
13.1.b: Example
The interp function uses a linear approximation between independent variable values in the old grid. For instance, suppose you recorded the
following temperature data:
time temperature
1:00 65
2:00 68
3:00 72
4:00 73
5:00 73
To interpolate the temperature at half-hour intervals, enter
old_table = { ...
[1., 65.], ...
[2., 68.], ...
[3., 72.], ...
[4., 73.], ...
[5., 73.] ...
}
new_grid = {1., 1.5, 2., 2.5, 3., 3.5, 4., 4.5, 5.}
interp(new_grid, old_table)
to which O-Matrix will respond
{
[
[
[
[
[
[
[
[
[
}
1 ,
1.5
2 ,
2.5
3 ,
3.5
4 ,
4.5
5 ,
65 ]
, 66.5 ]
68 ]
, 70 ]
72 ]
, 72.5 ]
73 ]
, 73 ]
73 ]
The first column in the matrix above is the time at half-hour intervals, and the second column is the interpolated values for temperature.
The interp function will extrapolate the linear approximation if an new grid value falls outside the range of old grid. If you continue the previous
example by entering
new_grid = {.5, 5.5}
interp(new_grid, old_table)
O-Matrix will respond
[ 0.5 , 63.5 ]
[ 5.5 , 73 ]
This approximates the temperature at 12:30 and 5:30, both of which lie outside the range of the old grid (the first column of table).
13.2: Piecewise Linear Interpolation In One Dimension
Syntax ynew = interp1(yold, xnew)
ynew = interp1(xold, yold, xnew)
13.2.a: Description
Piecewise linear interpolation of the row vector valued function of a scalar argument.
Let m be the number of rows in the integer, real, double-precision or complex matrix yold. (If yold is a row vector, m is the length of yold). The
argument xold is an integer, real, or double-precision vector of length m that is monotone: 26.y increasing or decreasing. If the argument xold is not
present, the column vector
T
(1, 2, ... , m)
is used in its place. The integer, real, or double-precision vector xnew specifies the values at which to interpolate the values of the function.
If yold is not a row vector, and i, j, k are positive integers such that
xold
<= xnew
<= xold
k
i
k+1
and 1 <= j <= m,
xnew - xold
i
k
ynew
= ------------ yold
+
i,j
xold - xold
k+1,j
k+1
k
xold
- xnew
k+1
i
------------xold - xold
k+1
k
yold
k,j
If yold is a row vector, and i, k are positive integers such that
xold
<= xnew
k
ynew
=
i
<= xold
i
k+1
xnew - xold
i
k
------------ yold
xold - xold
k+1
k+1
k
xold
+
- xnew
k+1
i
------------xold - xold
k+1
k
yold
k
If all the arguments are real, the return value is real. If y is complex, the return value is complex. Otherwise the return value is double-precision.
If yold is a row vector, the return value ynew has the same dimension as xnew. Otherwise it is a matrix with row dimension equal to the length of xnew
and with the same number of columns as yold.
13.2.b: Example
If you enter
xold = {1., 2., 3., 4.}
yold = {2., 4., 6., 8.}
xnew = {1.5, 2.5, 3.5}
ynew = interp1(xold, yold, xnew)
print ynew
{
3
5
7
}
13.2.c: Reference
Note that if an element of xnew is outside the range of the elements of xold, the values in the corresponding row of ynew is not defined.
13.3: Lagrange Polynomial Interpolation
Syntax lagrange(xd, yd, xi)
See Also polyfit: 13.4 , cubespl: 13.6 , interp: 13.1 , interp2: 13.8
13.3.a: Description
Returns the value of the Lagrange interpolating polynomial of a column vector valued function at a point. The interpolating polynomial has degree that
is one less than the column dimension of xd and is equal to the j-th column of yd at the j-th element of xd. The row vector xd specifies the argument
values that the polynomial interpolates. The real, double-precision, or complex matrix yd specifies the function values that the polynomial interpolates.
The parameters yd and xd must have the same number of columns. The scalar xi specifies the point at which to evaluate the polynomial. If yd is real or
double-precision, xd and xi must have the same type as yd. If yd is complex, xd and xi must be double-precision. The return value will have the same
type as yd.
13.3.b: Example
xd = [-1., 0., 2.]
yd = [+1., 0., 4.]
xi = 3.
print lagrange(xd, yd, xi)
returns
9
13.4: Least Squares Fit of a Descending Polynomial to Data
Syntax p = polyfit(x, y, n)
13.4.a: Description
Minimizes the linear least squares objective with respect to the polynomial coefficient vector p
N
2
----- |
n
1
|
>
| y - p * x - ... - p * x - p
|
----- | i
1
i
n
i
n+1 |
i = 1
where N is the length of the vectors x and y. The arguments x and
y are integer, real, double-precision or complex vectors with the same length. The
argument n is scalar and equal to an integer value. The returned value p is a row vector with the type that results from coercion: 4.4 between the type
of x and y (unless they are both integer in which case the return value is double precision).
13.4.b: Example
The following example fits a third degree polynomial to a sine wave over the interval [-pi , +pi]. The example plots the data values with the
symbol + an the fitted curve with a solid line (see the image below).
clear
x = PI * (seq(21) - 11) / 10d0
y = sin(x)
n = 3
p = polyfit(x, y, n)
v = polyval(p, x)
gplot(x, y, "plus")
gplot(x, v, "solid")
13.5: Smoothing Splines Of Arbitrary Order And Dimension
Syntax smosplc( m, y, t, sig, level)
smosplv( m, t, c, p, k)
13.5.a: Description
The routine smosplc returns coefficients that define a smoothing spline that interpolates a set of measurement values. The routine smosplv uses these
coefficients to evaluate the smoothing spline and its derivatives. Both smosplc and smosplv are defined in the file SMOSPL.OMS (not in SMOSPLC.OMS
or SMOSPLV.OMS). A spline passes though the specified values while a smoothing spline only approximates the specified values. Smoothing splines
are described in the article Surface fitting with scattered noisy data on Euclidean d-space and on the sphere, (1984) by G. Wahba, Volume 14, Number
1, of Rocky Mountain Journal of Mathematics.
The integer scalar m specifies the order of the partial derivatives that are minimized by the smoothing spline. The real or double-precision column
vector y contains the measurement values that the spline is smoothing. The matrix t has the same type and number of rows as y. The i-th row of t
specifies the value of the independent variable at which the value y(i) is measured. The column dimension of t is referred to as d and is the dimension
of the space on which the spline is defined. If d is even, 2 m - d must be greater than 0. If d is odd, 2 m - d must be greater than or equal to 0. The
vector sig has the same type and length as the vector y and each of the elements of sig is greater than 0. The value sig(i) is the standard deviation in
the measurement y(i). The integer scalar level specifies the level of tracing. If level > 1, the values lam, R(f), the derivative of R(f) with respect to
lam, and the change in lam are traced at each iteration. (a discussion of R(f) and lam follows below).
The derivative penalty term is defined by
/
------ /
\
|
J(f) = >
|
/
|
------ /
n
/
[
n(1)
n(2)
[ d
d
[ ------- ------[
n(1)
n(2)
[ d x
d x
1
2
n(m)
] 2
d
]
. . . ------- f(x) ]
dx
n(m)
]
d x
]
m
]
dimension d and the summation is over all vectors
where the integral is over Euclidean space of
between 1 and d. The average residual term is
N
1 ----2
2
R(f) = - >
{ y - f[t(i,:)] } / sig
N ----i
i
i = 1
where N is the number of rows in t and t(i,:) denotes the
of integers n that have m elements each of which is
i-th row of t. The smoothing spline s(x) solves the problem
minimize R(f) + lam J(f) with respect to f
where lam is adjusted so that the average residual, R(s), one equal to 1. If this cannot be accomplished, the message smosplc: average squared
normalized residual is not 1 is printed in the Command window.
A monomial on the space of dimension d is a function of the form
n(1) n(2)
n(d)
P (x) = x
x
. . . x
i
1
2
d
where n is a nonnegative integer vector of length d. The
degree of the monomial is the sum of the element of n. The index i above is used to denote a
single index counting of the different possible values for n.
The smoothing spline, s(x), is specified by the return value of smosplc. If c is the return value,
N
M
--------s(x) = >
c E[ |x - t(i,:)| ] + >
c
P (x)
----i
----i+N i
i = 1
i = 1
where M is the number of monomials on the space of dimension d and of degree
/
(2 m - d)
/ log(tau) tau
if d is even
E(tau) = {
\
(2 m - d)
\ tau
if d is even
less than m, and the function E(tau) is defined by
smosplv(m, t,
c, p, k)
Returns a column vector containing the value at the points specified by p of the derivative specified by k of the smoothing spline specified by m, t and
c. The vector c is the coefficient vector returned by smosplc. The arguments m and t must be the same as used in the call to smosplc that generated the
coefficient vector c. The matrix p has column dimension d and each row of p specifies a point at which to evaluate the smoothing spline. The integer
row vector k has column dimension d and all of its elements are nonnegative. It specifies the derivative of the spline that we are evaluating. If all of the
elements of k are 0, the spline is evaluated. In general, the i-th element of the return value is the function
k(1)
d
------k(1)
d x
1
evaluated at the
is not be finite.
k(2)
k(m)
d
d
------- . . . ------- s(x)
k(2)
k(m)
d x
d x
2
m
point p(i,:). If one of the elements of
k is nonzero. If a row of p is equal to a row of t the corresponding element of the return value
13.5.b: Example
The following program fits a smoothing spline to 20 data points of the form
y
= sin(t ) + w
i
i
i
w is a vector of independently
where
distributed normal random variables with mean zero and standard deviation .1. It plots the data and the smoothing
spline on a 100 point grid. It then plots the derivative of the smoothing and the analytic derivative of sin(t). Note that the points where the derivative
of the smoothing spline is not finite are not included in this plot (see the last sentence in the discussion of smosplv above).
clear
include smospl.oms
include isfinite.oms
N
= 20
sig
= fill(.1, N, 1)
t
= 2 * pi * seq(N) / real(N)
y
= sin(t) + sig % snormal(N, 1)
m
= 2
level = 1
c = smosplc(m, y, t, sig, level)
#
p
= 2 * pi * seq(100) / 100.
k
= 0
s
= smosplv(m, t, c, p, k)
gplot(t, y, "plus")
gplot(p, s, "solid")
#
k
= 1
ds
= smosplv(m, t, c, p, k)
ok
= isfinite(ds)
p
= p.row(ok)
ds
= ds.row(ok)
gplot(p, ds)
gplot(p, cos(p))
13.6: Compute Cubic Spline Coefficients
Syntax cubespl( x, d, b1, bn)
13.6.a: Description
Returns a matrix, with one less row than x and three columns, that defines a cubic spline through the data pairs (x(i), d(i)).
Let a, b, and c, be the first, second, and third columns of the return value. If z is between x(i) and x(i + 1), the cubic spline's value at z is equal to
3
a (z - x )
i
i
2
+
b (z - x )
i
i
+
c (z - x )
i
i
+
d
i
The column vector x must be either real or double-precision and x(i) < x(i+1) for all i. The vector d must have the same type and dimension as x.
The scalars b1 and bn must have the same type as x. The second derivative of the spline at x(1) 2 b1 and at x(n) is 2 bn, where n is the row
dimension of x.
The return value has the same type as x.
13.6.b: Example
The following program fits a cubic spline though the function
3
z
3
= 1 (z - 1)
2
+
3 (z - 1)
+
3 (z - 1) + d
1
3
= 1 (z - 2)
2
+
6 (z - 2)
+ 12 (z - 2) + d
2
Note that the second derivative of this function is 6 z. It follows from the equalities above that, the values of a, b, and c, are 1, 3, 3 in the first interval
and 1, 6, 12 in the second interval.
clear
#
x
= {1., 2., 3.}
d
= x^3
b1 = 6 * x(1) / 2
bn = 6 * x(3) / 2
cubespl(x, d, b1, bn)
13.7: Evaluate A Cubic Spline
Syntax cubeval( x, d, abc, p)
13.7.a: Description
Evaluates the cubic spline defined by x, d, and abc at the points specified by p. If a, b, and c are the first, second, and third columns of the matrix abc,
the cubic spline is defined as a function of z by
3
2
f(z) = a (z - x ) + b (z - x ) + c (z - x ) + d
i
i
i
i
i
i
i
all z between x(i) and x(i+1). The column vector x is real or double-precision
for
and x(i) < x(i + 1) for all i. The vector d has the same type
and dimension as x. The matrix abc has one fewer row than x, has three columns, and has the same type as x. The column vector p has the same type as
x and specifies the values of z at which to evaluate the cubic spline. The return value is a column vector with the same dimension as p, and its i-th
element is the value of f(z) at z = p(i). The return value has the same type and dimension as p.
13.7.b: Example
The program below evaluates a cubic spline that is equal to
3
3
z
= 1 (z - 1)
2
+
3 (z - 1)
+
6 (z - 2)
3
= 1 (z - 2)
+
3 (z - 1) + 1
2
+ 12 (z - 2) + 8
at the points 1.5 and 2.5. The corresponding value are their cubes namely 3.375 and 15.625.
clear
#
x
= {1., 2., 3.}
d
= {1., 8., 27.}
a
= {1., 1.}
b
= {3., 6.}
c
= {3., 12.}
abc = [a, b, c]
p
= {1.5, 2.5}
cubeval(x, d, abc, p)
13.8: Two Dimensional Piecewise Bilinear Interpolation
Syntax interp2( z, xz, yz, xi, yi)
13.8.a: Description
Returns the values of the piecewise bilinear interpolant that has the value z(i,j) at the point (xz(i), yz(j)) for i = 1 to the row dimension of xz
and j = 1 to the column dimension of yz. The (i,j)-th element of the return value is the value of the interpolant at (xi(i), yi(j)) for i = 1 to the
row dimension of xi and j = 1 to the column dimension of yi. The return value has the same type as z, the same row dimension as xi, and the same
column dimension as yi. Both the row and column dimensions of z must be greater than 1. The column vector xz has the same number of rows as z.
The row vector yz has the same number of columns as z.
The vectors xz, yz, xi, and yi are real or double-precision. In addition the vectors xz, and yz, are strictly monotone: 26.y increasing or decreasing. If z is
complex, the return value is complex. If all the arguments are real, the return value is real. Otherwise, the return value is double-precision.
13.8.b: Example
The example below uses interp2 to interpolate the function x y between 1 and 5 in both the x and y directions. The interpolation exactly matches the
function because x y is bilinear.
xz = {1., 5.}
yz = [1., 5.]
z = xz * yz
xi = {1., 2., 3., 4., 5.}
yi = xi'
interp2(z, xz, yz, xi, yi)
returns
{
[
[
[
[
[
}
1
2
3
4
5
,
,
,
,
,
2 , 3 , 4 , 5 ]
4 , 6 , 8 , 10 ]
6 , 9 , 12 , 15 ]
8 , 12 , 16 , 20 ]
10 , 15 , 20 , 25 ]
13.8.c: Reference
A function f(x,y) is bilinear if its second partial derivative with respect to x and its second partial derivative with respect to y is zero. The
interpolating function is continuous and it is bilinear over rectangles of the form
{(x,y) : xz
< x
i
< xz
and
i+1
yz
< y
i
< yz
}
i+1
13.9: Two Dimensional Piecewise Bilinear Interpolation (Mlmode)
Syntax interp2( xz, yz, z, xi, yi)
13.9.a: Description
Returns the values of the piecewise bilinear interpolant that has the value z(i,j) at the point (yz(i, 1), xz(1, j)) for i = 1 to the row dimension
of yz and j = 1 to the column dimension of xz. The (i,j)-th element of the return value is the value of the interpolant at (yi(i, 1), xi(1, j)) for
i = 1 to the row dimension of yi and j = 1 to the column dimension of xi. The return value has the same type as z, the same row dimension as yi, and
the same column dimension as xi. Both the row and column dimensions of z must be greater than 1. The matrix yz has the same number of rows as z.
The matrix xz has the same number of columns as z.
The vectors yz(:,1), xz(1,:), yi(:,1), xi(:,1) are integer, real, or double-precision. In addition, the vectors yz(:,1), xz(1,:), are strictly
monotone: 26.y increasing or decreasing. If z is complex, the return value is complex. If all the arguments are real, the return value is real. Otherwise
the return value is double-precision.
13.9.b: Example
The example below uses interp2 to interpolate the function x y between 1 and 5 in both the x and y directions. The interpolation exactly matches the
function because x y is bilinear.
If in Mlmode: 25 you enter
xz = [1. , 5.];
yz = xz';
z = yz * xz;
xi = [1. , 2. , 3. , 4. ,
yi = xi';
interp2(xz, yz, z, xi, yi)
5.];
O-Matrix will respond
{
[
[
[
[
[
}
1
2
3
4
5
,
,
,
,
,
2 , 3 , 4 , 5 ]
4 , 6 , 8 , 10 ]
6 , 9 , 12 , 15 ]
8 , 12 , 16 , 20 ]
10 , 15 , 20 , 25 ]
13.9.c: Reference
A function f(x,y) is bilinear if its second partial derivative with respect to x and its second partial derivative with respect to y is zero. The
interpolating function is continuous and it is bilinear over rectangles of the form
{(x,y) : xz
< x < xz
i
and
i+1
yz
< y < yz
i
}
i+1
13.10: Newton's Method For Multiple Nonlinear Equations In One Variable
Syntax snewton(function f, function df, fval, xini, mitr)
13.10.a: Description
Inverts a nonlinear scalar valued function of a scalar argument. The return value is a matrix x with the same type and dimension as fval, such that
f(x
) = fval
for i = 1, ... , M, and j = 1, ... , N
i,j
i,j
M and N are the row and column dimension of fval respectively. The matrix
where
xini has the same type and dimension as fval. The (i,j)-th element of
xini is the starting point when Newton's method is applied to solve the corresponding equation above.
The integer scalar mitr specifies the maximum number of Newton steps to attempt. If the method does not converge in mitr iterations, snewton returns
the current estimate. If you suspect this method might fail, you should check that the equations are solved by the return value. (Note the equations may
be solved for a subset of the indices.)
f (x )
The (i,j)-th element of the return value of f(x) is the value f(x(i, j)). The argument x and the return value f(x) have the same type and dimension
as fval.
df(x)
The (i,j)-th element of the return value of df(x) is the derivative of f evaluated at the point x(i, j). The argument x and the return value df(x) have
the same type and dimension as fval.
13.10.b: Example
The following example uses snewton to compute the square root of the integers between 1 and 4 (though we would normally use the sqrt: 6.1.2
function for this task). The initial starting points are random numbers between zero and one.
function f(x) begin
return x^2.
end
function df(x) begin
return 2. * x
end
fval
= real(seq(4))
xini
= rand(4, 1)
mitr
= 10
snewton(function f, function df, fval, xini, mitr)
returns
{
1
1.41421
1.73205
2
}
which are the square roots of 1, 2, 3, and 4, respectively.
13.11: Brent's Method for Multiple Nonlinear Equations Without Derivatives
Syntax [x, nfun] = brent(function f, fval, xini, step, mfun)
13.11.a: Description
Solves multiple nonlinear scalar valued equations of a scalar argument using a combination of bisection, linear interpolation and Brent's method. The
return value x is matrix with the same type and dimension as xini, such that
f
(x
) = fval
ij
ij
ij
The real, double-precision or complex matrix xini specifies the starting point when Brent's method is applied to solve the corresponding equation
above. The matrix fval has the same type and dimension as xini and specifies the right hand side of the equation. The scalar step has the same type as x
and specifies the initial step size with respect to x for bracketing the minimum.
The integer scalar mfun specifies the maximum number of evaluations of f to attempt. If the method cannot not converge in mfun calls to f, brent
returns the current estimate of x and with
nfun = mfun + 1
Otherwise, the return value of nfun is the number of evaluations of f that was used by brent
f (x )
The returns the element-by-element: 26.n a matrix valued function f(x) where x is a matrix with the same type and dimension as xini.
13.11.b: Example
The following example uses brent to compute the square roots of 1, 2, 3 and 4 (though we would normally use the sqrt: 6.1.2 function for this task).
clear
function f(x) begin
return x^2.
end
fval = double(seq(4))
xini = 1d0 + rand(4, 1)
step = .1d0
mfun = 100
[x, nfun] = brent(function f, fval, xini, step, mfun)
print x
returns
{
1
1.41421
1.73205
2
}
which are the square roots of 1, 2, 3, and 4 respectively.
13.12: Singular Linear Least Squares
Syntax linlsq(A, b, bound)
13.12.a: Description
Returns a vector x, that solves the problem
2
minimize | A x - b |
with respect to x
The matrix A is real, double-precision, or complex, b is a column vector with the same type and row dimension as A, and bound is a scalar with the
same type as A such that absolute singular values of the matrix A that are less than bound are replaced by 0 before solving the minimization problem. If
A is not complex, bound must have the same type as A. If A is complex, bound must be double-precision. The returned vector, x, has the same type as
A.
If more than one solution exists, the solution of minimum norm is returned (i.e., the value of x that minimizes |x| over the set of solutions).
The operation "\" uses a QR factorization to solve similar problems. If the rank of A is less than both its row and column dimension, the "\" operator
will generate an error if you compute A \ b. The linlsq function can solve such problems.
13.12.b: Example
A
= {1., 1.}
b
= {1., 2.}
eps = 1e-7
linlsq(A, b, eps)
returns
1.5
13.13: Linear Least Squares With Box Constraints
Syntax linlsqb( A, r, eps, xini, xlow, xup)
linlsqb( A, r, eps, xini, xlow, xup, active)
13.13.a: Description
Returns a vector that solves the problem
minimize |A x - r|^2 with respect to x
such that xlow(i) < x(i) < xup(i)
where the matrix A is real or double-precision, the column vector r has the same type and row dimension as A, and the scalar eps is such that singular
values of A that are less than eps are replaced by 0 in the minimization problem. The column vector xini specifies the initial point at which to start the
minimization. It must have the same number of rows as A has columns, and it must have the same type as A. The column vectors xlow and xup must
have the same type and dimension as xini. The return vector has the same type and dimension as xini.
If more than one solution exists, the solution of minimum norm is returned: the solution that minimizes |x| over the set of solutions.
If the argument active is present, its input value does not matter and its output value is an integer row vector with the same length as xini that specifies
which constraints are active at the solution. If the output value of active(i) is -1, the constraint xlow(i) < x(i) is active. If the output value of
active(i) is +1, the constraint x(i) < xup(i) is active. If neither of these constraints are active, the output value of active(i) is 0.
13.13.b: Example
The following example solves the problem
minimize
(x(1) - 4)^2 + (10 * x(2) - 30)^2 + (100 * x(3) - 200)^2
subject to -3 < x(1) < +3
-2 < x(2) < +2
-1 < x(3) < +1
The solution to this problem is x equals to the transpose
A = diag([1., 10., 100.])
r = {4., 30., 200.}
eps = 1e-7
xini = {0., 0., 0.}
xlow = {-3., -2., -1.}
xup = {3., 2., 1.}
linlsqb(A, r, eps, xini, xlow, xup)
of (3, 2, 1). If you enter
O-Matrix will respond
{
3
2
1
}
13.13.c: Restrictions
Every element of the upper limit xup must be strictly greater than the corresponding element of the lower limit xlow.
13.14: Nonlinear Least Squares
Syntax nlsq(function f, x0, scale, maxit, level)
13.14.a: Description
Uses the Gauss-Newton method to solve the problem
2
minimize |f(x)|
with respect to x
The function call f(x) returns a column vector with the same type as x0 provided that x has the same type and dimension as x0. The real or doubleprecision column vector x0 specifies the point at which to start the Gauss-Newton method. The vector scale has the same type and dimension as x0;
scale(i) is the maximum absolute change in x(i) per iteration, and .0001 scale(i) is the central difference step size used to approximate the
partial derivative of f with respect to x(i). The integer scalar maxit specifies the maximum number of iterations to try before giving up on
convergence. The integer scalar level specifies the amount of tracing within this function. If level > 1, the value of |f(x)|^2 is printed at each
iteration.
The vector scale also specifies convergence criteria. Convergence is accepted when the absolute change in x(i) between iterations is less than
.0001 scale(i) for all i.
The return value is a matrix with i-th column equal to the value of x at the beginning of the i-th iteration. The return value has the same type and row
dimension as x0. The last column of the return value is the approximate solution.
13.14.b: Example
The following program minimizes the function
f(x) =
with respect to
2
[exp(x ) - exp(1)]
+ [exp(x )
1
2
x. The resulting value of x is (1, 2).
2
- exp(2)]
clear
#
function f(x) begin
return {exp(x(1)) - exp(1.), exp(x(2)) - exp(2.)}
end
level = 0
maxit = 20
x0
= {0., 0.}
scale = {1., 1.}
result = nlsq(function f, x0, scale, maxit, level)
xout
= result.col(coldim(result))
print xout
13.15: Nonlinear Least Squares With Derivatives
Syntax dnlsq(function fval, xini, scale, eps, maxit, level)
13.15.a: Description
Uses the Gauss-Newton method to solve the problem
2
minimize |f(x)|
with respect to x.
If analytic derivatives of f(x) are not available, the function nlsq: 13.14 can be used to solve this problem.
13.15.b: xini
The real or double-precision column vector xini specifies the point at which to start the Gauss-Newton method.
13.15.c: scale
The vector scale has the same type and dimension as xini, and scale(i) is the maximum absolute change in x(i) per iteration. Every element of scale
must be greater than 0.
13.15.d: eps
The scalar eps has the same type as xini. Convergence is accepted if the maximum absolute change in x(i) is less than eps times scale(i) for all i.
13.15.e: maxit
The scalar integer maxit specifies the maximum number of iterations to try before giving up on convergence.
13.15.f: level
The scalar integer level specifies the level of tracing inside dnlsq. If level > 1, the value of |f(x)|^2 is printed at each iteration.
13.15.g: fval
13.15.g.a: fval(x, fout)
In the call fval(x, fout) the vector x has the same type and dimension as xini and specifies the point at which to evaluate f(x). The input value of fout
has no effect, and its output value is the value of f(x) as a column vector with the same type as x.
13.15.g.b: fval(x, fout, dfout)
In the call fval(x, fout, dfout) the arguments x and fout have the same meaning as above. The input value of dfout has no effect and its output value
is the derivative of f with respect to x and has the same type and row dimension as fout and a column dimension equal to the row dimension of x. The
(i,j)-th element of dfout is the derivative of the i-th component of f(x) with respect to the j-th component of x.
13.15.h: Return Value
The (i+1)-th column of the return value is the value of x at the i-th iteration. (The first column contains the initial value of x.) The return value has
same type and row dimension as xini. Its column dimension is equal to the number of iterations plus 1.
13.15.i: Example
The program below solves the problem
minimize
10
---->
[ x exp(- x t )
----1
2 i
i = 1
2
- y
]
with respect to x
i
where
y
= .5 exp(- t ) and
i
The solution is x = {.5, 1.}.
i
t
= i / 10
i
clear
#
const t = seq(10) / 10.
const y = .5 * exp(-t)
#
function fval(x, fout, dfout) begin
#
fout
= x(1) * exp(-x(2) * t) - y
if arg(0) < 3 then return
#
d1
=
exp(-x(2) * t)
d2
= -x(1) * exp(-x(2) * t) % t
dfout
= [d1, d2]
end
xini
= {2., 2.}
scale = {.5, .5}
eps
= 1e-4
maxit = 10
level = 0
x
= dnlsq(function fval, xini, scale, eps, maxit, level)
xout
= x.col(coldim(x))
print xout
13.16: Nonlinear least Squares With Box Constraints
Syntax nlsqbox(function f, xini, xlow, xup, maxit, level)
13.16.a: Description
Uses the Gauss-Newton method to solve the problem
minimize
such that
2
|f(x)| with respect to x
xlow < x < xup
i
i
i
f(x) returns a column vector with
The function call
the same type as xini provided that x has the same type and dimension as xini. The real or doubleprecision column vector xini specifies the point at which to start the Gauss-Newton method. The vector xlow specifies the lower limits for the
minimization problem and has the same type and dimension as xini. The vector xup specifies the upper limits for the minimization problem and has the
same type and dimension as xini. The integer scalar maxit specifies the maximum number of iterations to try before giving up on convergence. The
integer scalar level specifies the amount of tracing within this function. If level > 1, the value of |f(x)|^2 is printed at each iteration.
The return value is a matrix with i-th column equal to the value of x at the beginning of the i-th iteration. The return value has the same type and row
dimension as xini. The last column of the return value is the approximate solution.
The central difference step size .0001[xup(i) - xlow(i)] is used for approximating the partial derivative of f with respect to x(i). Convergence is
accepted when the absolute change in x(i) between iterations is less than .0001[xup(i) - xlow(i)] for all i.
13.16.b: Example
The following program minimizes the function
f(x) =
with respect to
2
[exp(x ) - exp(1)]
+ [exp(x )
1
2
x and subject to the constraints
-1 < x < +1
and
-1 < x < +1
2
- exp(2)]
1
2
The optimal value for x is (1, 1).
clear
#
function f(x) begin
return {exp(x(1)) - exp(1.), exp(x(2)) - exp(2.)}
end
level = 0
maxit = 20
xini
= {0., 0.}
xlow
= {-1., -1.}
xup
= {+1., +1.}
result = nlsqbox(function f, xini, xlow, xup, maxit, level)
xout
= result.col(coldim(result))
print xout
13.17: Nonlinear Least Squares With Box Constraints and Derivatives
Syntax dnlsqb(function fval, xini, xlow, xup, delta, maxit, level)
13.17.a: Description
Uses the Gauss-Newton method to solve the problem
minimize |f(x)|^2 with respect to x
such that xlow <= x <= xup
The return value of dnlsqb is a value of x that approximates
the solution of the optimization problem. The return value has the same type and
dimension as xini.
The function calls fval(x, f_out) and fval(x, f_out, df_out) evaluate f(x) and its derivative. The vector x has the same type and dimension as xini.
It specifies the point at which to evaluate f(x). The input value of f_out does not matter. Its output value is f(x) as a column vector with the same
type as x. If df_out is present, its input value does not matter. Its output value is the derivative of f(x) as a matrix with the same type and row
dimension as f_out, and column dimension equal to the row dimension of x. The element df_out(i, j) is the derivative of the i-th component of
f(x) with respect to the j-th component of x.
The real or double-precision column vector xini specifies the point at which to start the Gauss-Newton method. The a column vector xlow has the same
type and dimension as xini. It specifies the lower limit for the minimization problem. The a column vector xup has the same type and dimension as
xini. It specifies the upper limit for the minimization problem. The scalar delta has the same type as xini. Convergence is accepted if for each i,
|x(i) - xmin(i)| < delta * (xup(i) - xlow(i))
where xmin is a minimizer of the objective function. Convergence is also accepted is the absolute change in |f(x)|^2 is less than delta times its value.
The integer scalar maxit specifies the maximum number of iterations to try before giving up on convergence.
The integer scalar level specifies the level of tracing inside of dnlsqb. If dnlsqb fails to converge, the message "dnlsqb failed to converge" is printed.
If level > 1, the messages "begin dnlsqb" is printed before the first iteration and if the method converges, "dnlsqb converged" is printed at the end. In
addition, the value of |f(x)|^2 is printed at each iteration. If level > 2, the value of x is printed at each iteration.
13.17.b: Example
The example below solves the problem
minimize [exp(x(1)) - exp(1.)]^2 + [exp(x(2)) - exp(2.)]^2
with respect to x such that
-1 < x(1) < +1
-1 < x(2) < +1
The solution to this problem is x(1) = 1 and x(2) = 1.
clear
function fval(x, f_out, df_out) begin
f_out = {exp(x(1)) - exp(1.), exp(x(2)) - exp(2.)}
if arg(0) >= 3 then ...
df_out = diag(exp(x))
end
xini
= { 0., 0.}
xlow
= { -1., -1.}
xup
= { +1., +1.}
delta = 1e-4
maxit = 10
level = 2
argmin = dnlsqb(function fval, xini, xlow, xup, delta, maxit, level)
print "argmin' =", argmin'
13.18: Optimization Without Derivatives Using Conjugate Directions
Syntax [xout, nout] = conjdir(function f , xin, step, mitr, level)
13.18.a: Description
Uses a variation of Powell's conjugate direction method to minimize the function f(x) with respect to x.
f(x)
this function call returns the value of the objective function at x; i.e., f(x). The argument x has the same type and dimension as xin.
xin
The real or double-precision column vector xin specifies the initial estimate for the value of x that minimizes f(x).
step
The column vector step has the same type and dimension as xin. The minimization process has converged when the absolute change in x(i) is less
than or equal to step(i) for all i. All of the elements of step must be greater than 0.
mitr
The integer scalar mitr specifies the number of iterations of the conjugate gradient method to try before giving up on convergence.
level
The integer scalar level specifies the amount of tracing to do inside of conjdir:
Case
level > 1 f(xitr) objective function for current iteration
level > 2 xitr'
value of x for current iteration
level > 3 nf
number calls to f during line search
level > 3 beta
a step factor during line search
level > 3 f(x)
an objective function value during line search
level > 3 bmin
final step factor during line search
level > 3 fmin
final objective function value during line search
xout
If nout is not present, the ith column of the return value xout is the value of x at the ith iteration. Otherwise the return value xout is the value of x at
the last iteration. The return value xout has the same type and row dimension as xin.
nout
The return value nout is optional. If it is present, it contains the number of iterations required for convergence. If nout is present and convergence
cannot be achieved, the return value of nout is mitr+1 and xout is the best value of x so far. If nout is not present and convergence cannot be achieved,
the return value of xout is equal to novalue: 6.3.16 .
13.18.b: Example
The program below solves the problem
2
minimize (x
- 1)
2
+
1
The solution to this problem is
(x
- 2)
1
x = {1, 2}
with respect to x
clear
function f(x) begin
return (x(1) - 1.)^2 + (x(2) - 2.)^2
end
level = 0
mitr = 20
xin
= {0., 0.}
step = {.01, .01}
[xout, nout] = conjdir(function f, xin, step, mitr, level)
print "nout =", nout
print "xout'=", xout'
13.19: Optimization Using the Nelder Mead Simplex Method
Syntax [xout, nf] = neldermead(function f, ...
xin, dx, xtol, ftol, mfval, level)
13.19.a: Description
Uses a variation of the Nelder Mead simplex method is used to minimize a function of multiple variables without derivatives.
xout
is a vector with the same dimension as xin that contains the approximate minimizer of f(x).
nf
is the number of function evaluations used by neldermead. If more than mfval evaluations are required for convergence, nf is set to mfval + 1 .
f(x)
This function call returns a scalar value where x is a real or double-precision column vector with the same length as xin.
xin
The real or double-precision column vector xin specifies the location to start the minimization procedure at.
dx
The real or double-precision vector dx has the same dimension as xin and specifies the points in the initial simplex relative to simplex point xin. The
j+1-th point in the initial simplex is displaced dx(j) units from xin in the j-th coordinate direction. All the elements of dx must be greater than zero.
(Note that the current simplex size is used to detect convergence relative to the value of xtol.)
xtol
The real or double-precision vector xtol has the same dimension as xin and specifies the convergence criteria in argument space. It must be greater than
or equal to zero.
ftol
The real or double-precision scalar ftol specifies the convergence criteria in function value units. It must be greater than or equal to zero.
mfval
The integer scalar mfval specifies the maximum number of function evaluations to attempt. If this number is exceeded without either of the
convergence criteria being met,
nf = mfval + 1
level
The integer scalar level specifies the amount of tracing that is printed during the minimization. The following table corresponds the value of level with
what variables are printed and what their meaning is. Note that every line that is printed by this routine begins with the text neldermead:.
Level
level > 1 dia
diameter of the simplex
level > 1 nf
number of function evaluations
level > 1 sf
function values on simplex vertices
level == 2 xmin
minimum x values in simplex
level == 2 xmax
maximum x values in simplex
level == 3 sx
all of the vertices in the simplex
13.19.b: Example
The following example minimizes the function
f(x) = exp[(x
Note that the value of
- 1)^2 ] + (x - 2)^2
1
2
x that minimizes this function
is
/1\
\2/
clear
function f(x) begin
return exp( (x(1) - 1.)^2 ) + (x(2) - 2.)^2
end
one
= {1., 1.}
xin
= 0e0 * one
dx
= 1e0 * one
xtol = 1e-3 * one
ftol = 1e-6
mfval = 100
level = 0
neldermead(function f, xin, dx, xtol, ftol, mfval, level)
13.19.c: Mlmode
13.19.c.a: Syntax
In Mlmode: 25 , this function is accessed using the following syntax:
fmins(f, xin, options)
where the argument options is optional. In addition, each call of the form f(x) in neldermead is translated to a call of the form feval(f, x). The
following table has the correspondence between that arguments to neldermead and options. The value zero for an element of options is equivalent to
using the default value below:
fmins
Default
options(1) 0
level
options(2) 1e-4
all elements of xtol
options(3) 1e-4
ftol
options(14) 100 n-variables mfval
In addition the argument dx is given by
/ 100 xtol
dx
= <
j
if xin
= 0
j
otherwise
j
\ .1 xin
j
13.19.c.b: Example
The following example minimizes the function
f(x) = (x
- 1)^2 + (x
1
- 2)^2
2
Note that the value of x that minimizes this function is
If the
/1\
\2/
file fun.m in the current directory contains the text
function y = fun(x)
y = exp( (x(1) - 1.)^2 ) + (x(2) - 2.)^2;
and in Mlmode you enter
clear
xin
= [0. , 0.];
f
= 'fun';
fmins(f, xin)
O-Matrix will respond with an approximate minimizer for f(x).
13.20: Optimization Using The Conjugate Gradient Method
Syntax conjgrad(function fval, xin, scale, eps, maxit, level)
See Also conjdir: 13.18 , minline: 13.21 , sqp: 13.26 , nlsq: 13.14
13.20.a: Description
Uses the conjugate gradient method to minimize an objective f(x) with respect to x. The real or double-precision column vector xini specifies the
initial estimate for the value that minimizes the objective f. The column vector scale has the same type and dimension as x. The i-th element of scale
specifies the maximum absolute change for the i-th element of x between iterations. Every element of scale must be greater than 0. The scalar eps has
the same type as xini and specifies the convergence criteria. Convergence is accepted when the absolute change in x(i) is less than eps times
scale(i) for all i. The integer scalar maxit specifies the maximum number of iterations to attempt before giving up on convergence. The integer
scalar level specifies the amount of tracing. If level > 1, the current value of f(x) is printed at each iteration. If level > 2, the current argument
value x and the gradient g are printed at each iteration. If level > 3 , the step size and the function value are printed at each iteration of the line
search.
The (i+1)-th column of the return value is the value of x at the i-th iteration. (The first column contains the initial value xin.) The return value has same
type and row dimension as xini. Its column dimension is equal to the number of iterations plus 1.
fval(x, fout)
fval(x, fout, gout)
Computes the value of the objective and its gradient at the point specified by x, where x is a column vector with the same type and dimension as xini.
The input value of fout has no effect. On output, fout is equal to f(x). If the gout argument is present, its input value has no effect and its output value
is the gradient of f(x) evaluated at the point x and has the same type and dimension as x. The i-th element of gout is the derivative of f(x) with
respect to the i-th element of x.
13.20.b: Example
The program below solves the problem
2
minimize (x
- 1)
2
+
1
The solution to this problem is
(x
- 2)
with respect to x
1
x = {1, 2}
clear
#
function fval(x, fout, gout) begin
fout = (x(1) - 1.)^2. + (x(2) - 2.)^2
if arg(0) == 3 then begin
f_x1 = 2. * (x(1) - 1.)
f_x2 = 2. * (x(2) - 2.)
gout = {f_x1, f_x2}
end
return
end
xini
scale
eps
maxit
level
x
xout
print
= {0., 0.}
= {3., 3.}
= 1e-4
= 20
= 0
= conjgrad(function fval, xini, scale, eps, maxit, level)
= x.col(coldim(x))
xout
13.21: Minimization Along A Direction In A Vector Space
Syntax [betaout, nf] = minline(function f,
xref, betain, dir, level, maxdx, maxf)
13.21.a: Description
Sets betaout the value of beta that solves the problem:
minimize f(xref + beta dir) with respect to beta
where beta is a scalar with the same type as xref. If minline can not decrease the value of f in the direction dir, betaout is exactly equal to zero. If
present, the return value nf is set to the number of function evaluations used for the minimization.
f (x )
returns a scalar value with the same type as xref provided that x has the same type and dimension as xref.
xref
is a real or double-precision column vector that specifies the reference point for the line search.
betain
is a nonzero scalar that has the same type as xref and specifies the initial step size for the line search parameter.
dir
is a vector with the same type and dimension as xref. It specifies the direction of the line search.
level
is an integer scalar that specifies the level of tracing inside minline.
Name Condition Description
nf
level > 1 number calls to f
beta level > 1 step factor
f(x) level > 1 objective value
bmin level > 1 final step
fmin level > 1 final objective
maxdx
if present, maxdx specifies the maximum absolute change; that is,
| beta dir
|
i
< maxdx
for all i
i
and maxdx must have the same type and dimension as xref. If maxdx is not present, the vector defined by
maxdx
i
= 100 betain (|dir | + |dir| / 100)
i
is used.
nf
if present, maxf specifies the maximum number of evaluations of f to allow. If minline terminates because of this limit, nf is set to maxf + 1
13.21.b: Example
The following example minimizes the function
2
(2 + beta * 0 - 1)
2
+
(2 + beta * 1 - 1)
with respect to beta.
clear
function f(x) begin
return (x(1) - 1.)^2 + (x(2) - 1.)^2
end
xref
= {2., 2.}
betain = 1 / 3.
dir
= {0., 1.}
minline(function f, xref, betain, dir)
returns
-1
13.22: Solving Linear Complementarity Problems
Syntax lemke( level, maxitr, M, q, wout, zout)
13.22.a: Description
Uses Lemke's algorithm to solve the linear complementarity problem; i.e., determine column vectors z > 0 and w > 0 such that
w - M * z
= q
w(i) * z(i) = 0
for all i
This problem and algorithm are discussed in Section 10.6 of the second edition of Practical Methods of Optimization by R. Fletcher. The return value
of lemke is true, if it succeeds, and false otherwise.
The integer scalar maxitr specifies the maximum number of iterations to try before aborting. It is possible for Lemke's algorithm to cycle in a manner
similar to the simplex method. The real or double-precision square matrix M specifies the linear term in the complementarity problem. The column
vector q specifies the constant term in the complementarity problem. It has the same number of rows as the matrix M
The input values of the parameters wout and zout do not matter. The output values constitute the solution of the problem provided that the return value
of lemke is true. These output values have the same type and dimensions as q.
The integer scalar level specifies the level of tracing during the execution of the algorithm. If level > 1, the text "Begin lemke" and the value of M,
and q are printed at the beginning of the algorithm. The output values of wout and zout are printed at the end of the algorithm. In addition, the final
value of z0 and the residual in the complementarity equation are printed. These should both be zero. If the algorithm fails for some reason, a message
is printed to this effect. The message "Lemke returns true" is printed if the algorithm succeeds.
If level > 2, the value of z0 and its current numerical error, e0, are printed at each iteration. In addition, the index and value of the current pivot
element and the corresponding right hand side of the equation is printed at each iteration. The indices corresponding to the basic variables (nonzero
variables) are printed at each iteration as well as at the end of the algorithm. Lemke's algorithm completes when it finds a combination of basic
variables that results in a numerically zero value for z0. If m is the number of rows in M, index values less than m + 1 correspond to the elements of w,
the index value m + 1 corresponds to z0, index values greater than m + 1 correspond to the elements of z.
If level > 3, the Tableaux is printed at each iteration (see Table 10.6.3 of Practical Methods of Optimization for a description of the Tableaux).
13.22.b: Example
The following problem
minimize x(1)^2 + x(2)^2 + x(1) - x(2)
subject to x > 0
has corresponding Lagrangian
L(x, w) = x(1)^2 + x(2)^2 + x(1) - x(2) - w(1) x(1) - w(2) x(2)
Setting the partial derivative of the Lagrangian with respect to x equal to zero we have
w(1) - 2 x(1) = +1
w(2) - 2 x(2) = -1
This corresponds to the following linear complementarity problem:
clear
#
M = {[2., 0.], [0., 2.]}
q = {+1., -1.}
#
level
= 1
maxitr = 10
wout
= novalue
zout
= novalue
format real "g5.2"
flag = lemke(level, maxitr, M, q, wout, zout)
print "flag =", flag
13.23: Quadratic Programming with Inequality and Positive Constraints
Syntax Qpos(level, G, g, B, b, xout, lamout, alpout)
13.23.a: Description
Determine a value of x that solves the problem
minimize (1/2) x' G x + g' x
such that x > 0
B x - b > 0
with respect to x
This is Problem (10.6.1) in the second edition of Practical Methods of Optimization by R. Fletcher. The Lagrangian for this problem is
L(x, lam, alp) = (1/2) x' G x + g' x - lam' (B x - b) - alp' x
The return value of Qpos is true if it succeeds in solving the problem and false otherwise.
The real or double-precision symmetric positive definite matrix G contains the quadratic term in the objective function. The column vector g specifies
the linear term in the objective function. It has the same type and number of rows as G. The matrix B specifies the linear term in the constraint
inequalities. It has the same type and column dimension as G. The column vector b specifies the constant term in the constraint inequalities. It has the
same type and row dimension as B.
The input values of the parameters xout, lamout, and alpout do not matter. If the return value of Qpos is true, the output value of these parameters
satisfy the Kuhn-Tucker condition in Equation (9.1.16) of Practical Methods of Optimization, namely:
1. The partial of L with respect to x is zero at the point (xout, lamout, alpout).
2. The constraints are satisfied at the point xout.
3. All of the elements of lamout and alpout are greater than zero.
4. The following equations hold
0 = alpout' xout
0 = lamout' (B xout - b)
Note that because all the terms in these products are non-negative, this implies each term is zero.
The integer scalar level specifies the level of tracing inside of the Qpos function. If level > 1, the text "Beginning Qpos" and the value of G, g, B, and
b are printed before attempting to solve this problem. If Qpos cannot solve the problem, the text "Qpos returns false" is printed before it returns. If
Qpos does solve the problem, the output values of xout, lamout, and alpout are printed. In addition the partial of L with respect to x, and B xout - b
are printed together with the text "Qpos returns true".
If level > 2, a tracing level of level - 1 is used in the call to lemke: 13.22 that is used by Qpos.
13.23.b: Example
The following is Problem 10.4 from Practical Methods of Optimization
minimize x(1)^2
subject to x(1)
x(2)
- x(1) - x(2)
- x(1) * x(2) + x(2)^2 - 3 * x(1)
>= 0
>= 0
>= -2
The example below solves this problem
clear
#
G = {[2., -1.], [-1., 2.]}
g = {-3., 0.}
B = [-1., -1.]
b = -2.
#
level = 1
xout
= novalue
lamout = novalue
alpout = novalue
format real "g5.2"
flag = Qpos(level, G, g, B, b, xout, lamout, alpout)
print "flag = ", flag
13.24: Quadratic Programming with Inequality and Box Constraints
Syntax Qbox(level, Q, q, A, a, xlow, xup,
xout, gamout, alpout, betaout)
13.24.a: Description
Determine a value of x that solves the problem
minimize (1/2) x' Q x + q' x
such that A x - a < 0
xlow < x < xup
with respect to x
The Lagrangian for this problem is
L(x, gam, alp, beta) = (1/2) x' Q x + q' x
+ gam' (A x - a) + alp' (xlow - x) + beta' (x - xup)
The return value of Qbox is true if it succeeds in solving the problem and false
otherwise.
The real or double-precision symmetric positive definite matrix Q contains the quadratic term in the objective function. The column vector q specifies
the linear term in the objective function. It has the same type and number of rows as Q. The matrix A specifies the linear term in the constraint
inequalities. It has the same type and column dimension as Q. The column vector a specifies the constant term in the constraint inequalities. It has the
same type and row dimension as A. The column vectors xlow and xup specify the lower and upper limits for the box constraints. The have the same
type and row dimension as Q. Each element of xlow must be greater than or equal the corresponding element of xup. If the corresponding elements are
exactly equal, the corresponding component of x is removed from the optimization problem.
The input values of the parameters xout, gamout, alpout, and betaout do not matter. If the return value of Qbox is true, the output value of these
parameters satisfy the Kuhn-Tucker condition in Equation (9.1.16) of the second edition of Practical Methods of Optimization by R. Fletcher, namely:
1. The partial of L with respect to x is zero at the point (xout, gamout, alpout, betaout).
2. The constraints are satisfied at the point xout.
3. All of the elements of gamout, alpout, and betaout are greater than zero.
4. The following equations hold
0 = gamout' (a - A xout)
0 = alpout' (xout - xlow)
0 = betaout' (xup - xout)
Note that because all the terms in these products are non-negative, this implies each term is zero.
The integer scalar level specifies the level of tracing inside of the Qbox function. If level > 1, the text "Beginning Qbox" and the value of xlow, xup,
Q, q, A, and a are printed before attempting to solve this problem. If Qbox cannot solve the problem, the text "Qbox returns false" is printed before it
returns. If Qbox does solve the problem, the output values of xout, gamout, alpout, and betaout are printed. In addition the partial of L with respect to x,
and A xout - a are printed together with the text "Qbox returns true".
If level > 2, a tracing level of level - 1 is used in the call to Qpos: 13.23 that is used by Qbox.
13.24.b: Example
The program below solves the problem
minimize
x(1)^2 - (x(2) - 2)^2 + (x(3) + 2)^2
subject to 5. - x(1) < 0
-1 < x(1) < +1
-1 < x(2) < +1
-1 < x(3) < -1
The solution to this problem is x = [.5, -1, +1]
clear
#
level = 1
Q
= 2 * identity(3)
q
= {0., -4., +4}
A
= [-1., 0., 0.]
a
= -.5
xlow = {-1., -1., -1.}
xup
= {+1., +1., -1.}
xout
= novalue
gamout = novalue
alpout = novalue
betaout = novalue
ok = Qbox(level, Q, q, A, a, xlow, xup, xout, gamout, alpout, betaout)
print "ok =", ok
13.25: Quadratic Programming with Equality and Inequality Constraints
Syntax Qpro(level, G, g, A, a, neq, xlow, xup, xout, yAout, yLout, yUout)
13.25.a: Description
Determines the value of the x that solves the problem
minimize (1/2) x'
such that A.row(i)
A.row(i)
xlow < x
G
x
x
<
x + g x with respect to x
+ a(i) = 0 for i = 1, ..., neq
+ a(i) < 0 for i = neq + 1, ..., rowdim(A)
xup
The Lagrangian for this problem is
L(x, yA, yL, yU) = (1/2) x' G x + g x
+ yA' (A x + a) + yL' (xlow - x) + yU' (xup - x)
The return value of Qpro is true if it succeeds in solving the problem and
false otherwise.
The real or double-precision symmetric positive definite matrix G contains the quadratic term in the objective function. The row vector g specifies the
linear term in the objective function. It has the same type and number of columns as G. The matrix A specifies the linear term in the constraints. It has
the same type and column dimension as G. The column vector a specifies the constant term in the constraints. It has the same type and row dimension
as A.
The input values of the parameters xout, yAout, yLout, and yUout do not matter. If the return value of Qpro is true, the output value of these parameters
satisfy the Kuhn-Tucker condition in Equation (9.1.16) of Practical Methods of Optimization, namely:
1. The partial of L with respect to x is zero at the point (xout, yAout, yLout, yUout)
2. The constraints are satisfied at the point xout.
3. All of the elements of yLout and yUout are greater than zero. In addition, the elements of yAout with index greater than neq are greater than zero.
4. The following equations hold
0 = yAout' (- A x - a)
0 = yLout' (x - xlow)
0 = yUout' (xup - x)
Note that because all the terms in these products are non-negative, this implies each term is zero. The output value of xout, yLout and yUout are a
column vectors with the same type and dimensions as xlow. The output value of yAout is a column vector with the same type and row dimension as A.
The parameter level is an integer scalar specifying the level of tracing inside of the Qpro function. If level > 1, the text "Beginning Qpro" and the
value of G, g, A, a, xlow, and xup, are printed before attempting to solve this problem. If Qpro cannot solve the problem, the text "Qpro returns false"
is printed before it returns. If Qpro does solve the problem, the output values of xout, yAout, yLout, and yUout are printed. In addition the partial of L
with respect to x, and A xout + a are printed together with the text "Qpro returns true".
If level > 2, a tracing level of level - 1 is used in the call to Qbox: 13.24 that is used by Qpro.
13.25.b: Example
The program below solves the problem
minimize
x(1)^2 + x(2)^2 + 2 x(1) + x(2)
subject to - x(1) - x(2) < 0
clear
level = 1
G
= {[2., 0], [0, 2.]}
g
= [2., 1.]
A
= [-1., -1.]
a
= 0.
neq
= 0
xlow = {-10., -10.}
xup
= {+10., +10.}
xout = novalue
yAout = novalue
yLout = novalue
yUout = novalue
ok = Qpro(level, G, g, A, a, neq, xlow, xup, xout, yAout, yLout, yUout)
print "ok =", ok
13.26: Nonlinear Constrained Optimization by Successive Quadratic Programming
Syntax sqp(function f, function df, function g, function dg, ...
neq, xlow, xup, xini, maxitr, level, eps, ...
xout, ygout, ylimout, flagout)
13.26.a: Description
Uses successive quadratic programming to solve the problem
minimize f(x) with respect to x and subject to
g(x)(i) = 0 for i = 1, ... , neq
g(x)(i) < 0 for i = neq + 1, ... , rowdim(g(x))
xlow(i) < x(i) < xup(i) for i = 1, ... , rowdim(xlow)
The Lagrangian for this problem is
L(x, yg, ylim) = f(x) + yg * g(x) + ylim
In the following function calls, x is a column vector of the same type and dimension as xlow. The function call f(x) returns the value of the objective
function at x as a scalar with the same type as x. The function call df(x) returns the derivative of the objective function at x as a row vector with the
same type as x and with the same number of columns as x has rows. The function call g(x) returns the value of the constraints at the point x as a
column vector with the same type as x. The function call dg(x) returns is the derivative of the constraints at x as a matrix with the same type as x, the
same number of rows as g(x), and the same number of columns as x has rows. Element (i, j) of dg(x) is the partial derivative of the i-th component
of g with respect to the j-th component of x.
The integer scalar neq specifies the number of equality constraints and must be less than or equal to the number of rows of g(x). The real or doubleprecision column vector xlow specifies the lower limits for the minimization problem. The vector xup specifies the upper limits for the minimization
problem and has the same type and dimension as xlow. Either xup(i) is equal to xlow(i) or the value xup(i) - xlow(i) is used to scale the
problem with respect to the i-th component of x. Thus, if there are no upper and lower limits, xlow and xup should be set to give a meaningful scaling
for the problem. The vector xini specifies the point at which the successive quadratic programming method is started. It has the same type and
dimension as xlow and must be between xlow and xup. The integer scalar maxitr specifies the maximum number of iterations to try before giving up on
convergence of the method. The scalar eps has the same type as xlow and specifies the convergence criteria. Convergence is achieved when the
solution of the approximate quadratic programming subproblem is within eps times the upper minus the lower limit; i.e.,
|xout(i) - xmin(i)| < eps (xup(i) - xlow(i))
for all i where xmin is the solution of the quadratic programming subproblem that approximates the original problem near the point xout.
The input values of xout, ygout, ylimout and flagout do not matter. The column vector xout is set to the approximate solution and has the same type and
dimension as xlow. The row vector ygout is set to the Lagrange multipliers corresponding to the constraints defined using the function g and have the
same type as xlow and the same number of columns as g(x) has rows. The row vector ylimout is set to the Lagrange multipliers corresponding to the
limits xlow and xup. It has the same type as xlow and the same number of columns as xlow has rows. The character row vector flagout is set to
"converged" if the eps criteria is achieved, "line search failed" if the method fails during a line search, and "max iterations" is the maximum number of
iterations is reached with out achieving convergence. The i-th column of the return value from sqp contains the value of x at the i-th iteration. The
return value has the same type and row dimension as xlow.
The integer scalar level specifies the level of tracing inside of the function sqp. If level > 1, the text "Beginning sqp" and the value of xlow, xini,
xup, f, and g are printed before attempting to solve the problem. The following values are printed at each iteration: the iteration number, the current
value of f(x), the current value of the penalty function, and the maximum scaled difference between the approximate solution and the current point. In
addition, the value of flagout is printed just before sqp returns. If level > 2, the following value are printed at each iteration: the difference between
the approximate subproblem solution and the current point, the value of g(x), the Lagrange multiplier values used in the penalty function, and the
partial of the Lagrangian with respect to x. In addition, the line search is traced with lam being the line search step size, dp being the change in the
penalty function, and dapx being the corresponding change in the penalty function for the approximation. If level > 3, the value of the
approximation to the Hessian of the Lagrangian is printed at each iteration. If level > 4, the tracing level level - 3, is used inside of Qpro: 13.25
when it solves the approximate subproblem.
13.26.b: Example
The following program solves the problem
minimize
x(1)^2 + x(2)^2 with respect to x
subject to 1 - x(1) = 0
that the solution to this problem is x(1) = 1 and x(2) = 0. The
Note
active during the optimization process.
lower and upper limits for x are chosen large enough so that they should not be
clear
#
function f(x) begin
return x(1)^2 + x(2)^2
end
function df(x) begin
return 2 * x'
end
function g(x) begin
return 1 - x(1)
end
function dg(x) begin
return [-1., 0.]
end
maxitr
= 10
level
= 1
eps
= 1e-5
xini
= {2., 2.}
xlow
= {-100., -100.}
xup
= {+100, +100.}
neq
= 1
xout
= novalue
ygout
= novalue
ylimout = novalue
flagout = novalue
sqp(function f, function df, function g, function dg, ...
neq, xlow, xup, xini, maxitr, level, eps, ...
xout, ygout, ylimout, flagout)
print "xout' =", xout
13.27: Extended Least Squares
Syntax relative(function y, function F, function dF, ...
M, xin, xlow, xup, eps, maxstp, mitr, ...
xout, vout, Rout, gout, lamout, Cout)
13.27.a: Description
Uses a modified version of the Gauss-Newton method to solve the extended least squares problem
M
----minimize >
----i = 1
such that
2
N
i
xlow
log(v ) +
i
< x
j
| y(i) - F(i, x) |
-----------------v
i
with respect to (v, x)
< xup
j
j
This is the maximum likelihood estimator for (v, x) if there is a true, but unknown, value for (v, x) such that for each i the elements of the data
vector y(i) are independent normally distributed with mean F(i, x) and variance v(i). This estimator and the algorithm used by relative are
discussed in the paper A relative weighting method for estimating parameters and variances in multiple data sets, (1997) volume 22, pages 119-135 of
Computational Statistics and Data Analysis.
The return value of relative is true if convergence is achieved and false otherwise.
y (i )
Returns the value y(i) as a column vector with the same type as xin, where i is an integer scalar between 1 and M.
F (i , x )
Returns the value F(i, x) as a column vector with the same type and dimension as y(i), where i is an integer scalar between 1 and M and x is a
vector with the same type and dimension as xin.
dF(i, x)
The derivatives of F(i, x) with respect to x as a column vector with the same type and row dimension as y(i). The column dimension of dF(i, x)
is equal to the row dimension of xin. The (k,j)-th element of the return value dF(i, x) is the partial derivative of the k-th element of F(i, x) with
respect to the j-th element of x.
The integer scalar M specifies the number of measurement sets each of which has its own variance. The real or double-precision column vector xin
specifies the starting point for the optimization procedure. The inequality xlow(j) < x(j) < xup(j) must hold for each j. The column vector xlow
has the same type and dimension as xin and specifies the lower limits for x in the extended least squares problem. The column vector xup has the same
type and dimension as xin and specifies the upper limits for x in the extended least squares problem. The column vector eps has the same type and
dimension as xin and convergence is accepted when the absolute change in the j-th element of x is less than or equal eps(j) for all j. All of the
elements of eps must be greater than 0. The vector maxstp has the same type and dimension as xin and the value maxstp(j) is the maximum absolute
change allowed in the j-th element if x between iterations of the algorithm. All of the elements of maxstp must be strictly greater than 0. The integer
scalar mitr specifies the maximum number of iterations of the relative weighting algorithm to execute before giving up on convergence.
The input value of xout has no effect. Its output value has the same type and row dimension as xin and its column dimension is equal to the number of
iterations. The k-th column of the output value of xout is the estimate of the parameter vector x at the k-th iteration of the algorithm. The input value of
vout has no effect. The output value of vout has the same type as xin, its row dimension is M, and its column dimension is equal to the number of
iterations. The (i,k)-th element of the output is the variance estimate that corresponds to the i-th measurement set and the k-th iteration. The input value
of Rout has no effect. The output value of Rout is a row vector with the same type as xin and column dimension equal to the number of iterations. The
k-th element of Rout is the reduced objective function value that corresponds to the k-th iteration. (The reduced objective is the sum of the logarithm
terms normalized by the number of data points. Up to a constant, this is equal to the original extended least squares objective at the value of v that is
optimal for the current x.) The input value of gout has no effect. The output value of gout is a matrix with row dimension equal to the row dimension
of xin and column dimension equal to the number of iterations. The (j,k)-th element of gout is the partial derivative of the reduced objective function
with respect to the j-th element of x at the k-th iteration. The input value of lamout has no effect. The output value of lamout is a row vector with the
same type as xin and lamout(k) is the line search parameter that corresponds to the difference between the k-th column of xout and the k+1-th column
of xout. The input value of Cout has no effect. The output value of Cout is a square matrix: 26.ak with the same number of rows as xin. The matrix
Cout is an estimate of the covariance of the optimal value for x as an estimate of the true parameter vector.
13.27.b: Example
The relative weighting algorithm should be used when data sets have different variances. The program below simulates two data sets, each with its
own time grid. The first data set has a standard error of .1 and the second has a standard error of .01. The model for the data has three parameters and
is
2
x
+ x
1
t
2
+
x
t
3
The simulation is done using the true, but unknown during fitting, values of the elements of x which are all 1. The true value of x and v are {1, 1, 1}
and {.01, .0001} respectively. These values are approximated by the values of x and v that solve the minimization problem.
clear
#
# simulate data set 1
t1 = seq(100) / 100.
y1 = 1. + t1 + t1^2 + .1 * snormal(100, 1)
#
# simulate data set 2
t2 = seq(10) / 10.
y2 = 1. + t2 + t2^2 + .01 * snormal(10, 1)
#
function y(i) begin
global y1, y2
if i == 1 then ...
return y1
else return y2
end
#
function F(i, x) begin
global t1, t2
if i == 1 then ...
return x(1) + x(2) * t1 + x(3) * t1^2
else return x(1) + x(2) * t2 + x(3) * t2^2
end
#
function dF(i, x) begin
global t1, t2
if i == 1 then ...
return [ones(rowdim(t1), 1), t1, t1^2]
else return [ones(rowdim(t2), 1), t2, t2^2]
end
#
M
= 2
xin
= {.5, .5, .5}
xlow
= {0., 0., 0.}
xup
= {10., 10., 10.}
eps
= {1e-3, 1e-3, 1e-3}
maxstp = {1., 1., 1.}
mitr
= 10
xout
= novalue
vout
= novalue
Rout
= novalue
gout
= novalue
lamout = novalue
Cout
= novalue
relative(function y, function F, function dF, ...
M, xin, xlow, xup, eps, maxstp, mitr, ...
xout, vout, Rout, gout, lamout, Cout )
#
print "minimizing x =", xout.col(coldim(xout))
print "minimizing v =", vout.col(coldim(vout))
13.28: Forward Difference Derivative Approximation
Syntax fordiff(function f, x, h)
13.28.a: Description
Returns the forward difference approximation for the Jacobian of f at x, where f is a function such that f(x) returns a column vector with the same type
as x, x is a real or double-precision column vector specifying the point at which to approximate the Jacobian of f, and h is a column vector, with the
same type and dimension as x, that specifies the step size for approximating partials of f.
A matrix valued function J(x) is the Jacobian of f(x) if the (i,j)-th element of J(x) is the partial of the i-th element of f(x) with respect to the j-th
element of x. The return value of fordiff has the same type as x, the same number of rows as f(x), and the same number of columns as x has rows.
If h(j) is 0, partials with respect to x(j) are not approximated, and 0 is returned in the corresponding column of the return value.
The functions fordiff and cendiff: 13.29 can be used to approximate derivatives for both optimization and zero-finding algorithms. The cendiff
function is more accurate, but it requires more function evaluations.
13.28.b: Example
The derivative of the function
2
f(x) = x
has the value 2 at x = 1. This example approximates this derivative using a forward difference with a .01 step size.
If you enter
function f(x) begin
return x^2
end
x
= 1.
h
= .01
print fordiff(function f, x, h)
O-Matrix will respond
2.01
13.29: Central Difference Derivative Approximation
Syntax cendiff(function f, x, h)
13.29.a: Description
Returns the central difference approximation for the Jacobian of f at x. The real or double-precision vector x specifies the point at which to
approximate the Jacobian. The real or double-precision vector h specifies the step size for approximating the partials of f, and h has the same length as
x. If h(j) is 0, partials with respect to x(j) are not approximated and 0 is returned in the corresponding column of the Jacobian.
A matrix function J(x) is the Jacobian of a column vector function f(x) if the (i,j) element of J(x) is the partial of the ith element of f(x) with
respect to the jth element of x.
Given a real or double precision vector with the same dimension as x, the function f returns a real, double-precision, or complex column vector. The
return value of cendiff has the type that results from coercion: 4.4 between the type of x, h and f(x). It has the same number of rows as f(x) and its
column dimension is equal to the length of x.
The functions cendiff and fordiff: 13.28 can be used to approximate derivatives for an optimization or zero-finding algorithm. The cendiff function
is more accurate, but it requires more function evaluations.
13.29.b: Example
function f(x) begin
return x^2
end
x = 1.
h = .1
cendiff(function f, x, h)
returns
2
13.30: Numerical Derivatives With Automatic Step Size Control
Syntax autodiff(function f, epsf, x, h)
13.30.a: Description
Returns a central difference approximation for the derivative of the function f(y) evaluated at the point specified by x. The return value has the same
number of rows as f(y) and its column dimension is equal to the row dimension of x.
If y has the same type and dimension as x, f(y) returns a column vector with the same type as x. In addition, the row dimension of f(y) is the same
for all values of y. The scalar epsf has the same type as x and specifies the relative accuracy in the value of f(y). The real, double-precision or
complex column vector x is the point at which the derivative of f(y) is approximated. The column vector h has the same type and dimension as x The
input value of h specifies the step size for this approximation of the derivative of f(y). The output value of h is a suggested step size for the next time
the partials of f(y) is evaluated nearby. You may modify this value before the next call to autodiff. (for example, to ensure it is between some
maximum and minimum values).
13.30.b: Example
The program below approximates the derivative of the exponential function. The routine f(y) simulates evaluating this function to a relative accuracy
of 1e-5 by adding a random error. The autodiff function is called four times in order to demonstrate the improvement in the derivative approximation
with each call. Note that the derivative of the exponential function at x = 1 is equal to exp(1).
clear
function f(y) begin
return exp(y) * ( 1d0 + 1d-5 * rand(1, 1))
end
format int
"10"
format double "f15.10"
epsf = 1d-5
x
= 1d0
h
= 1d0
print "exp(1d0) =", exp(1d0)
print align("i, h, autodiff", ",", [10, 16, 16], "right")
for i = 1 to 4 begin
print i, h, autodiff(function f, epsf, x, h)
end
13.30.c: Reference
If the input value of h(j) + x(j) is equal to x(j), partials of f(y) with respect to x(j) are not approximated. In this case, zero is placed in the j-th
column of the return value. In addition, the output value of h(j) is equal to its input value.
The step size is controlled to be optimal for the component of f(y) that has the largest value. If the components of f(y) have very different scaling, it
may help to evaluate the derivative one component at a time (maintaining a different value of h for each component).
The functions autodiff, cendiff: 13.29 , and fordiff: 13.28 can be used to approximate derivatives for an optimization or zero-finding algorithm. The
function autodiff requires more function evaluations than the others, but it should be more accurate.
13.31: Testing Calculation of The Derivative of a Function
Syntax testder(function fval, x0, h)
13.31.a: Description
Given a routine fval that calculates the derivative of a column vector valued function f(x), testder compares this calculation with a central
difference approximation. The results of the comparison are printed in the command window. The column vector x0 specifies the value of x at which
to check the calculation of the derivative. The column vector h has the same type and dimension as x0. It specifies the step size to use for each
component of x when computing the central difference approximations to the derivative of f(x).
fval(x1, fout)
fval(x1, fout, dfout)
The column vector x1 has the same type and dimension as x0 and specifies a point at which to calculate the value of f(x). The input value of fout does
not matter. Its output value is a column vector with the same type as x0 and equal to the value of f(x1). If dfout is present, its input value does not
matter. Its output value is a matrix with the same type and row dimension as fout. Its column dimension is equal to the row dimension of x1 and
d f (x) |
i
|
dfout
= -------- |
i,j
d x
| x = x1
j
each component of x, the partials returned
For
command window.
by fval, the central difference approximation, and the corresponding relative error are printed in the
13.31.b: Example
The following program checks the derivative calculation for the function f(x) where
/ x \
f(x) = |
| ,
\ x^2 /
d f(x) |
------ |
d x
|x = 1
/ 1 \
= |
|
\ 2 /
clear
function fval(x1, fout, dfout) begin
fout = {x1, x1^2}
if arg(0) == 3 then ...
dfout = {1, 2 * x1}
end
x0 = 1.
h = .001
testder(function fval, x0, h)
13.32: Testing Calculation of The Gradient of a Function
13.32.a: Description
Given a routine fval that calculates the gradient of a column vector valued function f(x), testgrad compares this calculation with a central difference
approximation. (The gradient is the transpose of the derivative.) The results of the comparison are printed in the command window. The column vector
x0 specifies the value of x at which to check the calculation of the gradient. The column vector h has the same type and dimension as x0. It specifies
the step size to use for each component of x when computing the central difference approximations to the derivative of f(x).
fval(x1, fout)
fval(x1, fout, gout)
The column vector x1 has the same type and dimension as x0 and specifies a point at which to calculate the value of f(x). The input value of fout does
not matter. Its output value is a column vector with the same type as x0 and equal to the value of f(x1). If gout is present, its input value does not
matter. Its output value is a matrix with the same type and row dimension as x0. Its column dimension is equal to the row dimension of fout and
d f (x)
j
gout
= -------i,j
d x
i
each component of x, the
For
command window.
|
|
|
| x = x1
partials returned by fval, the central difference approximation, and the corresponding relative error are printed in the
13.32.b: Example
The following program checks the gradient calculation for the function f(x) where
/ x \
f(x) = |
| ,
\ x^2 /
__
|
\/ f(x) |
=
|x = 1
(1, 2)
clear
function fval(x1, fout, gout) begin
fout = {x1, x1^2}
if arg(0) == 3 then ...
gout = [1, 2 * x1]
end
x0 = 1.
h = .001
13.33: Testing Calculation of The Hessian of a Function
Syntax testhess(function fval, x0, h)
13.33.a: Description
Given a routine fval that calculates the gradient and Hessian of a scalar valued function f(x), testhess compares these calculations with a central
difference approximation. (The Hessian if the second derivative.) The column vector x0 specifies the value of x at which to check the calculations. The
column vector h has the same type and dimension as x0. It specifies the step size to use for each component when computing the central difference
approximations.
fval(x1, fout)
fval(x1, fout, gout)
fval(x1, fout, gout, Hout)
The column vector x1 has the same type and dimension as x0 and specifies the point at which to calculate the value of f(x). The input value of fout
does not matter. Its output value is a scalar and equal to the value f(x1). If gout is present, its input value does not matter. Its output value is a column
vector with the same type and dimension as x1 and
gout
d f(x) |
------- |
d x
| x = x1
i
=
i
If Hout is present, its input value does not matter. Its output value is a square matrix with the same type and row dimension as x1 and
Hout
=
i,j
d
d f(x) |
----- ------ |
d x
d x
| x = x1
i
j
First the gradient calculation is compared with central differences of the function values. Then the Hessian calculation is compared with central
differences of the gradient values. This is done for each component of x by printing the values returned by fval, the central difference approximation,
and the corresponding relative error in the command window. (Note that in the output that checks the Hessian, gradient refers to the gradient of the
derivative which is the Hessian.)
13.33.b: Example
The following program checks the gradient and Hessian calculation for the function f(x) where
f(x) = x
* x
1
,
2
/ x \
__
| 2 |
\/ f(x) = |
|
| x |
\ 1 /
,
/ 0
__2
|
\/ f(x) = |
|
\ 1
1 \
|
|
|
0 /
clear
function fval(x1, fout, gout, Hout) begin
fout = x1(1) * x1(2)
if arg(0) >= 3 then ...
gout = {x1(2), x1(1)}
if arg(0) >= 4 then ...
Hout = {[0., 1.], [1., 0.]}
end
x0 = {1., 1.}
h = {.001, .001}
testhess(function fval, x0, h)
14: FFTs, Filtering and Time Series
14.a: Contents
fourier: 14.1
Fourier Transforms
kalman_bucy: 14.2 Kalman-Bucy Filtering and Smoothing
filter: 14.3
Auto-Regressive And Moving Average Filtering
mlmode_filter: 14.4 Auto-Regressive And Moving Average Filtering (Mlmode)
arcov: 14.5
Simulating An AR Process With A Specified Covariance
fspec: 14.6
Estimating The Fourier Spectrum Of A Random Process
dpss: 14.7
Discrete Prolate Spheroidal Sequences
wavelet: 14.8
Computing The Wavelet Transform
iwavelet: 14.9
Inverse Wavelet Transform
fnbut: 14.10
Normalized Butterworth Filter Polynomials
fncheb: 14.11
Normalized Chebyshev Filter Polynomials
fnbpole: 14.12
Poles Of A Normalized Butterworth Filter
fncpole: 14.13
Poles Of A Normalized Chebyshev Filter
fn2cbp: 14.14
Converting From A Normalized To Continuous Bandpass Filter
fn2clp: 14.15
Converting From A Normalized To Continuous Lowpass Filter
fc2dig: 14.16
Converting From A Continuous To Digital Filter
fn2dbp: 14.17
Converting From A Normalized To Digital Bandpass Filter
fn2dlp: 14.18
Converting From A Normalized To Digital LowPass Filter
14.1: Fourier Transforms
14.1.a: Contents
dft: 14.1.1
The Discrete Fourier Transform
idft: 14.1.2
The Inverse Discrete Fourier Transform
fft: 14.1.3
The Centered Finite Fourier Transform
ifft: 14.1.4
The Centered Finite Inverse Fourier Transform
dbldft: 14.1.5 Forward Fourier Transform of a Double-Precision Vector
idbldft: 14.1.6 Inverse Fourier Transform of a Double-Precision Vector
lombft: 14.1.7 The Unevenly Spaced Lomb-Fourier Transform
fft2d: 14.1.8
Two Dimensional Fourier Transform
ifft2d: 14.1.9 Two Dimensional Inverse Fourier Transform
dft2d: 14.1.10 Two Dimensional Discrete Fourier Transform
idft2d: 14.1.11 Two Dimensional Inverse Discrete Fourier Transform
fftshift: 14.1.12 Circular Shift That Centers a Discrete Fourier Transform
14.1.1: The Discrete Fourier Transform
Syntax dft(z)
See Also fft: 14.1.1.c , idft: 14.1.2 , fft: 14.1.3 , lombft: 14.1.7
14.1.1.a: Description
Returns a complex matrix containing the discrete Fourier transform of z, where z is an integer, real, double-precision or complex matrix. If N is the
number of rows in z, the (k,j)-th element of the return value is equal to
N
---->
----i = 1
__
exp[-2 pi \/-1 (i - 1) (k - 1) / N]
z
i,j
for k between 1 and N and j between 1 and the number of columns in z.
14.1.1.b: Example
If you enter
z = {0, 1, 0, 0}
only the term with i = 2 in the summation defining dft(z) is nonzero, and the k-th element of dft(z) is equal to
__
exp[-2 pi \/-1 (k - 1) / 4]
which is 1, -\sqrt(-1), -1, and \sqrt(-1), for k equal to 1, 2, 3, and 4, respectively. If you continue this example by entering
dft(z)
O-Matrix will respond
{
(1,0)
(0,-1)
(-1,0)
(0,1)
}
14.1.1.c: Mlmode
In Mlmode: 25 this function is called fft instead of dft. If you continue the example above by entering
mlmode
fft(z)
O-Matrix will respond
{
(1,0)
(0,-1)
(-1,0)
(0,1)
}
14.1.2: The Inverse Discrete Fourier Transform
Syntax idft(z)
14.1.2.a: Description
Returns a complex matrix containing the inverse discrete Fourier transform of z, where z is an integer, real double-precision or complex matrix. If N is
the number of rows in z, the (k,j)-th element of the return value is equal to
for
N
1 ----__
- >
z
exp[+2 pi \/-1 (i - 1) (k - 1) / N]
N ----i,j
i = 1
k between 1 and N and j between 1 and the number of columns
in z.
14.1.2.b: Example
If you enter
z = {0, 1, 0, 0}
only the term with i = 2 in the summation defining idft(z) is nonzero, and the k-th element of idft(z) is equal to
1
__
- exp[+2 pi \/-1 (k - 1) / 4]
4
which is 1/4, \sqrt(-1)/4, -1/4, and -\sqrt(-1)/4, for k equal to 1, 2, 3, and 4, respectively. If
idft(z)
you continue this example by entering
O-Matrix will respond
{
(.25,0)
(0,.25)
(-.25,0)
(0,-.25)
}
14.1.2.c: Mlmode
In Mlmode: 25 this function is called ifft instead of idft. If you continue the example above by entering
mlmode
ifft(z)
O-Matrix will respond
{
(.25,0)
(0,.25)
(-.25,0)
(0,-.25)
}
14.1.3: The Centered Finite Fourier Transform
Syntax fft(z)
See Also ifft: 14.1.4 , fft2d: 14.1.8 , dft: 14.1.1 , lombft: 14.1.7
14.1.3.a: Description
Returns a complex matrix containing the centered finite Fourier transform of z, where z is an integer, real double-precision or complex matrix. If N is
the number of rows in z, the (k,j)-th element of the return value is equal to
N
---->
----i = 1
__
exp[-2 pi \/-1 (i - N/2 - 1) (k - N/2 - 1) / N]
z
i,j
for k between 1 and N and j between 1 and the number of columns in z.
14.1.3.b: Example
The Fourier transform of a function h(t) is defined as follows:
+infinity
/
__
H(f) = | h(t) exp(-2 pi \/-1 f t) dt
/
-infinity
If the function h(t) is the rectangular window function
/
h(t) = {
\
1, if -T < t < T
0, otherwise
The Fourier transform of h(t) is given by the following:
sin(2 pi T f)
H(f) = ------------pi f
The following program plots an approximation for the transform that defines H(f), where T = 1/2, there are 2^10 points in the finite Fourier
transform, of which 2^6 points are between -T and +T. The names dt and df are used for the spacing in the time and frequency grids.
clear
N
= 2^10
M
= 2^6
T
= .5
dt = 2 * T / M
df = 1. / (N * dt)
f
= (seq(N) - N / 2 - 1) * df
t
= (seq(N) - N / 2 - 1) * dt
h
= int( abs(t) <= T )
H
= fft(h) * dt
gxaxis("linear", -5, +5)
gtitle("H(f)")
gplot(f, real(H))
14.1.4: The Centered Finite Inverse Fourier Transform
Syntax ifft(z)
14.1.4.a: Description
Returns a complex matrix containing the inverse centered finite Fourier transform of z, where z is an integer, real double-precision or complex matrix.
If N is the number of rows in z, the (k,j)-th element of the return value is equal to
N
---->
----i = 1
__
exp[+2 pi \/-1 (i - N/2 - 1) (k - N/2 - 1) / N]
z
i,j
for k between 1 and N and j between 1 and the number of columns in z.
14.1.4.b: Example
The inverse Fourier transform of a function H(f) is defined as follows:
+infinity
/
__
h(t) = | H(f) exp(+2 pi \/-1 f t) df
/
-infinity
If the function H(f) is defined by:
sin(2 pi T f)
H(f) = ------------pi f
The inverse Fourier transform of H(f) is given by the
/ 1, if -T < t < T
h(t) = {
\ 0, otherwise
following:
The following program plots an approximation for the inverse transform that defines h(t), where T = 1/2, there are 2^10 points in the finite Fourier
transform, of which 2^6 points are between -T and +T. The names dt and df are used for the spacing in the time and frequency grids. (Note the index
N/2 +1 is a special case because f = 0 at that index.)
clear
N
= 2^10
M
= 2^6
T
= .5
dt
= 2 * T / M
df
= 1. / (N * dt)
t
= (seq(N) - N / 2 - 1) * dt
f
= (seq(N) - N / 2 - 1) * df
H
= sin(2 * pi * T * f) / (pi * f)
H(N/2 + 1) = 1
h
= ifft(H) * df
gxaxis("linear", -1, +1, 4, 5)
gtitle("Real Part of h(t)")
gplot(t, double(h))
14.1.5: Forward Fourier Transform of a Double-Precision Vector
Syntax dbldft(w)
14.1.5.a: Description
Returns the column by column discrete transform of w, where w is a double-precision matrix with an even number of rows. The numbers 2, 3, 5, and 7
must be the only prime factors of the number of rows in w. This routine is faster and uses less memory than the dft function but it only applies to the
case where the vector to be transformed has zero imaginary part.
If N is half the number of rows in w, define
z(k, j) = sum_{i=1}^{2 N}
w(i, j) exp[ -2 pi sqrt{-1} (i - 1) (k - 1) / (2 N) ]
Thus z is the column by column discrete Fourier transform of w.
For each j, z(1, j) and z(N + 1, j) have zero imaginary part because w has zero imaginary part. Furthermore for k > N + 1, z(k, j) is equal to
the complex conjugate of z(2 N + 2 - k, j). Thus we only need return that value of z(k, j) for k between 1 and N + 1 to specify the entire
transform of w.
The return value of the dbldft function has the same type and dimension as w. If c is the return value, for all k between 2 and N, and all j between 1
and the column dimension of w
c(1, j)
=
c(2, j)
=
c(2 k - 1, j) =
c(2 k, j)
= the
the real part of z(1, j)
the real part of z(N + 1, j)
the real part of z(k, j)
imaginary part of z(k, j)
14.1.5.b: Example
If you enter
w = double({0, 1, 0, 0})
only the term with i = 2 in the summation defining dbldft(w) is nonzero, and element k of the Fourier transform of w is given by
z(k) = exp[- pi sqrt{-1} (k - 1) / 2]
which is given by the following table
z(1)
z(2)
z(3)
z(4)
=
=
=
=
1
-sqrt{-1}
-1
sqrt{-1}
If you continue this example by entering
dbldft(w)
O-Matrix will respond
{
1
-1
0
-1
}
the first element of the vector above is equal to the real part of z(1). The second element is equal to the real part of z(3) (note that for this case
N + 1 = 3). The third element is equal to the real part of z(2). The fourth element is equal to the imaginary part of z(2).
14.1.6: Inverse Fourier Transform of a Double-Precision Vector
Syntax idbldft( c)
14.1.6.a: Description
Returns the column by column inverse discrete transform of c, where c is a double-precision matrix with an even number of rows. The numbers 2, 3,
5, and 7 must be the only prime factors of the number of rows in c. This routine is faster and uses less memory than the idft function but it only
applies to the case where the vector c represents a complex vector that is conjugate symmetric. If N is half the number of rows in c and for all k
between 2 and N, and all j is between 1 and the column dimension of c define the complex matrix z by
z(1, j) = c(1, j)
z(N + 1, j) = c(2, j)
the real part of z(k, j) = c(2 k - 1, j)
the imaginary part of z(k, j) = c(2 k, j)
z(2 N + 2 - k, j) = the complex conjugate of z(k, j)
The return value of the idbldft function is the matrix w defined by
w(k, j) = (1 / (2 N)) * sum_{i=1}^{2 N}
z(i, j) exp[ 2 pi sqrt{-1} (i - 1) (k - 1) / (2 N)]
Thus w is the column by column inverse discrete Fourier transform of z (w is real because z
is conjugate symmetric).
14.1.6.b: Example
If you enter
c = double({0, 1, 0, 0})
only the term with i = 3 in the summation defining w is nonzero. Also note that 2 N is 4 and element k of the inverse Fourier transform of c is given
by
w(k) = (1/4) exp[ pi sqrt{-1} (k - 1) ]
which is given by the following table
w(1)
w(2)
w(3)
w(4)
=
=
=
=
+1/4
-1/4
+1/4
-1/4
(Note that all of the elements of w are real.) If you continue this example by entering
idbldft(c)
O-Matrix will respond
{
.25
-.25
.25
-.25
}
14.1.7: The Unevenly Spaced Lomb-Fourier Transform
Syntax [a, b] = lombft(t, z, f)
14.1.7.a: Description
Computes Lomb-Fourier transform of the data sequence
{ (t , z ): j = 1, ... , N }
j
j
where t and z are column vectors with length N. The vector t is integer, real, or double-precision and z is integer, real, double-precision or complex.
The column vector f is integer, real, or double-precision and all of its elements are greater than zero. The Lomb-Fourier transform solves the following
problem:
zhat(f ) = argmin
j
(a + i b)
N
-->
--j=1
2
|
| z
| j
2 pi i f(j) t(j) |
- (a + i b) * e
|
|
where i denotes the square root of minus one. The return values a and b are double-precision column vectors with the same length as f and such that
zhat(f ) = a(f ) + i b(f )
j
j
j
14.1.7.b: Example
The following program plots the square of the absolute value of the Lomb-Fourier transform of a sine wave on unevenly spaced data:
#
clear
#
ranseed
N
= 100
Tmax
= sqrt(double(N))
f0
= sqrt(double(N))
t
= Tmax * rand(N, 1)
z
= sin(2 * PI * f0 * t)
f
= seq(N / 2)
#
[a, b] = lombft(t, z, f)
gplot(f, a^2 + b^2)
gxaxis("log")
gtitle("Lomb-Fourier Transform Squared")
14.1.8: Two Dimensional Fourier Transform
Syntax fft2d( z)
14.1.8.a: Description
Returns the complex two-dimensional centered Fourier transform of z, where z is an integer, real, double-precision or complex matrix with an even
number of rows and columns. If M is the number of rows in z and N is the number of columns in z, the (m,n)-th element of the return value is equal to
M
-----
N
-----
{
__ [ (i - M/2 - 1) (m - M/2 - 1) / M ] }
>
----i = 1
>
----j = 1
z
i,j
exp{ -2 pi \/-1 [
+
] }
{
[ (j - N/2 - 1) (n - N/2 - 1) / N ] }
If the only prime factors of M and N are 2, 3, 5, and 7, the transform is done in order (M)(N)[log(N) + log(M)] operations; otherwise the transform is
done in order (M)(N)(N + M) operations.
14.1.8.b: Example
In the following example M is 4, N is 2, and the (4,1)-th and (4,2)-th elements of z are one (the rest of the elements of z are zero). The (m,n)-th element
of the transform is therefore equal to
__
__
exp{-2 pi \/-1 [(m - 3) / 4 - (n - 2) / 2]} + exp[-2 pi \/-1 (m - 3) / 4]
If you enter
z = [{0, 0, 0, 1}, {0, 0, 0, 1}]
fft2d(z)
O-Matrix replies
{
[
[
[
[
}
(0,0)
(0,0)
(0,0)
(0,0)
,
,
,
,
(-2,0) ]
(0,2) ]
(2,0) ]
(0,-2) ]
Due to numerical limitations, some of the zeros may be output as numbers that are nearly 0.
14.1.9: Two Dimensional Inverse Fourier Transform
Syntax ifft2d(z)
14.1.9.a: Description
Returns the complex two-dimensional centered inverse Fourier transform of z, where z is an integer, real, double-precision or complex matrix with an
even number of rows and columns. If M is the number of rows in z and N is the number of columns in z, the (i,j)-th element of the return value is equal
to
M
---->
----m = 1
N
---->
----n = 1
z
{
__ [ (i - M/2 - 1) (m - M/2 - 1) / M ] }
exp{ 2 pi \/-1 [
+
] }
m,n
{
[ (j - N/2 - 1) (n - N/2 - 1) / N ] }
The return value has the same type and dimension as z. If the only prime factors of M and N are 2, 3, 5, and 7, the transform is done in order
(M)(N)[log(N) + log(M)] operations; otherwise the transform is done in order (M)(N)(N + M) operations.
14.1.9.b: Example
In the following example M is 4, N is 2, and the (4,1)-th and (4,2)-th elements of z are one (the rest of the elements of z are zero). The (i,j)-th element of
the transform is therefore equal to
__
__
exp{2 pi \/-1 [(i - 3) / 4 - (j - 2) / 2]} + exp[2 pi \/-1 (i - 3) / 4]
If you enter
z = [{0, 0, 0, 1}, {0, 0, 0, 1}]
ifft2d(z)
O-Matrix replies
{
[
[
[
[
}
(0,0)
(0,0)
(0,0)
(0,0)
,
,
,
,
(-2,0) ]
(0,-2) ]
(2,0) ]
(0,2) ]
Due to numerical limitations, some of the zeros may be output as numbers that are nearly 0.
14.1.10: Two Dimensional Discrete Fourier Transform
Syntax dft2d( z)
14.1.10.a: Description
Returns the complex two-dimensional discrete Fourier transform of z, where z is an integer, real, double-precision or complex matrix. If M is the
number of rows in z and N is the number of columns in z, the (m,n)-th element of the return value is equal to
M
---->
----i = 1
N
---->
----j = 1
z
{
__ [ (i - 1) (m - 1) / M ] }
exp{ -2 pi \/-1 [
+
] }
i,j
{
[ (j - 1) (n - 1) / N ] }
If the only prime factors of M and N are 2, 3, 5, and 7, the transform is done in order (M)(N)[log(N) + log(M)] operations; otherwise the transform is
done in order (M)(N)(N + M) operations.
14.1.10.b: Example
In the following example M is 4, N is 2, and the (4,1)-th and (4,2)-th elements of z are one (the rest of the elements of z are zero). The (m,n)-th element
of the transform is therefore equal to
__
__
exp{-2 pi \/-1 [(m - 1)3/4]} + exp{-2 pi \/-1 [(m - 1)3/4 + (n - 1)/2]}
which is also equal to
__
__
exp{-2 pi \/-1 [(m - 1)3/4]} * ( 1 + exp{-2 pi \/-1 [(n - 1)/2]})
If you enter
z = [{0, 0, 0, 1}, {0, 0, 0, 1}]
dft2d(z)
O-Matrix replies
{
[
[
[
[
}
(2,0) , (0,0) ]
(0,2) , (0,0) ]
(-2,0) , (0,0) ]
(0,-2) , (0,0) ]
14.1.10.c: Mlmode
In Mlmode: 25 , this function is automatically included: 3.9 as fft2 instead of dft2d. If in Mlmode you enter
z = [0 0 0 1; 0 0 0 1]';
fft2(z)
O-Matrix replies
{
[
[
[
[
}
(2,0)
(0,2)
(-2,0)
(0,-2)
,
,
,
,
(0,0)
(0,0)
(0,0)
(0,0)
]
]
]
]
14.1.11: Two Dimensional Inverse Discrete Fourier Transform
Syntax idft2d(z)
14.1.11.a: Description
Returns the complex two-dimensional inverse discrete Fourier transform of z, where z is an integer, real, double-precision or complex matrix. If M is
the number of rows in z and N is the number of columns in z, the (m,n)-th element of the return value is equal to
1
--N M
M
---->
----i = 1
N
---->
----j = 1
z
{
__ [ (i - 1) (m - 1) / M ] }
exp{ +2 pi \/-1 [
+
] }
i,j
{
[ (j - 1) (n - 1) / N ] }
If the only prime factors of M and N are 2, 3, 5, and 7, the transform is done in order (M)(N)[log(N) + log(M)] operations; otherwise the transform is
done in order (M)(N)(N + M) operations.
14.1.11.b: Example
In the following example M is 4, N is 2, and the (4,1)-th and (4,2)-th elements of z are one (the rest of the elements of z are zero). The (m,n)-th element
of the transform is therefore equal to
__
__
exp{+2 pi \/-1 [(m - 1)3/4]}/8 + exp{+2 pi \/-1 [(m - 1)3/4 + (n - 1)/2]}/8
which is also equal to
__
__
exp{+2 pi \/-1 [(m - 1)3/4]} * ( 1 + exp{+2 pi \/-1 [(n - 1)/2]}) / 8
If you enter
z = [{0, 0, 0, 1}, {0, 0, 0, 1}]
idft2d(z)
O-Matrix replies
{
[
[
[
[
}
(0.25,0) , (0,0) ]
(0,-0.25) , (0,0) ]
(-0.25,0) , (0,0) ]
(0,0.25) , (0,0) ]
14.1.11.c: Mlmode
In Mlmode: 25 , this function is automatically included: 3.9 as ifft2 instead of idft2d. If in Mlmode you enter
z = [0 0 0 1; 0 0 0 1]';
ifft2(z)
O-Matrix replies
{
[
[
[
[
}
(.25,0)
(0,-.25)
(-.25,0)
(0,.25)
,
,
,
,
(0,0)
(0,0)
(0,0)
(0,0)
]
]
]
]
14.1.12: Circular Shift That Centers a Discrete Fourier Transform
Syntax
fftshift(z)
14.1.12.a: Description
circularly shifts the elements of the matrix z so that the first row corresponds to the center row of that result, and the first column of z corresponds to
the center column of the result.
14.1.12.b: Fourier Transforms
If z is a vector and the result of a one dimensional discrete transform or if it is a matrix and the result of a two dimension discrete transform, fftshift
shifts the zero frequency to the center of the grid.
14.1.12.c: Example
If you enter
z = 1 :: 4
fftshift(z)
{
3
4
1
2
}
14.1.12.d: Reference
In O-Matrix mode, the routine dft: 14.1.1 performs the discrete transform and the routine fft: 14.1.3 does this shifting automatically. In Mlmode: 25 ,
fft: 14.1.1.c is the discrete transform.
14.2: Kalman-Bucy Filtering and Smoothing
14.2.a: Contents
kalman: 14.2.1
Advancing A Linear Kalman-Bucy Filter One Step At a Time
itrsmo: 14.2.2
Nonlinear Kalman-Bucy Filtering And Smoothing
AffineKbs: 14.2.3 The Affine Kalman Bucy Smoother and Marginal Likelihood
14.2.1: Advancing A Linear Kalman-Bucy Filter One Step At a Time
Syntax kalman(xin, Pin, z, R, Phi, Q, H, xout, Pout)
14.2.1.a: Description
Executes one step of the linear Kalman-Bucy filter. The values xin, Pin, z, R, Phi, Q, and H may be either real or double-precision. These values are
input and are not changed. The column vector xin specifies the estimate for the state vector at the initial time. The square matrix: 26.ak Pin has the
same number of rows as xin and specifies the covariance of xin as an estimate for the initial state. The column vector z contains the value of the data at
the new time (not the initial time). The square matrix Phi has the same number of rows as xin and specifies the transition matrix. This matrix is the
deterministic part of the mapping that transforms the initial state to the new state. The square matrix Q has the same number of rows as xin and is the
covariance of the random part of the mapping that transforms the initial state to the new state. The matrix H has the same number of rows as z and the
same number of columns as xin has rows. This matrix is the deterministic part of the mapping from the new state value to the measurement value z.
The square matrix R has the same number of rows as z and is the covariance of the random part of the mapping from the current state to the current
measurement value.
If all of the input variables have the same type, the output values xout and Pout will have that type and all of the calculations will be done in the
corresponding precision. The input value xout has no effect. Its output value is set to the expected value of the state vector at the new time (given the
value of the measurement z). The input value of Pout has no effect. Its output value is set to the covariance of xout as an estimate of the state at the
new time.
Let xinitial and xnew denote the true value of the state vector at the initial and new times, respectively. The transition model is
xnew = Phi xinitial + w,
where w is a mean zero random variable with covariance Q. The measurement model is
z
= H xnew + v,
where v is a mean zero random variable with covariance R. If the estimate xin and the random variables w and v are independent and normally
distributed, the state estimate xout is the maximum likelihood estimate for the state. In this case, the estimate xout is normally distributed and Pout is
its covariance matrix.
14.2.1.b: Example
The following example uses kalman to advance the state estimate and its covariance two time steps. The example is included as one program below to
make it easier to copy and paste into the O-Matrix command line. A discussion: 14.2.1.c of the example follows the program
clear
xinitial
alpha
Pin
u
xin
dt
Phi
=
=
=
=
=
=
=
{10., 10., 1., 1.}
2.
alpha^2 * identity(4)
alpha * snormal(4, 1)
xinitial + u
1.
{[1., 0., dt, 0.], ...
[0., 1., 0., dt], ...
[0., 0., 1., 0.], ...
[0., 0., 0., 1.] ...
}
beta
Q
w
xnew
H
=
=
=
=
=
1.
beta^2 * identity(4)
beta * snormal(4, 1)
Phi * xinitial + w
{[1., 0., 0., 0.], ...
[0., 1., 0., 0.] ...
}
gamma
= .5
R
= gamma^2 * identity(2)
v
= gamma * snormal(2, 1)
z
= H * xnew + v
xout
= novalue
Pout
= novalue
kalman(xin, Pin, z, R, Phi, Q, H, xout, Pout)
print [xnew, xout]
xinitial = xnew
xin
= xout
Pin
= Pout
beta
= .01
Q
= beta^2 * identity(4)
w
= beta * snormal(4, 1)
xnew
= Phi * xinitial + w
gamma
= .01
R
= gamma^2 * identity(2)
v
= gamma * snormal(2, 1)
z
= H * xnew + v
kalman(xin, Pin, z, R, Phi, Q, H, xout, Pout)
print [xnew, xout]
14.2.1.c: Discussion
This example is a two-dimensional tracking application of the Kalman-Bucy filter. We initialize the random number generator and clear any existing
function definitions with the command
clear
For simulation purposes, the true initial location is 10 units east and 10 units north, and the initial velocity is northeast with a speed of sqrt(2):
xinitial = {10., 10., 1., 1.}
The components of the initial state estimate are independent and each has a standard deviation alpha. We simulate noise u, with the corresponding
covariance Pin, and the initial state estimate xin, by entering
alpha
Pin
u
xin
=
=
=
=
2.
alpha^2 * identity(4)
alpha * snormal(4, 1)
xinitial + u
The model for the new position is the old position plus the velocity times the time step dt, plus noise. The model for the new velocity is the old
velocity plus noise. The corresponding transition matrix, Phi, is
dt
Phi
= 1.
= {[1.,
[0.,
[0.,
[0.,
0.,
1.,
0.,
0.,
dt,
0.,
1.,
0.,
0.], ...
dt], ...
0.], ...
1.] ...
}
The east and north components of the noise in the transition model are independent and each has standard deviation beta. We simulate noise, w, with
the corresponding covariance Q, and the true state value at the new time xnew, by entering
beta
Q
w
xnew
=
=
=
=
1.
beta^2 * identity(4)
beta * snormal(4, 1)
Phi * xinitial + w
The measurement has two independent components. The first is the east position and the second is the north position. The corresponding measurement
matrix H, is
H
= {[1., 0., 0., 0.], ...
[0., 1., 0., 0.] ...
}
The measurement noise is independent and each component has standard deviation gamma. We simulate noise v with the corresponding covariance R,
and the measurement z, by entering
gamma
R
v
z
=
=
=
=
.5
gamma^2 * identity(2)
gamma * snormal(2, 1)
H * xnew + v
In an actual tracking problem the noise values u, v, and w and true state values xinitial and xnew are not known. We estimate the new state vector
xnew by
xout
= novalue
Pout
= novalue
kalman(xin, Pin, z, R, Phi, Q, H, xout, Pout)
We can compare the true value xnew, and its estimate xout, by
print [xnew, xout]
entering
to which O-Matrix will respond
{
[
[
[
[
}
10.456 , 10.8956 ]
11.7081 , 11.0963 ]
-0.588691 , 2.18574 ]
1.4681 , 2.66793 ]
The first two components of xout are the estimates of east and north position. The second two components are estimates of east and north velocity.
You will notice that the estimates of position are better than the estimates of velocity. This is because we are measuring position directly and are
inferring the velocity through the transition equation.
We begin another time step by advancing the true position, the estimated position, and the covariance of the estimate.
xinitial = xnew
xin
= xout
Pin
= Pout
Next we simulate a transition with much smaller error
beta
Q
w
xnew
=
=
=
=
.01
beta^2 * identity(4)
beta * snormal(4, 1)
Phi * xinitial + w
Next we simulate a measurement with much smaller error
gamma
R
v
z
=
=
=
=
.01
gamma^2 * identity(2)
gamma * snormal(2, 1)
H * xnew + v
Then we compute our new estimate and compare it to the true value by entering
kalman(xin, Pin, z, R, Phi, Q, H, xout, Pout)
print [xnew, xout]
to which O-Matrix will respond
{
[
[
[
[
9.88414 ,
13.1767 ,
-0.602134
1.48339 ,
9.89429 ]
13.1708 ]
, 0.746347 ]
2.02662 ]
}
14.2.2: Nonlinear Kalman-Bucy Filtering And Smoothing
Syntax itrsmo(function meas, function tran, ...
level, M, N, xini, Pinv)
itrsmo(function meas, function tran, ...
level, M, N, xini, Pinv, Cout)
14.2.2.a: Description
Returns the extended Kalman-Bucy filter or smoother estimate for the value of the state vector at each time point. The k-th column of the return value
is the estimate for the state vector at the k-th time point. This routine allows for general nonlinear measurement and transition functions. The input
arguments xini and Pinv and the outputs from the functions meas and tran must be real or double-precision. If they all have the same type, Cout and
the return value of itrsmo will have that type and all of the calculations will be done in the corresponding precision.
The iterated smoother combines the decomposition technique of Kalman filtering with a Gauss-Newton method to solve a large nonlinear least squares
problem. The integer scalar M specifies the number of Gauss-Newton iterations that the iterated smoother performs. If M is 0, the result is the same as
for the extended Kalman filter; if M is 1, the result is the same as for the affine Kalman smoother. If the integer scalar level is 1, the residual sum of
squares is printed at each iteration. If level is 0, no tracing is done. The integer scalar N specifies the number of time points at which there are
measurement values. The column vector xini specifies an estimate for the initial value of the true state vector. The square matrix: 26.ak Pinv has the
same number of rows as xini and specifies the inverse of the covariance for the estimate xini. The model for the initial estimate is
xini = x1 + e1
where x1 is the true, but unknown, value of the state vector at time point number one, e1 is a mean zero random vector with the same dimension as
xini, and the covariance of e1 is equal to the inverse of Pinv.
If Cout is present, its input value does not matter and its output value contains the covariance that corresponds to each of the state estimates. The row
dimension of Cout is the square of the row dimension of xini and its column dimension is equal to N. The k-th column of Cout contains the variance of
the state estimate for the k-th time point. This could be converted to a covariance matrix C as follows
C = Cout.col(k)
dim C(N, N)
meas(k, sk, hk, dhk, zk, Rinvk)
The measurement model and the data values are specified by the function meas. The measurement model for the k-th time point is
zk = h(xk) + vk
where h(x) is a known function, xk is the true, but unknown, value of the state vector at time point k, vk is a mean zero random vector with the same
dimension as zk, and the covariance of vk is equal to the inverse of Rinvk. The input value of k is an integer scalar between 1 and N that specifies the
current time point. The input value of sk has the same dimension as xini and specifies a value for the state vector at time index k. The other arguments
to meas are outputs and their input values have no effect. The value hk is set to the value of the measurement function at sk; that is, h(sk). This value
must have the same dimensions as zk. The value dhk is set to the derivative of the measurement function at sk; that is, h'(sk). (The prime symbol here
denotes the derivative of h, not the transposition of a matrix.) The (i,j)-th element of dhk is the partial derivative of the i-th element of h(x) with
respect to the j-th element of x. The matrix dhk must have the same number of rows as zk and its column dimension must equal the row dimension of
xini. The value zk is set to the data value for this time point. The matrix Rinvk is set to the inverse of the data covariance for this time point. It must be
a symmetric: 26.am positive definite matrix with the same number of rows as zk. (The matrix Rinvk is positive definite if
T
Rinvk u > 0
whenever u is a nonzero
u
column vector with the same number of rows as Rinvk.)
tran(k, sk, gk, dgk, Qinvk)
The transition model is specified by the function tran. This model for the k-th time interval is
xkp = g(xk) + wk
where g(x) is a known function, xk is the true, but unknown value of the state vector at time point k, xkp is the true, but unknown value of the state
vector at time point k+1, wk is a mean zero random vector with the same dimension as xini, and the covariance of wk is equal to the inverse of Qinvk.
The input value of k is an integer scalar between 1 and N-1 that specifies the current time interval. (Interval k is the time between the measurement at
time point k and at time point k+1.) The input value of sk has the same dimension as xini and specifies a value for the state vector at time point k. The
other arguments to tran are outputs and their input values have no effect. The value gk is set to the value of the transition function at sk; that is, g(sk).
This value must have the same dimensions as xini. The value dgk is set to the derivative of the transition function at sk; that is, g'(sk). The (i,j)-th
element of dgk is the partial derivative of the i-th element of g(x) with respect to the j-th element of x. The matrix dgk must be a square matrix with
the same number of rows as xini. The matrix Qinvk is set to the inverse of the transition covariance for the time interval; it must be a symmetric
positive definite matrix with the same number of rows as xini.
14.2.2.b: Example
The following example runs an iterated smoother, tracing the residual sum of squares and then compares the estimates with the true solution that was
used for simulating the data. The example is included as one program below to make it easier to copy and paste into the O-Matrix command line. A
discussion: 14.2.2.c of the example follows the program
clear
x1
alpha
Pinv
e1
xini
dt
Phi
=
=
=
=
=
=
=
{10., 10., 1., 1.}
2.
identity(4) / alpha^2
alpha * snormal(4, 1)
x1 + e1
1.
{[1., 0., dt, 0.], ...
[0., 1., 0., dt], ...
[0., 0., 1., 0.], ...
[0., 0., 0., 1.] ...
}
beta = 1.
w1
= beta * snormal(4, 1)
x2
= Phi * x1 + w1
function tran(k, sk, gk, dgk, Qinvk) begin
global Phi, beta
gk
= Phi * sk
dgk
= Phi
Qinvk = identity(4) / beta^2
return
end
function h(x) begin
h1 = sqrt( x(1)^2 + x(2)^2 )
h2 = sqrt( (x(1) - 20.)^2 + x(2)^2 )
return {h1, h2}
end
function dh(x) begin
hx
= h(x)
dh11 = x(1) / hx(1)
dh12 = x(2) / hx(1)
dh21 = (x(1) - 20.) / hx(2)
dh22 = x(2) / hx(2)
return {[dh11, dh12, 0., 0.], ...
[dh21, dh22, 0., 0.]}
end
gamma = .5
v1
= gamma * snormal(2, 1)
v2
= gamma * snormal(2, 1)
z
= [ h(x1) + v1, h(x2) + v2 ]
function meas(k, sk, hk, dhk, zk, Rinvk) begin
global z, gamma
hk
= h(sk)
dhk
= dh(sk)
zk
= z.col(k)
Rinvk = identity(2) / gamma^2
return
end
level = 1
M
= 3
N
= 2
xhat = itrsmo(function meas, function tran, level, M, N, xini, Pinv)
print [xhat.col(1), x1]
print [xhat.col(2), x2]
14.2.2.c: Discussion
We initialize the random number generator and clear any existing function definitions with the command
clear
For simulation purposes, the true initial location is 10 units east and 10 units north, and the initial velocity is northeast with speed equal to sqrt(2)
x1
= {10., 10., 1., 1.}
The components of the initial state estimate are independent and each has a standard deviation alpha. We simulate noise, e1, with the corresponding
inverse covariance, Pinv, and the initial state estimate, xini, by entering
alpha
Pinv
e1
xini
=
=
=
=
2.
identity(4) / alpha^2
alpha * snormal(4, 1)
x1 + e1
The model for the new position is the old position plus the velocity times the time step dt, plus noise. The model for the new velocity is the old
velocity plus noise. The corresponding transition matrix, Phi, is
dt
Phi
= 1.
= {[1.,
[0.,
[0.,
[0.,
0.,
1.,
0.,
0.,
dt,
0.,
1.,
0.,
0.], ...
dt], ...
0.], ...
1.] ...
}
The east and north components of the noise in the transition model are independent and each has standard deviation beta. We simulate noise, w1, and
the true state value at the new time, x2, by entering
beta
w1
x2
= 1.
= beta * snormal(4, 1)
= Phi * x1 + w1
We define the transition model by entering
function tran(k, sk, gk, dgk, Qinvk) begin
global Phi, beta
gk
= Phi * sk
dgk
= Phi
Qinvk = identity(4) / beta^2
return
end
The transition function, g(x) = Phi x, is linear, and its derivative
is thus simple to calculate. The measurement function is more complicated because
it is nonlinear.
The measurement has two independent components. The first component is the distance from the state vector's position to the point (0, 0). The
second is the distance from the state vector to the point (20, 0). The corresponding measurement function, h(x), is defined by
function h(x) begin
h1 = sqrt( x(1)^2 + x(2)^2 )
h2 = sqrt( (x(1) - 20.)^2 + x(2)^2 )
return {h1, h2}
end
We also use the derivative of the measurement function; that is,
function dh(x) begin
hx
= h(x)
dh11 = x(1) / hx(1)
dh12 = x(2) / hx(1)
dh21 = (x(1) - 20.) / hx(2)
dh22 = x(2) / hx(2)
return {[dh11, dh12, 0., 0.], ...
[dh21, dh22, 0., 0.]}
end
Note that the (i,j)-th element of the return value is the partial derivative of the i-th element of h(x) with respect to the j-th element of x. The function
dh(x) calculates these derivatives one at a time.
The measurement noise is independent and each component has standard deviation gamma. We simulate noise (v1 and v2) and the measurements (
z.col(1) and z2.col(2)) by entering
gamma
v1
v2
z
=
=
=
=
.5
gamma * snormal(2, 1)
gamma * snormal(2, 1)
[ h(x1) + v1, h(x2) + v2 ]
We define the measurement model by entering
In an
by
function meas(k, sk, hk, dhk, zk, Rinvk) begin
global z, gamma
hk
= h(sk)
dhk
= dh(sk)
zk
= z.col(k)
Rinvk = identity(2) / gamma^2
return
end
actual tracking problem the noise values e1, v1, e2, v2, and
level
M
N
xhat
=
=
=
=
true state values x1 and x2 are not known. We estimate the state vectors x1 and x2
1
3
2
itrsmo(function meas, function tran, level, M, N, xini, Pinv)
to which O-Matrix responds
itrsmo: residual sum of squares = 45.1148
itrsmo: residual sum of squares = 3.27125
itrsmo: residual sum of squares = 2.94872
These are the residual sum of squares corresponding to the state estimate at the beginning of each iteration. We compare the true and estimated state
vector at time point 1 by entering
print [xhat.col(1), x1]
to which O-Matrix responds
{
[
[
[
[
}
10.5083
9.75987
1.14223
2.31955
,
,
,
,
10 ]
10 ]
1 ]
1 ]
We then compare the true and estimated state vector at time point 2 by entering
print [xhat.col(2), x2]
to which O-Matrix responds
{
[
[
[
[
}
11.244 , 10.456 ]
12.2182 , 11.7081 ]
1.14223 , -0.588691 ]
2.31955 , 1.4681 ]
The second two components of xhat.col(1) and xhat.col(2) are the velocity estimates at time point 1 and time point 2. These estimates are the
same because we are not measuring velocity directly. We are inferring velocity by differencing positions and we only have two time points.
14.2.3: The Affine Kalman Bucy Smoother and Marginal Likelihood
Syntax [Obj, L, Xhat] = ...
AffineKbs(function meas, function tran, N, X, y)
14.2.3.a: Bell:00
The marginal likelihood for parameters in a discrete Gauss-Markov process, IEEE Transactions On Signal Processing, March 2000.
14.2.3.b: Description
Calculates the Kalman-Bucy smoother solution and the marginal likelihood for the affine case using the formula in Theorem 8 of [Bell:00]: 14.2.3.a .
14.2.3.c: Notation
Math
n
m
N
z_k
R_k(y)
h_k(x,
Q_k(y)
g_k(x,
Description
number of components in the state vector at one time point
number of components in the data vector at k-th time index
number of time points
value of the data vector at k-th time index
variance of v_k; i.e., noise in the measurement equation
y) expected value of z_k given x at k-th time index
variance of w_k; i.e., the noise in the transition equation
y) expected value of x at next time index given value at k-th time index
14.2.3.d: Measurement Model
[zk,
hk, dhk, Rk] = meas(k, x, y)
The input value k is an integer between 1 and N. The input value x is a the real or double-precision column vector of length n. The input value y is a the
real or double-precision column vector equal to the corresponding argument of AffineKbs. The output values are all real or double-precision and are
specified by
Notation Dimension Description
zk
(m, 1)
measurement at k-th time index
hk
(m, 1)
h_k(x, y)
dhk
(m, n)
d/dx [h_k(x, y)]
Rk
(m, m)
R_k(y)
14.2.3.e: Transition Model
[gk,
dgk, Qk] = tran(k, x, y)
The input value k is an integer between 0 and N. The input value x is a the real or double-precision column vector of length n. The input value y is a the
real or double-precision column vector equal to the corresponding argument of AffineKbs. The output values are all real or double-precision and are
specified by
Notation Dimension Description
gk
(n, 1)
g_k(x, y)
(n, n)
d/dx [g_k(x, y)]
dgk
Qk
(n, n)
Q_k(y)
Note that as specified in [Bell:00]: 14.2.3.a : if k is zero, g_k(x, y) is defined to be the initial state estimate, and if k is N, g_k(x, y) is defined to be
zero. Also note that dgk must be zero for these cases and that Qk can be any invertible matrix.
14.2.3.f: Other Inputs
The integer scalar N specifies the number of time index values. The real or double-precision column vector X is a column vector of length N * n
containing a sequence of state values for all time around which the affine approximations of the model functions are made. The real or doubleprecision vector y specifies the value of the parameter vector.
14.2.3.g: Outputs
The output value Obj is a real or double-precision scalar containing the affine approximation for the marginal likelihood as specified in Theorem 8 of
[Bell:00]: 14.2.3.a . The output value L is a real or double precision scalar containing the value of the joint likelihood corresponding to Xhat and y; i.e.,
the term L(Xhat(y), y) in Theorem 8 of [Bell:00]: 14.2.3.a . The output value Xhat is a real or double-precision column vector of length N * n
containing a sequence of state values for all time. This is the solution to the affine smoother problem corresponding to X and y.
14.2.3.h: Example
The following example uses AffineKbs to estimate the initial dose, noise levels, and decay rate corresponding to a one compartment stochastic model.
The elements of the parameter vector y are
y(1) initial dose
y(2) decay rate
y(3) process variance
y(4) measurement variance
clear
# initialize O-Matrix
N
= 50
# number of data points
T
= 1.:1.:N
# grid of time points between 1 and N
Zsim = fill(0., N, 1)
# vector that will hold simulated data
B
= 1.
# Basal value of concentration
#
# define the transition function
function [gk, dgk, Qk] = tran(k, x, y) begin
global N, T, B
# make variables visible in function
if k == 0 then begin
Phi = exp(-y(2) * T(1))
# transition matrix for differential equation
gk = (y(1) - B) * Phi + B
# solution corresponding to initial x = y(1)
dgk = 0.
# derivative of solution w.r.t x
Qk = y(3)
# variance in transition equation
end else if k == N then begin
gk = 0.
# values for this case not used
dgk = 0.
Qk = 1.
# Qk must be invertible
end else begin
dt = T(k+1) - T(k)
# time to next measurement
Phi = exp(-y(2) * dt)
# transition matrix for differential equation
gk = (x - B) * Phi + B
# solution corresponding to previous x value
dgk = Phi
# derivative of solution w.r.t x
Qk = y(3)
# variance in transition equation
end
return
end
#
# define the measurement function
function [zk, hk, dhk, Rk] = meas(k, x, y) begin
global Zsim, T
# make visible in function
zk = Zsim(k)
# data value for this time index
hk = x
# model for the data
dhk = 1.
# derivative of the model w.r.t. x
Rk = y(4)
# variance of the model
return
end
#
# simulation
ranseed
# seed the random number generator
ysim = {10., 5./N, .1, .1}
# parameter values for simulation
[gk, dgk, Qk] = tran(0, novalue, ysim)
# initial state estimate and variance
for k = 1 to N begin
wk
= snormal(1, 1) * sqrt(Qk)
# process noise
xk
= gk + wk
# next state value for this realization
[zk, hk, dhk, Rk] = meas(k, xk, ysim)
# measurement information
vk
= snormal(1, 1) * sqrt(Rk)
# measurement noise
Zsim(k)
= hk + vk
# measurement value
[gk, dgk, Qk] = tran(k, xk, ysim)
# transition information
end
#
# arguments to optimizer
X0
= fill(0d0, N, 1)
# initial estimate of state for all indices
yin
= ysim / 2
# initial value of parameters
step = ysim * 1e-3
# convergence criteria and step size
mitr = 100
# maximum number of iterations
level = 1
# level of tracing
function f = AffineKbs(meas, tran, N, X0) # objective function
#
# optimization
yout = conjdir(function f, yin, step, mitr, level)
yest = yout.col(coldim(yout))
#
print "Parameter vector used for simulation =", ysim'
print "Estimated parameter vector
=", yest'
#
[Obj, L, Xhat] = AffineKbs(function meas, function tran, N, X0, yest)
gplot(T, Zsim, "square")
# simulated data values
gplot(T, Xhat, "solid")
# affine smoother estimate for state values
14.3: Auto-Regressive And Moving Average Filtering
Syntax filter(a, b, x, s)
See Also mlmode_filter: 14.4 , conv: 15.53 , polmul: 18.6 , kalman: 14.2.1 , arcov: 14.5
14.3.a: Description
Filters the input sequence x using both the auto-regressive coefficients, a, and moving average coefficients b. If x is white noise, the return value is the
process corresponding to a and b. The arguments a, b, x, and s can be either integer, real, double-precision or complex. The arguments must all
be column vectors but do not have to be the same type. The return value has the type that results from coercion: 4.4 between the arguments types. Let
na, nb, nx and ns, be the lengths of a, b, x, and s respectively. The value ns must satisfy the conditions ns > na - 1, ns > nb - 1 , and ns < nx.
The return vector y has length nx, and
ARMA
if i < ns,
y
=
s
i
if i > ns,
i
y
=
b
i
x
1
+
i
-
b x
+ . . . + b x
2 i-1
nb i-nb+1
a y
- . . . - a y
2 i-1
na i-na+1
Note that the first element of a is not used.
14.3.b: Example
If you enter
x = {1, 2, 3}
a = {1, -1}
b = {1, 1}
s = 0
filter(a, b, x, s)
O-Matrix will respond
{
0
3
8
}
Note that
y
=
s
1
y
=
x
2
y
=
0
=
3
=
8
1
+ x
2
=
x
3
+ y
1
+ x
3
1
+ y
2
2
(Also note that the first element of a was not used.)
14.4: Auto-Regressive And Moving Average Filtering (Mlmode)
Syntax filter(b, a, x)
See Also filter: 14.3 , conv: 15.53 , polmul: 18.6 , kalman: 14.2.1 , arcov: 14.5
14.4.a: Description
Filters the input sequence x using both the auto-regressive coefficients, a, and moving average coefficients b. If x is white noise, the return value is the
process corresponding to a and b. The arguments a, b, and x can be either integer, real, double-precision or complex. The arguments must all be
vectors but do not have to be the same type. The return value has the type that results from coercion: 4.4 between the arguments types and the same
dimensions as x. Let na be the length of a, nb be the length of b, A be a/a(1), and B be b/a(1). The return vector y has the same length as x and is
given by
ARMA
y
=
B
i
x
1
+
i
B
x
x
nb i-nb+1
A y
- . . . - A y
2 i-1
na i-na+1
2
-
+ . . . + B
i-1
where negative subscripts correspond to zero values.
14.4.b: Example
If in Mlmode: 25 you enter
x = [1; 2; 3];
a = [1; -1];
b = [1; 1];
filter(b, a, x)
O-Matrix will respond
{
1
4
9
}
Note that the first element of a is one so A and B are equal to a and b respectively.
y
=
1
x
=
1
1
y
=
x
2
y
+ x
2
=
3
x
+ y
1
+ x
3
=
4
=
9
1
+ y
2
2
14.5: Simulating An AR Process With A Specified Covariance
Syntax arcov( N, M, r)
14.5.a: Description
Returns M columns, each of which is a realization of a Gaussian AR process with an order that is one less than the row dimension of r, where N is an
integer scalar specifying the number of points in each realization of the AR process, M is an integer scalar specifying the number of realizations, and r
is a real or double-precision column vector such that for L = 1 to the row dimension of r, the expected value of x(i,j) * x(i + L - 1,j) is equal
to r(L). The return value has N rows, M columns, and the same type as r.
If x is a Gaussian AR process of order m, there is a vector, a, such that
x = a w + a x
+ ... + a x
n
0 n
1 n-1
m n-m
where the {w(n)} are independent, normal, and have
a mean of 0 and a variance of 1.
14.5.b: Example
N = 200
M = 1
r = {1., .9}
y = arcov(N, M, r)
gtitle("AR(1) Simulation")
gplot(seq(N), y, "plus")
returns the following plot:
14.6: Estimating The Fourier Spectrum Of A Random Process
Syntax fspec( x, dt, taper)
See Also fft: 14.1.3 , dpss: 14.7 , arcov: 14.5 , filter: 14.3
14.6.a: Description
Returns an estimate for the Fourier spectrum of a random process using one or more tapers and realizations. Each column of the integer, real, doubleprecision, or complex column matrix x contains a realization of a random process X. The row dimension of x must be even (if its only prime factors are
2, 3, 5, and 7, an FFT is used and the calculation is quicker). The integer, real, or double-precision scalar dt specifies the time between the samples. The
i-th row of x corresponds to samples at time
t
=
(i - N / 2 - 1) dt
i
Each column of the integer, real, double-precision, or complex matrix taper specifies a tapering window where taper and x have the same number of
rows.
If N is the row dimension of x, the return value of fspec is a double-precision column vector of length N. The k-th element of the return value is the
spectral density estimate at frequency
f
=
k
k - N / 2 - 1
------------N dt
The Fourier spectrum of X, at frequency f, is defined as the limit as T goes to infinity of the expected value of
1 |
--- |
T |
T/2
2
/
__
|
| X(s) exp(-2 pi \/-1 f s) ds |
/
|
-T/2
The spectral estimate corresponding to the j-th column of x and the m-th column of taper is
N
2
1
| ----__
|
---- | >
taper
x
exp(-2 pi \/-1 f t ) dt |
N dt | ----i,m i,j
k i
|
i = 1
---------------------------------------------------------N
1
----2
--- >
taper
N
----i,m
i = 1
The returned value is a double-precision column vector of length N in which the k-th element is the average over all windows and realizations of the
estimate above. If x is real or double-precision, and 2 < k < N/2, the k-th element of the expression above is equal to the N-k+2-th element.
14.6.b: Example
The spectral estimate corresponding to a rectangular taper is sometimes referred to as the periodogram. The following program computes the spectral
estimate for 256 points of white noise using a rectangular taper. The noise is normally distributed with a mean of zero and variance of one, on a
uniform time grid between time 0 and 256. It then plots the spectral estimate
clear
#
N
= 256
x
= snormal(N, 1)
dt
= 1.
taper = fill(1, N, 1)
spec = fspec(x, dt, taper)
df
= 1. / (N * dt)
f
= (seq(N) - N / 2 - 1) * df
gyaxis("log")
gtitle("Spectrum of White Noise")
gplot(f, spec, "plus")
14.7: Discrete Prolate Spheroidal Sequences
Syntax dpss(N, m, w)
14.7.a: Description
Returns discrete prolate spheroidal sequences, where N an integer scalar specifying the number of points in each sequence, m is an integer scalar
specifying the number of sequences to return, and w is a real or double-precision scalar specifying the fractional bandwidth of the sequences such that
0 < w < .5, with a suggested value of 4./N. The sequence of order i is placed in the (i+1)-th column of the return value for i = 0, ... , m - 1.
The return value has m columns, N rows, and the same type as w.
These sequences are used as tapers for spectral estimation (see fspec: 14.6 ). There are two important factors corresponding to a taper: its bandwidth
(how wide a frequency range it allows leakage over) and its rejection (how much energy is reduced when it is outside that frequency range). If w is
small, the frequency range of the allowed leakage will be small. On the other hand, a smaller w leads to more energy leaking outside the allowed range
(poorer rejection).
14.7.b: Example
N = 128
m = 1
w = 4d0 / N
S = dpss(N, m, w)
gtitle("Discrete Prolate Spheroidal Window")
gplot(seq(N)/double(N), S)
returns the following plot:
14.8: Computing The Wavelet Transform
Syntax wavelet( m, x)
14.8.a: Description
Returns the forward wavelet transform of x where x is a real, double-precision, or complex column vector with length equal to a power of 2 (i.e., 2, 4,
8, ...). The integer scalar m specifies the number of wavelet coefficients. If m is 2, the Haar coefficients are used. If m is 4 or 6, the Daubechies
coefficients are used. These are the only values of m that are currently implemented.
The vector c of length m is used below to denote the wavelet coefficients. The smoothing operator S applied to a vector y is a vector S(y) with half the
number of elements as y. The i-th element of S(y) is defined by
S (y)
i
= c
y
1
+ c
2i-1
y
2
+ . . . + c
2i
y
m
2i+m-2
If an index of y in the summation above exceeds the length of the vector y, the vector is extended circularly; that is, if n is the length of y and j is
greater than n, y(j) is defined to be y(j-n). The detail operator D applied to a vector y is a vector D(y) with half the number of elements as y. The i-th
element of D(y) is defined by
D (y) = c y
- c
y
+ . . . - c y
i
m 2i-1
m-1 2i
1 2i+m-2
where y is extended circularly when its index exceeds its length.
The wavelet coefficients are chosen so that the i-th element of D(y) is 0 if the m elements between y(2i-1) and y(2i+m-2) are constant. If m > 4, the
i-th element of D(y) is 0 if the m elements satisfy an affine function of i (an affine function has a linear and constant term). If m > 6, the i-th element
of D(y) is 0 if the m elements satisfy a quadratic function of i.
We use n to denote the length of x and we use r to denote the return value. The last n/2 elements of r contain D(x); that is,
D(x) = {r(n/2+1), r(n/2+2), . . . , r(n)}
The previous n/4 elements of r contain D(S(x)); that is,
D(S(x)) = {r(n/4+1), r(n/4+2), . . . , r(n/2)}
This pattern continues with the details of S(S(x)) stored starting at index n/8+1 of the return value. This procedure is repeated until the last
smoothing value is in r(1) and the last detail is in r(2).
14.8.b: Example
We can compute the wavelet transform of a linear vector x by entering
x = real(seq(16))
m = 4
r = wavelet(m, x)
We can then print the high-order details by entering
format real "f6.3"
print r.row(9, 8)
to which O-Matrix will respond
{
0.000
0.000
0.000
0.000
0.000
0.000
0.000
-5.657
}
Note that all of the details are 0 except for the last one. This is because for 1 < i < n/2, the sequence
x(2i-1), x(2i), x(2i+1), x(2i+2)
is affine (n is 16 for our example). But when i = n/2, the sequence is
x(n-1), x(n), x(1), x(2)
which is not linear (due to the circular manner in which x is extended).
For i < n/2, the smoothing values are given by
S (x) = c x
+ c x
+ c x
+ c x
i
1 2i-1
2 2i
3 2i+1
4 2i+2
It follows that these smoothing values are an affine function of the index i for i < n/2. The next order details, D(S(x)), are given by
Thus
D (S(x)) = c S (x) - c S (x) +
i
4 2i-1
3 2i
when 2i+2 < n/2 these details are 0; that is
print r.row(5, 4)
c
2
S (x)
2i+1
the first two
+
c
S (x)
2i+2
elements of D(S(x))
4
are 0. We can print D(S(x)) by entering
to which O-Matrix will respond
{
0.000
0.000
0.732
-.7660
}
14.9: Inverse Wavelet Transform
Syntax iwavelet(m, y)
14.9.a: Description
Returns the inverse of the wavelet: 14.8 transform of y, where y is a real, double-precision or complex column vector with length equal to a power of
2. The integer scalar m specifies the number of wavelet coefficients. The forward wavelet transform is an invertible mapping; in fact, it is an
orthogonal mapping (a linear mapping that maps vectors to vectors with the same norm). This function is the inverse mapping of the forward wavelet
transform; that is, if y = wavelet(m, x) and z = iwavelet(m, y) it follows that z is equal to x.
14.9.b: Example
If you enter
x = real(seq(8))
y = wavelet(4, x)
z = iwavelet(4, y)
print z'
O-Matrix will respond
[ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
14.10: Normalized Butterworth Filter Polynomials
Syntax fnbut( n, numout, denout)
14.10.a: Description
Computes the numerator and denominator polynomials: 26.ac for a normalized Butterworth filter with n poles, where n is an integer greater than 0.
The input values of numout and denout have no effect. The output value of numout is set to the double-precision column vector corresponding to the
numerator polynomial of the Butterworth filter (numout is equal to the scalar 1 because normalized Butterworth filters have no zeros). The output
value of denout is set to the double-precision column vector corresponding to the denominator polynomial of the Butterworth filter. The filter's
response function is
|numout[s]|2
|---------|
|denout[s]|
and it is near 1 for s in the interval
__
[0, \/-1 ]
and near 0 for the rest of the positive imaginary axis.
14.10.b: Example
numout
denout
n
fnbut(n,
= novalue
= novalue
= 3
numout, denout)
xmin
= 1e-2
xmax
= 1e+2
ymin
= 1e-4
ymax
= 1e+1
cutoff = 1.
fcplot(xmin, xmax, ymin, ymax, cutoff, numout, denout)
returns the following plot:
14.11: Normalized Chebyshev Filter Polynomials
Syntax fncheb(n, eps, numout, denout)
14.11.a: Description
Computes the numerator and denominator polynomials: 26.ac for a normalized Chebyshev filter with n poles, where n is an integer greater than 0. The
real or double-precision scalar eps specifies the ripple parameter, 0 < eps < 1.
The input values of numout and denout have no effect. The output value of numout is set to the double-precision column vector corresponding to the
numerator polynomial of the Chebyshev filter (numout is equal to the scalar 1 because normalized Chebyshev filters have no zeros). The output value
of denout is set to the double-precision column vector corresponding to the denominator polynomial of the Chebyshev filter. The filter's response
function is
|numout[s]|2
|---------|
|denout[s]|
and it is near 1 for s in the interval
__
[0, \/-1 ]
and near 0 for the rest of the positive imaginary axis.
14.11.b: Example
numout
denout
= novalue
= novalue
n
= 3
eps
= .8
fncheb(n, eps,numout, denout)
xmin
= 1e-2
xmax
= 1e+2
ymin
= 1e-4
ymax
= 1e+1
cutoff = 1.
fcplot(xmin, xmax, ymin, ymax, cutoff, numout, denout)
returns the following plot:
14.12: Poles Of A Normalized Butterworth Filter
Syntax fnbpole( n)
14.12.a: Description
Returns the poles of a normalized Butterworth filter with n poles, where n is an integer scalar. Note that the poles come in conjugate pairs, so the
corresponding polynomial is real. The return value is a complex column vector of length n with each element corresponding to a pole.
14.12.b: Example
The following program computes the poles corresponding to a 7 pole Butterworth filter. It then converts the complex pole locations to polar
coordinates (r, theta) and plots them.
clear
#
p
= fnbpole(7)
r
= abs(p)
theta = atan2(imag(p), double(p))
theta = 180 * theta / PI
rmax
= 2.
rmajor = 2
tmajor = 4
style = "cross"
color = "black"
polar(r, theta, rmax, rmajor, tmajor, style, color)
14.13: Poles Of A Normalized Chebyshev Filter
Syntax fncpole( n)
14.13.a: Description
Returns the poles of a normalized Chebyshev filter with n poles and ripple parameter eps, where n is an integer scalar and eps is a real or doubleprecision scalar such that 0 < eps < 1. Note that the poles come in conjugate pairs, so the corresponding polynomial is real. The return value is a
complex column vector of length n with each element corresponding to a pole.
14.13.b: Example
The following program computes the poles corresponding to a 7 pole Chebyshev filter with .8 ripple parameter. It then converts the complex pole
locations to polar coordinates (r, theta) and plots them.
clear
#
n
= 7
eps
= .8
p
= fncpole(n, eps)
r
= abs(p)
theta = atan2(imag(p), double(p))
theta = 180 * theta / PI
rmax
= 2.
rmajor = 2
tmajor = 4
style = "cross"
color = "black"
polar(r, theta, rmax, rmajor, tmajor, style, color)
14.14: Converting From A Normalized To Continuous Bandpass Filter
Syntax fn2cbp(cutoff, numin, denin, numout, denout)
14.14.a: Description
Converts a normalized filter to a continuous bandpass filter. The real or double-precision row vector cutoff has two elements and specifies the cutoff
frequencies for the bandpass filter. The column vector numin has the same type as cutoff and specifies the numerator polynomial: 26.ac for the
normalized filter. The column vector denin has the same type as cutoff and specifies the denominator polynomial for the normalized filter.
The input values of numout and denout have no effect. The output value numout is set to the column vector representing the numerator polynomial for
the continuous bandpass filter. The output value denout is set to the column vector representing the denominator polynomial for the continuous
bandpass filter. The output values of numout and denout have the same type as cutoff.
The response of a continuous filter is
2
|num[s]|
|------|
|den[s]|
where num[s] is the numerator polynomial and den[s] is the denominator polynomial corresponding to the filter. The response of a normalized filter
is near 1 for s in the interval
__
[0, \/-1]
and near 0 for the rest of the positive imaginary axis. The response of the continuous bandpass filter is near 1 for s in the interval
__
__
[\/-1 cutoff(1), \/-1 cutoff(2)]
and near 0 for the rest of the positive imaginary axis.
14.14.b: Example
numin = 1.
denin = {1., sqrt(2.), 1.}
numout = novalue
denout = novalue
cutoff = [1., 2.]
fn2cbp(cutoff, numin, denin, numout, denout)
xmin = 1e-1
xmax = 1e+1
ymin = 1e-5
ymax = 1e+1
fcplot(xmin, xmax, ymin, ymax, cutoff, numout, denout)
returns the following plot:
14.15: Converting From A Normalized To Continuous Lowpass Filter
Syntax fn2clp(cutoff, numin, denin, numout, denout)
14.15.a: Description
Converts a normalized filter to a continuous lowpass filter. The real or double-precision scalar cutoff specifies the cutoff frequency for the lowpass
filter. The column vector numin has the same type as cutoff and specifies the numerator polynomial: 26.ac for the normalized filter. The column vector
denin has the same type as cutoff and specifies the denominator polynomial for the normalized filter.
The input values of numout and denout have no effect. The output value of numout is set to the column vector representing the numerator polynomial
for the continuous lowpass filter. The output value of denout is set to the column vector representing the denominator polynomial for the continuous
lowpass filter. The output values of numout and denout have the same type as cutoff.
The response of a continuous filter is
2
|num[s]|
|------|
|den[s]|
where num[s] is the numerator polynomial and den[s] is the denominator polynomial corresponding to the filter. The response of a normalized filter
is near 1 for s in the interval
__
[0, \/-1]
and near 0 for the rest of the positive imaginary axis. The response of the continuous lowpass filter is near 1 for s in the interval
__
[0, \/-1 cutoff]
and near 0 for the rest of the positive imaginary axis.
14.15.b: Example
numin = 1.
denin = {1., sqrt(2.), 1.}
numout = novalue
denout = novalue
cutoff = 2.
fn2clp(cutoff, numin, denin, numout, denout)
xmin = 1e-1
xmax = 1e+1
ymin = 1e-4
ymax = 1e+2
fcplot(xmin, xmax, ymin, ymax, cutoff, numout, denout)
returns the following plot:
14.16: Converting From A Continuous To Digital Filter
Syntax fc2dig(dt, numin, denin, numout, denout)
See Also fdplot: 10.4.10 , fn2clp: 14.15 , fn2cbp: 14.14 , fn2dlp: 14.18
14.16.a: Description
Converts a continuous filter to a digital filter, where dt is a real or double-precision scalar specifying the time between samples, numin is a column
vector (with the same type as dt) specifying the numerator polynomial: 26.ac of the continuous filter, denin is a column vector (with the same type as
dt) specifying the denominator polynomial for the continuous filter. The input values numout and denout have no effect. The output value of numout is
the column vector that represents the numerator polynomial for the digital filter. The output value of denout is the column vector that represents the
denominator polynomial for the digital filter. The output values of numout and denout have the same type as dt.
The transfer function for the continuous filter is numin[s] / denin[s]. The transfer function for the digital filter is
numout[z]
--------denout[z]
=
numin[(2 / dt) (z - 1) / (z + 1)]
--------------------------------denin[(2 / dt) (z - 1) / (z + 1)]
14.16.b: Example
The following program converts a normalized 2 pole Butterworth filter to a digital filter where the time between samples is 1. The cutoff frequency for
the continuous filter is transformed to the corresponding digital cutoff frequency and included in the plot.
clear
#
numcon = 1.
dencon = {1., sqrt(2.), 1.}
dt
= 1.
numdig = novalue
dendig = novalue
fc2dig(dt, numcon, dencon, numdig, dendig)
#
cutoff = 1.
cutoff = (2. / dt) * atan(cutoff * dt / 2)
#
ymin = 1e-4
ymax = 10
fdplot(dt, ymin, ymax, cutoff, numdig, dendig)
14.17: Converting From A Normalized To Digital Bandpass Filter
Syntax fn2dbp(cutoff, dt, numin, denin, numout, denout)
14.17.a: Description
Converts a normalized filter to a digital bandpass filter. The real or double-precision row vector cutoff has two elements and specifies the cutoff
frequencies for the bandpass filter. The scalar dt specifies the time between samples and has the same type as cutoff. The column vector numin has the
same type as cutoff and specifies the numerator polynomial: 26.ac for the normalized filter. The column vector denin has the same type as cutoff and
specifies the denominator polynomial for the normalized filter.
The input values of numout and denout have no effect. The output value numout is set to the column vector representing the numerator polynomial for
the digital bandpass filter. The output value denout is set to the column vector representing the denominator polynomial for the digital bandpass filter.
The output values of numout and denout have the same type as cutoff.
The response of the normalized filter is
2
|numin[s]|
|--------|
|denin[s]|
and it is near 1 for s in the interval
__
[0, \/-1]
and near 0 for the rest of the positive imaginary axis. The response of the digital bandpass filter is
|
__
|2
| numout[ exp( \/-1 dt w ) ] |
------------------------------|
__
|2
| denout[ exp( \/-1 dt w ) ] |
and it is near 1 for w in the interval [cutoff(1), cutoff(2)] and near 0 for other w in the interval [0, pi / dt].
14.17.b: Example
numin
denin
cutoff
dt
=
=
=
=
1.
{1., sqrt(2.), 1.}
[2., 4.]
.2
numout = novalue
denout = novalue
fn2dbp(cutoff, dt, numin, denin, numout, denout)
ymin = 1e-5
ymax = 1e+1
fdplot(dt, ymin, ymax, cutoff, numout, denout)
returns the following plot:
14.18: Converting From A Normalized To Digital LowPass Filter
Syntax fn2dlp(cutoff, dt, numin, denin, numout, denout)
14.18.a: Description
Converts a normalized filter to a digital lowpass filter. The real or double-precision scalar cutoff specifies the cutoff frequency for the lowpass filter.
The scalar dt specifies the time between samples and has the same type as cutoff. The column vector numin has the same type as cutoff and specifies
the numerator polynomial: 26.ac for the normalized filter. The column vector denin has the same type as cutoff and specifies the denominator
polynomial for the normalized filter.
The input values of numout and denout have no effect. The output value numout is set to the column vector representing the numerator polynomial for
the digital lowpass filter. The output value denout is set to the column vector representing the denominator polynomial for the digital lowpass filter.
The output values of numout and denout have the same type as cutoff.
The response of the normalized filter is
2
|numin[s]|
|--------|
|denin[s]|
and it is near 1 for s in the interval
__
[0, \/-1]
and near 0 for the rest of the positive imaginary axis. The response of the digital lowpass filter is
|
__
|2
| numout[ exp( \/-1 dt w ) ] |
------------------------------|
__
|2
| denout[ exp( \/-1 dt w ) ] |
and it is near 1 for w in the interval [0, cutoff(2)] and near 0 for other w in the interval [0, pi / dt].
14.18.b: Example
numin
= 1.
denin
= {1., sqrt(2.), 1.}
cutoff = 2.
dt
= .2
numout = novalue
denout = novalue
fn2dlp(cutoff, dt, numin, denin, numout, denout)
ymin = 1e-5
ymax = 1e+1
fdplot(dt, ymin, ymax, cutoff, numout, denout)
returns the following plot:
15: Statistics and Statistical Distributions
15.a: Basic Statistics
colrange: 15.13 Computing The Range of Data for Each Column
colmax: 15.42 Determining The Maximum Element In Each Column
rowmax: 15.43 Determining The Maximum Element In Each Row
colsum: 15.44 Computing The Sum Of Each Column
rowsum: 15.45 Computing The Sum Of Each Row
sum: 15.55
Sum of Elements of a Matrix
cumsum: 15.56 Running Cumulative Sum of Elements of a Matrix
prod: 15.57
Product of Elements of a Matrix
cumprod: 15.58 Running Cumulative Product of Elements of a Matrix
15.b: Descriptive Statistics
colmean: 15.40 Computing The Mean Of Each Column
colmedian: 15.49 Computing The Median of Each Column
median: 15.48 Computing The Median
colstd: 15.41
Computing the Standard Deviation of Each Column
colvar: 15.51
Computing the Variance of Each Column
colmode: 15.14 Computing The Mode of Each Column
colcor: 15.38
Correlation Coefficients Between Columns Of A Matrix
colcov: 15.39
Covariance Between Columns Of A Matrix
colmad: 15.11 Computing The Mean Absolute Deviation Of Each Column
colmead: 15.50 Computing The Median Absolute Deviation of Each Column
colmse: 15.12
Computing The Mean Squared Deviation Of Each Column
colnorm: 15.46 Computing The Norm Of Each Column
rownorm: 15.47 Computing The Euclidean Norm Of Each Row Of A Matrix
prctile: 15.1
Percentiles of Each Column
kurtosis: 15.15 Computing The Kurtosis of Each Column
skewness: 15.16 Computing The Skewness of Each Column
corr: 15.52
Column-wise Correlation Of Matrices Using FFT
conv: 15.53
Column-wise Convolution Of Matrices Using FFT
conv2: 15.54
Two Dimensional Convolution Of Matrices Using FFT
15.c: Statistical Distributions
rand: 15.8
Generating Uniformly Distributed Pseudo Random Numbers
seed: 15.10
Seeding Pseudo Random Number Generation
ranseed: 15.18
Using Time To Seed Random Number Generation
snormal: 15.9
Generating Normally Distributed Pseudo Random Numbers
unirnd: 15.20
Generating Random Numbers with Uniform Distribution
normrnd: 15.21 Generating Random Numbers with Normal Distribution
exprnd: 15.22
Generating Random Numbers with Exponential Distribution
cauchyrnd: 15.24 Generating Random Numbers with Cauchy Distribution
gumbelrnd: 15.25 Generating Random Numbers with Gumbel Distribution
laplacernd: 15.26 Generating Random Numbers with Laplace Distribution
lognrnd: 15.27 Generating Random Numbers with Log Normal Distribution
wblrnd: 15.28
Generating Random Numbers with Weibull Distribution
gamrnd: 15.23
Generating Random Numbers with Gamma Distribution
binornd: 15.29 Generating Random Numbers with Binomial Distribution
poissrnd: 15.30 Generating Random Numbers with Poisson Distribution
ftail: 15.2
Compute Tail Probabilities For An F-Statistic
ttail: 15.4
Tail Probability Of A T-Statistic
ittail: 15.5
Inverse Of The Cumulative Distribution For T-Statistic
unifm0v1: 15.19 Simulating a Mean Zero Variance One Uniform Random Variable
randperm: 15.17 Generating a Random Permutation
15.d: Probability Density Functions
normpdf: 15.33 Normal Probability Density Function
exppdf: 15.31 Exponential Probability Density Function
unifpdf: 15.34 Uniform Probability Density Function
wblpdf: 15.36 Weibull Probability Density Function
tpdf: 15.3
The Probability Density For A T-statistic
15.e: Cumulative Distribution Functions
cnormal: 15.6 The Cumulative Normal Distribution Function
expcdf: 15.32 Exponential Cumulative Distribution Function
unifcdf: 15.35 Uniform Cumulative Distribution Function
wblcdf: 15.37 Weibull Cumulative Density Function
inormal: 15.7 Inverse Of The Cumulative Normal Distribution Function
15.1: Percentiles of Each Column
Syntax prctile( X, p)
See Also colrange: 15.13 , colmedian: 15.49 , colmean: 15.40 , sort: 9.20
15.1.a: Description
Returns percentiles of the values in X. The value returned is a real or double-precision row vector with the same column dimension as X. The value p is
a numeric scalar that specifies the percent value to calculate.
15.1.b: Example
X = {1., 2, 3, 4, 5}
X = X*X'
print "X == ", X
print "25th percentile == ", prctile(X, 25.0)
returns
X == {
[ 1 , 2 , 3 , 4 , 5 ]
[ 2 , 4 , 6 , 8 , 10 ]
[ 3 , 6 , 9 , 12 , 15 ]
[ 4 , 8 , 12 , 16 , 20 ]
[ 5 , 10 , 15 , 20 , 25 ]
}
25th percentile == [ 2 , 4 , 6 , 8 , 10 ]
Continue the example by entering
prctile(X, 75)
returns
[ 4 , 8 , 12 , 16 , 20 ]
15.2: Compute Tail Probabilities For An F-Statistic
Syntax ftail( f, dfn, dfd)
15.2.a: Description
Returns the element-by-element: 26.n tail probability for an F-statistic, where f is a real or double-precision matrix with all its elements greater than 0,
dfn is an integer matrix specifying the number of degrees of freedom in the numerator, and dfd is an integer matrix specifying the number of degrees of
freedom in the denominator.
The tail probability for the F-statistic is
+infinity
/
| p(x, dfn, dfd) dx
/
f
where p(x, n, d) is the probability
density function for an F-distribution with n degrees of freedom in the numerator and d degrees of freedom in the
denominator.
15.2.b: Example
f
= .1 : .1 : 10.
dfn
= 5
dfd
= 5
tail = ftail(f, dfn, dfd)
gtitle("Tail of F-statistic")
gplot(f, tail)
returns the following plot:
15.3: The Probability Density For A T-statistic
Syntax tpdf(t, free)
15.3.a: Description
Computes the element-by-element: 26.n probability density function for a T-statistic at the values specified by t, where t is a real or double-precision
matrix. The matrix free has the same type as t and specifies the number of degrees of freedom for the corresponding T-statistic. All of the elements of
free must be greater than 0. The return value is equal to
-(free + 1) / 2
[
2
]
[1 + t / free]
---------------------------------beta(1/2, free/2) \/ free
where beta: 16.4 is the beta function.
15.3.b: Example
If you enter
t
= -2. : .1 : +2.
free = 10.
gplot(t, tpdf(t, free))
O-Matrix will respond with the plot
15.4: Tail Probability Of A T-Statistic
Syntax ttail( t, df)
15.4.a: Description
Returns the element-by-element: 26.n tail probability for a T-statistic, where t is a real or double-precision matrix specifying values for the T-statistic
and df is an integer matrix specifying the number of degrees of freedom. All of the elements of t must be positive.
The return value is
+infinity
/
| tpdf(x, df) dx
/
t
where tpdf: 15.3 is the probability density function for the T-distribution. The return value has the same type and dimension as t.
15.4.b: Example
N
= 100
t
= 6. * seq(N) / real(N)
df = 5
gtitle("|t|-statistic Tail Probabilities")
gplot(t, ttail(t, df))
returns
15.5: Inverse Of The Cumulative Distribution For T-Statistic
Syntax ittail(p, free)
15.5.a: Description
Computes the element-by-element: 26.n inverse of the cumulative distribution for the T-statistic, where p is a real or double-precision matrix
specifying the value of the tail probability. Each of the elements of p must be greater than 0 and less than 1. The matrix free specifies the number of
degrees of freedom for the T-statistic and may be integer, real, or double-precision. If t is the return value,
+infinity
/
p = | tpdf(x, free) dx
/
t
where tpdf: 15.3 is the probability density function for the T-statistic.
15.5.b: Example
If you enter
p = [.1, .5, .9]
free = 3
ittail(p, free)
O-Matrix will respond
[ 1.63768 , 0 , -1.63768 ]
15.6: The Cumulative Normal Distribution Function
Syntax cnormal( x)
15.6.a: Description
Returns the element-by-element: 26.n cumulative normal distribution
x
1
/
---------- |
sqrt(2 pi) /
2
-t
/ 2
e
dt
-inf
where x is a real or double-precision matrix.
15.6.b: Example
x = [-5. : .1 : +5.]
gplot(x, cnormal(x))
gtitle("Cumulative Normal Distribution")
returns the following plot:
15.7: Inverse Of The Cumulative Normal Distribution Function
Syntax inormal( p)
15.7.a: Description
Returns the element-by-element: 26.n inverse of the cumulative normal distribution function cnormal: 15.6 . The matrix p is real or double-precision
and its elements are between 0 and 1 exclusive.
15.7.b: Example
x = .01: .01 : .99
gtitle("inormal")
gplot(x, inormal(x))
returns the following plot:
15.8: Generating Uniformly Distributed Pseudo Random Numbers
Syntax rand(rows)
rand(rows, cols)
15.8.a: Description
Returns a real matrix containing random elements that are uniformly distributed between 0 and 1, where rows is the number of rows and cols is the
number of columns. The arguments rows and cols are integer, real, double-precision or complex scalars. If an argument is complex, only its real part:
26.ad is used. If the argument cols is not present, a square matrix: 26.ak is returned.
15.8.b: Example
clear
rand(3, 1)
results in
{
4.65661e-010
0.527357
0.384887
}
The rand function returns values from a pseudo-random sequence. It
a clear. If you continue the previous example by entering
clear
rand(3, 1)
always starts at the same point at the beginning of an O-Matrix session and after
O-Matrix will respond
{
4.65661e-010
0.527357
0.384887
}
which are the same as the numbers output above. If, however, you continue the previous example (without clearing) by entering
rand(3, 1)
O-Matrix will respond
{
0.134948
0.223919
0.643237
}
which is a different set of numbers.
15.8.c: Reference
The arguments must be scalars. If they are logical, real, double-precision or complex, the corresponding integer: 6.4.2 values are used.
15.9: Generating Normally Distributed Pseudo Random Numbers
Syntax snormal( rows)
snormal( rows, cols)
See Also randn: 15.9.c , rand: 15.8 , seed: 15.10 , ranseed: 15.18 , cnormal: 15.6 , inormal: 15.7
15.9.a: Description
Returns a real matrix in which the elements simulate independent realizations of the normally distributed random variable with mean 0 and variance 1,
where rows and cols are the number of rows and columns, respectively, in the result. If the argument cols is not present, a square matrix: 26.ak is
returned.
The seed: 15.10 and ranseed: 15.18 functions can change the initial point of the simulated random sequence.
15.9.b: Example
clear
noise = snormal(100, 1)
gstyle("cross", 1, 20)
gplot(noise)
returns the following plot:
15.9.c: Mlmode
In Mlmode: 25 , this function is called randn instead of snormal. If in Mlmode you enter
clear
noise = randn(100, 1);
x
= 1:100;
plot(x, noise, 'x')
O-Matrix will draw the same plot as above except with a larger symbol: 10.1.6 style.
15.9.d: Reference
The arguments must be scalars. If they are logical, real, double-precision or complex, the corresponding integer: 6.4.2 values are used.
15.10: Seeding Pseudo Random Number Generation
Syntax seed(s1)
See Also ranseed: 15.18 , unirnd: 15.20 , normrnd: 15.21 , randperm: 15.17
15.10.a: Description
Sets the point at which the pseudo-random sequence starts, where the seed value s1 is an integer scalars between 1 and 168.
15.10.b: Example
seed(12)
rand(3, 1)
returns
{
5.58794e-009
0.32828
0.618638
}
15.10.c: Mlmode
In Mlmode: 25 , the arguments can be are logical, real, double-precision or complex. In this case, the corresponding integer: 6.4.2 values are used.
15.11: Computing The Mean Absolute Deviation Of Each Column
15.11.a: Description
Returns a row vector containing the mean absolute deviation of each column of x, where x is a real or double-precision matrix. The return value has the
same type and column dimension as x.
15.11.b: Example
x = [{0., 2., 4.}, {0., -1., 1.}]
returns
[ 1.3333 , 0.666667 ]
15.12: Computing The Mean Squared Deviation Of Each Column
Syntax colmse(x)
See Also colrange: 15.13 , colsum: 15.44 , colstd: 15.41 , colmean: 15.40 , colmedian: 15.49 , colmad: 15.11
15.12.a: Description
Returns a row vector containing the mean squared deviation of each column of x, where x is a real or double-precision matrix. The return value has the
same type and column dimension as x.
15.12.b: Example
x = [{0., 2., 4.}, {0., -1., 1.}]
colmse(x)
returns
[ 2.66667 , 0.666667 ]
15.13: Computing The Range of Data for Each Column
Syntax [min, max]
= colrange(x)
[min, max, minIdx, maxIdx] = colrange( x)
See Also colmax: 15.42 , maxs: 6.1.5 , mins: 6.1.6 , colsum: 15.44 , colstd: 15.41 , colmean: 15.40 , colmedian: 15.49 , colmad: 15.11
15.13.a: Description
Returns a row vector min containing the minimum values in each column of x, and a row vector max containing the maximum values in each column
of x. The argument x is an integer, real or double-precision matrix. The returned values min and max have the same type and column dimension as x.
If present, the returned values minIdx and maxIdx are integer row vectors that contain the column index values of the returned min and max vectors.
The vectors minIdx and maxIdx have the same column dimension as x.
15.13.b: Example
x = [ {1, 2, 3}, {5, 3, 1}, {-2, -1, -3} ]
[vMin, vMax ] = colrange(x)
print vMin
print vMax
returns
[ 1 , 1 , -3 ]
[ 3 , 5 , -1 ]
If you continue the example by entering
[vMin, vMax, minIdx, maxIdx ] = colrange(x)
print minIdx
print maxIdx
O-Matrix will respond
[ 1 , 3 , 3 ]
[ 3 , 1 , 2 ]
15.14: Computing The Mode of Each Column
Syntax colmode( x)
See Also colrange: 15.13 , colmedian: 15.49 , colmean: 15.40 , sort: 9.20
15.14.a: Description
Returns a row vector containing the mode, (the most frequently occurring value), of each column of x, where x is an integer, real, or double-precision
matrix. The return value has the same type and column dimension as x.
15.14.b: Example
X = {[3., 3, 1, 4], ...
[0, 0, 1, 1], ...
[0, 1, 2, 4]}
colmode(X)
returns
[ 0 , 0 , 1 , 1 ]
15.15: Computing The Kurtosis of Each Column
Syntax kurtosis(X)
See Also skewness: 15.16 , colrange: 15.13 , colmedian: 15.49 , colmean: 15.40 , sort: 9.20
15.15.a: Description
Returns a row vector containing the kurtosis of each column of X, where X is a real, or double-precision matrix. The return value has the same type and
column dimension as x.
The kurtosis of the normal distribution is 3. Distributions that are more outlier prone than the normal distribution have a kurtosis value greater than 3,
distributions that are less outlier prone have a kurtosis value less than 3
15.15.b: Example
X = normrnd(0., 1., 10000, 3)
kurtosis(X)
returns
[ 2.92882 , 3.06149 , 3.02654 ]
15.16: Computing The Skewness of Each Column
Syntax skewness(X)
See Also kurtosis: 15.15 , colrange: 15.13 , colmedian: 15.49 , colmean: 15.40 , sort: 9.20
15.16.a: Description
Returns a row vector containing the skewness of each column of X, where X is a real, or double-precision matrix. The return value has the same type
and column dimension as x.
If skewness is negative, the data are spread out more to the left of the mean than to the right. If skewness is positive, the data are spread out more to the
right.
15.16.b: Example
X = normrnd(0., 1., 10000, 3)
skewness(X)
returns
[ 0.0146647 , -0.00473214 , 0.00667061 ]
15.17: Generating a Random Permutation
Syntax randperm(n)
15.17.a: Description
Generates a random ordering of the integers between 1 and the real part: 26.ad of n, where n is an integer, real, complex scalar with real part equal to
an integer value. The return value is an integer row vector of length equal to the real part of n.
15.17.b: Example
If you enter
clear
randperm(5)
[ 4 , 1 , 3 , 5 , 2 ]
Note that the return value depends on the current seeding: 15.10 of the O-Matrix random number generator. If you continue by enter
randperm(5)
[ 2 , 1 , 4 , 3 , 5 ]
15.18: Using Time To Seed Random Number Generation
Syntax ranseed
15.18.a: Description
Seeds the O-Matrix random number generator, using the system clock. The seed depends on the day of the month, hour, minute, and second of the day,
so that it will be different each time the function is called.
15.18.b: Example
clear
rand(1, 1)
returns the value
0.386184
where as
clear
ranseed
rand(1, 1)
returns a value that is different each time
15.19: Simulating a Mean Zero Variance One Uniform Random Variable
Syntax unifm0v1(nr, nc)
15.19.a: Description
Returns a real matrix containing simulated samples of a uniform random variable that has mean zero and variance one. The integer scalars nr and nc
specify the number of rows and columns in the return value.
15.19.b: Derivation
Suppose that f(x) is the density function defined by
/ 1 / (2 b) if -b < x < +b
f(x) = |
\ 0
otherwise
where b is equal to the square root of 3. It follows
that the corresponding random variable is uniformly distributed, has mean zero, and variance equal
to
+b
/
2
| f(x) x dx
/
-b
3
=
1
--2 b
x
3
2
|+b
|
|-b
=
b
3
=
1
15.19.c: Example
If you enter
unifm0v1(1, 4)
O-Matrix will print four number with values between plus and minus the square root of 3.
15.20: Generating Random Numbers with Uniform Distribution
Syntax unirnd(min, max, rows, cols)
See Also normrnd: 15.21 , exprnd: 15.22 , seed: 15.10 , snormal: 15.9 , randperm: 15.17
15.20.a: Description
Returns a real or double matrix containing random elements that are uniformly distributed between min and max, where rows is the number of rows
and cols is the number of columns. The arguments rows and cols are integer scalars. If the arguments min and max are double-precision scalars then
the matrix returned is double, otherwise the return value is real.
15.21: Generating Random Numbers with Normal Distribution
Syntax normrnd( alpha, sigma, rows, cols)
See Also seed: 15.10 , snormal: 15.9 , randperm: 15.17 , unirnd: 15.20 , exprnd: 15.22
15.21.a: Description
Returns a real or double matrix containing random elements that are normally (Gaussian) distributed with mean value alpha and standard deviation
sigma. The value rows is the number of rows and cols is the number of columns in the result. The value sigma must be greater than 0. If the arguments
alpha and sigma are double-precision scalars then the matrix returned is double, otherwise the return value is real.
15.22: Generating Random Numbers with Exponential Distribution
Syntax exprnd(alpha, rows, cols)
See Also seed: 15.10 , snormal: 15.9 , randperm: 15.17 , unirnd: 15.20 , normrnd: 15.21
15.22.a: Description
Returns a real or double matrix containing random elements that are exponentially distributed with displacement alpha, where rows is the number of
rows and cols is the number of columns in the result. If the argument alpha is a double then the matrix returned is double, otherwise the return value is
real.
15.23: Generating Random Numbers with Gamma Distribution
Syntax gamrnd(alpha, displacement, rows, cols)
15.23.a: Description
Returns a real or double matrix containing random elements that are gamma distributed with shape parameter alpha, and displacement displacement
where rows is the number of rows and cols is the number of columns in the result. The value of alpha must be greater than 0. If the argument alpha is
a double then the matrix returned is double, otherwise the return value is real.
15.24: Generating Random Numbers with Cauchy Distribution
Syntax cauchyrnd( alpha, rows, cols)
See Also seed: 15.10 , snormal: 15.9 , randperm: 15.17 , unirnd: 15.20 , normrnd: 15.21
15.24.a: Description
Returns a real or double matrix containing random elements that are Cauchy distributed with displacement alpha, where rows is the number of rows
and cols is the number of columns in the result. If the argument alpha is a double then the matrix returned is double, otherwise the return value is real.
15.25: Generating Random Numbers with Gumbel Distribution
Syntax gumbelrnd( alpha, rows, cols)
See Also seed: 15.10 , snormal: 15.9 , randperm: 15.17 , unirnd: 15.20 , normrnd: 15.21
15.25.a: Description
Returns a real or double matrix containing random elements that are Gumbel distributed with displacement alpha, where rows is the number of rows
and cols is the number of columns in the result. If the argument alpha is a double then the matrix returned is double, otherwise the return value is real.
15.26: Generating Random Numbers with Laplace Distribution
Syntax laplacernd(alpha, rows, cols)
See Also seed: 15.10 , snormal: 15.9 , randperm: 15.17 , unirnd: 15.20 , normrnd: 15.21
15.26.a: Description
Returns a real or double matrix containing random elements that are Laplace distributed with mean value (or average) alpha, where rows is the number
of rows and cols is the number of columns in the result. If the argument alpha is a double then the matrix returned is double, otherwise the return value
is real.
15.27: Generating Random Numbers with Log Normal Distribution
Syntax lognrnd( alpha, sigma, displacement, rows, cols)
See Also normrnd: 15.21 , exprnd: 15.22 , seed: 15.10 , snormal: 15.9 , randperm: 15.17
15.27.a: Description
Returns a real or double matrix containing random elements that are lognormally distributed with average distribution of alpha, and standard deviation
sigma with displacement displacement, where rows is the number of rows and cols is the number of columns in the result. The value of sigma must be
greater than 0. If the argument alpha is a double then the matrix returned is double, otherwise the return value is real.
15.28: Generating Random Numbers with Weibull Distribution
Syntax wblrnd(alpha, displacement, rows, cols)
15.28.a: Description
Returns a real or double matrix containing random elements that are Weibull distributed with displacement of displacement, and shape alpha where
rows is the number of rows and cols is the number of columns in the result. The argument alpha must be greater than 0. If the argument alpha is a
double then the matrix returned is double, otherwise the return value is real.
15.29: Generating Random Numbers with Binomial Distribution
Syntax binornd( Ntrials, successProbability, rows, cols)
See Also unirnd: 15.20 , normrnd: 15.21 , exprnd: 15.22 , poissrnd: 15.30
15.29.a: Description
Returns an integer matrix containing random elements that are binomially distributed with number of independent Bernoulli trials Ntrials, and with
probability successProbability of a single trial with success, where successProbability is between 0 and 1. The value rows is the number of rows and
cols is the number of columns in the result. A binomially distributed variate represents the number of successes in Ntrials independent Bernoulli trials
with probability of a single trial success successProbability.
15.30: Generating Random Numbers with Poisson Distribution
Syntax poissrnd(lambda, rows, cols)
15.30.a: Description
Returns an integer matrix containing random elements that are Poisson distributed with distribution parameter lambda, where lambda is greater than 0.
The value rows is the number of rows and cols is the number of columns in the result.
15.31: Exponential Probability Density Function
Syntax exppdf(X, mu)
See Also normrnd: 15.21 , exprnd: 15.22 , seed: 15.10 , snormal: 15.9 , randperm: 15.17
15.31.a: Description
Computes the exponential PDF at each of the values in X. The value returned has the same type, column dimension and row dimension as X. The value
mu must be a positive real or double scalar.
15.31.b: Example
exppdf([4., 5., 6], 1.0)
results in
[ 0.0183156 , 0.00673795 , 0.00247875 ]
15.32: Exponential Cumulative Distribution Function
Syntax expcdf(X, mu)
15.32.a: Description
Computes the exponential CDF at each of the values in X. The value returned has the same type, column dimension and row dimension as X. The
value mu must be a positive real or double scalar.
15.32.b: Example
expcdf([4., 5., 6], 1.0)
results in
[ 0.981684 , 0.993262 , 0.997521 ]
15.33: Normal Probability Density Function
Syntax normpdf( X, mu, sigma)
15.33.a: Description
Computes the normal PDF at each of the values in X. The value returned has the same type, column dimension and row dimension as X. The value mu
must be a real or double scalar. The value sigma must be a positive real or double scalar.
15.34: Uniform Probability Density Function
Syntax unifpdf( X, a, b)
15.34.a: Description
Computes the uniform PDF at each of the values in X. The value returned has the same type, column dimension and row dimension as X. The values a
and b must be a real or double scalars. The value a must be less than b.
15.35: Uniform Cumulative Distribution Function
Syntax unifcdf( X, a, b)
15.35.a: Description
Computes the uniform CDF at each of the values in X. The value returned has the same type, column dimension and row dimension as X. The value a
and b are the minimum and maximum respectively. The values a and b must be a real or double scalars. The value a must be less than b.
15.35.b: Example
X = [1., 2., 3.]
unifcdf(X, 0, 1)
results in
[ 1 , 2 , 3 ]
15.36: Weibull Probability Density Function
Syntax wblpdf(X, shape, scale, location)
See Also rand: 15.8 , cnormal: 15.6 , normpdf: 15.33 , wblcdf: 15.37
15.36.a: Description
Computes the normal PDF at each of the values in X. The value returned has the same type, column dimension and row dimension as X.
15.36.b: Example
If at the O-Matrix prompt you enter,
shape = { 2, 2, 3, 4 }
scale = { 0.5, 1.0, 1.5, 3.0 }
location = 0
x = 0.001:0.001:10
N = rowdim(x)
y1 = zeros(N,4)
y2 = zeros(N,4)
for i = 1 to 4 begin
shapei = shape(i)
scalei = scale(i)
y1(:,i) = wblpdf(x,shapei,scalei,location)
end
gyaxis("linear",0,2,20)
gxaxis("linear",0,5,10)
gcolor({"red","green","blue","purple"})
gplot(x,y1)
O-Matrix will generate the following plot
15.37: Weibull Cumulative Density Function
Syntax wblcdf(X, shape, scale, location)
See Also rand: 15.8 , cnormal: 15.6 , normpdf: 15.33 , wblpdf: 15.36
15.37.a: Description
Computes the Weibull CDF at each of the values in X. The value returned has the same type, column dimension and row dimension as X.
15.37.b: Example
If at the O-Matrix prompt you enter,
shape = { 2, 2, 3, 4 }
scale = { 0.5, 1.0, 1.5, 3.0 }
location = 0
x = 0.001:0.001:10
N = rowdim(x)
y1 = zeros(N,4)
y2 = zeros(N,4)
for i = 1 to 4 begin
shapei = shape(i)
scalei = scale(i)
y2(:,i) = wblcdf(x,shapei,scalei,location)
end
gyaxis("linear",0,1,10)
gxaxis("linear",0,5,10)
gcolor({"red","green","blue","purple"})
gplot(x,y2)
O-Matrix will generate the following plot
15.38: Correlation Coefficients Between Columns Of A Matrix
Syntax colcor(x)
Syntax colcor(x, y)
See Also corrcoef: 15.38.d , colcov: 15.39 , colstd: 15.41 , colmean: 15.40 , colmad: 15.11 , colmse: 15.12
15.38.a: Description
The call colcor(x) returns a matrix containing the correlation of the columns of x, where x is a real or double-precision matrix. The return value has
the same type as x. Each column of x corresponds to a random variable, and each row of x corresponds to a realization. The row and column
dimensions of the return value are equal to the column dimension of x. If C is the colcov(x): 15.39 , the (i, j)th element of the return value is
C(i,j) / sqrt(C(i,i) C(j,j)).
15.38.b: Two Arguments
If both x and y are vectors of equal length, colcor(x, y) returns that correlation between the two vectors. To be specific this is the return value is
equal to the return value of colcor(X) where the first column of X contains the elements of the vector x and the second column of X contains the
elements of y.
15.38.c: Example
x = [{0., 2., 4.}, {0., -1., 1.}]
colcor(x)
returns
{
[ 1 , 0.5 ]
[ 0.5 , 1 ]
}
15.38.d: Mlmode
In Mlmode: 25 this function is called corrcoef instead of colcor. If in Mlmode you enter,
x = [ [0 ; 2 ; 4 ], [0 ; -1 ; 1] ];
corrcoef(x)
{
[ 1 , 0.5 ]
[ 0.5 , 1 ]
}
15.39: Covariance Between Columns Of A Matrix
Syntax colcov(x)
Syntax colcov(x, y)
See Also cov: 15.39.d , colcor: 15.38 , colstd: 15.41 , colmean: 15.40 , colmad: 15.11 , colmse: 15.12
15.39.a: One Argument
The call colcov(x) returns a matrix containing the covariance of the columns of x, where x is a real or double-precision matrix. The return value has
the same type as x. Each column of x corresponds to a random variable, and each row of x corresponds to a realization. The row and column
dimensions of the return value are equal to the column dimension of x. If C is the covariance of x,
C
=
i,j
N
1
---_
_
----- >
(x
- x ) (x
- x )
N - 1 ---k,i
i
k,j
j
k = 1
where N is the number of rows in x and
_
1
N
----
x
=
j
--- >
x
N ---k,j
k = 1
15.39.b: Two Arguments
If both x and y are vectors of equal length, colcov(x, y) returns that covariance between the two vectors. To be specific this is the return value is
equal to the return value of colcov(X) where the first column of X contains the elements of the vector x and the second column of X contains the
elements of y.
15.39.c: Example
x = [{0., 2., 4.}, {0., -1., 1.}]
colcov(x)
returns
{
[ 4 , 1 ]
[ 1 , 1 ]
}
15.39.d: Mlmode
In Mlmode: 25 this function is called cov instead of colcov. If in Mlmode you enter,
x = [ [0 ; 2 ; 4 ], [0 ; -1 ; 1] ];
cov(x)
{
[ 4 , 1 ]
[ 1 , 1 ]
}
15.40: Computing The Mean Of Each Column
Syntax colmean( x)
See Also colsum: 15.44 , colstd: 15.41 , colmedian: 15.49 , colmode: 15.14 , colmad: 15.11 , colmse: 15.12
15.40.a: Description
Returns a row vector containing the average of each column of x, where x is an integer, real, double-precision, or complex matrix. The return value has
the same type and column dimension as x. If x is an integer matrix, the fractional part of the return value is dropped.
15.40.b: Example
x = [{0., 2., 4.}, {0., -1., 1.}]
colmean(x)
returns
[ 2 , 0 ]
15.41: Computing the Standard Deviation of Each Column
Syntax colstd(x)
See Also colvar: 15.51 , colnorm: 15.46 , colmax: 15.42 , colmean: 15.40 , colmad: 15.11 , colmse: 15.12
15.41.a: Description
Returns the standard deviation of each column of x where x is a real, double-precision, or complex matrix. The return value is a row vector with the
same number of columns as x. If x is complex, the return value is double-precision, otherwise the return value has the same type as x. The jth element
of the return value is
-------------------------------------_
2
_
2
/ | x
- x |
+ ... + | x
- x |
\
/
1,j
j
N,j
j
\ /
-----------------------------------\/
N - 1
where N is the number of rows in the matrix x and
N
_
1 ---x
= --- >
x
j
N ---k,j
k = 1
/
15.41.b: Example
If you enter
x = [{0., 2., 4.}, {0., -1., 1.}]
colstd(x)
O-Matrix will respond
[ 2 , 1 ]
15.42: Determining The Maximum Element In Each Column
Syntax colmax(x)
colmax(x, index)
See Also colrange: 15.13 , maxs: 6.1.5 , mins: 6.1.6 , rowmax: 15.43 , colnorm: 15.46 , colmean: 15.40
15.42.a: Description
Computes the maximum of each column of x, where x is an integer, real, or double-precision matrix with at least one row. The return value is a row
vector with the same type and number of columns as x. The j-th element of the return value is the maximum of the elements in the j-th column of x.
If index is present, its input value has no effect. Its output value is an integer row vector with the same number of columns as x. The j-th element of the
output value of index is the index of the row containing the maximum element of the j-th column of x.
15.42.b: Example
x = [ {1, 2, 3}, {5, 3, 1}, {-2, -1, -3} ]
colmax(x)
returns
[ 3 , 5 , -1 ]
15.43: Determining The Maximum Element In Each Row
Syntax rowmax(x)
rowmax(x, index)
See Also colrange: 15.13 , colmax: 15.42 , rownorm: 15.47 , rowsum: 15.45
15.43.a: Description
Computes the maximum of each row of x, where x is an integer, real, or double-precision matrix with at least one column. The return value is a column
vector with the same type and number of rows as x. The j-th element of the return value is the maximum of the elements in the j-th row of x.
If index is present, its input value has no effect. Its output value is an integer column vector with the same number of rows as x. The j-th element of the
output value of index is the index of the column containing the maximum element of the j-th row of x.
15.43.b: Example
x = [ {1, 2, 3}, {5, 3, 1}, {-2, -1, -3} ]
rowmax(x)
returns
{
5
3
3
}
15.44: Computing The Sum Of Each Column
Syntax colsum(x)
See Also sum: 15.55 , colrange: 15.13 , colmean: 15.40 , colstd: 15.41 , colmad: 15.11 , colmse: 15.12
15.44.a: Description
If x is an integer, real, double-precision, or complex matrix, returns a row vector with the same type and column dimension as x containing the sum of
each column. If x is a logical matrix, returns an integer row vector (with the same column dimension as x) containing the number of "true" entries in
each column.
15.44.b: Example
x = [{0., 2., 4.}, {0., -1., 1.}]
colsum(x)
returns
[ 6 , 0 ]
15.45: Computing The Sum Of Each Row
Syntax rowsum(x)
See Also sum: 15.55 , colrange: 15.13 , rownorm: 15.47 , colsum: 15.44
15.45.a: Description
If x is an integer, real, double-precision, or complex matrix, returns a column vector with the same type and row dimension as x containing the sum of
each row. If x is a logical matrix, returns an integer column vector (with the same row dimension as x) containing the number of "true" entries in each
row.
15.45.b: Example
x = {[0., 2., 4.], [0., -1., 1.]}
rowsum(x)
returns
{
6
0
}
15.46: Computing The Norm Of Each Column
Syntax colnorm( x)
15.46.a: Description
Returns the norm of each column of x where x is a real, double-precision, or complex matrix. The return value is a row vector with the same number of
columns as x. If x is complex, the return value is double-precision, otherwise the return value has the same type as x. The jth element of the return
value is
-------------------------------------2
2
2
\ / | x
| + | x
| + ... + | x
|
\/
1,j
2,j
n,j
where n is the number of rows in the matrix x.
/
15.46.b: Example
If you enter
x = [{1., 1.}, {3., 4.}]
colnorm(x)
O-Matrix will respond
[ 1.41421 , 5 ]
15.47: Computing The Euclidean Norm Of Each Row Of A Matrix
Syntax rownorm( x)
15.47.a: Description
Returns the Euclidean norm of each row of x where x is a real, double-precision, or complex matrix. The return value is a column vector with the same
number of rows as x. If x is complex, the return value is double-precision, otherwise the return value has the same type as x. The i-th element of the
return value is
---------------------------------2
2
2
/ |x
| + |x
| + . . . + |x
|
\/
i,1
i,2
i,m
where m is the number of columns in the matrix x.
/
15.47.b: Example
If you enter
x = {[1., 1.], [3., 4.]}
rownorm(x)
O-Matrix will respond
{
1.41421
5
}
15.48: Computing The Median
Syntax median(x)
See Also colmedian: 15.49 , colmean: 15.40 , sort: 9.20 , psort: 9.22
15.48.a: Description
If x is a vector, returns a scalar containing the median of the elements of x Otherwise, returns a row vector with the same column dimension as x and
containing the median of each of the columns of x. The argument x is an integer, real, or double-precision matrix. The return value is a doubleprecision vector.
The median of an even number of elements is the average of the two central values.
New programs should be converted to use the colmedian function. The median() function may be deprecated in future versions.
15.48.b: Example
If you enter
x = {2, 3, 1}
median(x)
O-Matrix returns
2
If you enter
x = [2, 4, 6, 8]
median(x)
O-Matrix returns
5
15.49: Computing The Median of Each Column
Syntax colmedian( x)
See Also colrange: 15.13 , median: 15.48 , colmean: 15.40 , colmode: 15.14 , sort: 9.20 , psort: 9.22
15.49.a: Description
Returns a row vector containing the median of each column of x, where x is an integer, real, or double-precision matrix. The return value has the same
type and column dimension as x.
If x has an even number of rows, the average of the two central values is returned. If x is also an integer, the fractional part of this average is dropped.
15.49.b: Example
x = {2, 3, 1}
colmedian(x)
returns
2
15.50: Computing The Median Absolute Deviation of Each Column
See Also colmedian: 15.49 , colmse: 15.12 , median: 15.48 , colmean: 15.40 , sort: 9.20 , psort: 9.22
15.50.a: Description
Returns a row vector containing the median absolute deviation of each column of x, where x is an integer, real, or double-precision matrix. The return
value has the same type and column dimension as x.
15.50.b: Example
x = {13., 11, 16, 5, 3, 18, 9, 8, 6, 27, 7}
X = [x , x*2 ]
returns
[ 4 , 8 ]
15.51: Computing the Variance of Each Column
Syntax colvar(x)
See Also colstd: 15.41 , colnorm: 15.46 , colmax: 15.42 , colmean: 15.40 , colmedian: 15.49 , colmad: 15.11 , colmse: 15.12
15.51.a: Description
Returns the variance of each column of x where x is a real or double-precision matrix. The return value is a row vector with the same number of
columns as x. The return value has the same type as x.
15.51.b: Example
If you enter
x = [{4., -2., 1.}, {9., 5., 7.}]
colvar(x)
O-Matrix will respond
[ 12.5 , 24.5 , 18 ]
15.52: Column-wise Correlation Of Matrices Using FFT
Syntax corr(g, h)
15.52.a: Description
Returns a matrix that is the column-wise correlation of g with h, where g and h are integer, real, double-precision, or complex matrices with the same
column dimension. If ng and nh are the number of rows in the matrices g and h, respectively, the (k,j)-th element of the return value is
ng
---->
----i = 1
g
H
i,j
where
H
i+k-ng,j
= <
i+k-ng,j
/ 0
0
\ h
if i+k-ng < 1
if i+k-ng > nh
otherwise
i+k-ng,j
The return value is a matrix with row dimension equal to ng + nh - 1 with the same type and column dimension as g. An FFT is used to compute the
correlation.
15.52.b: Example
g = {1, 1}
h = {1, 1}
corr(g, h)
returns
{
1
2
1
}
15.53: Column-wise Convolution Of Matrices Using FFT
Syntax conv(g, h)
See Also mlmode_conv: 18.15 , corr: 15.52 , polmul: 18.6 , filter: 14.3
15.53.a: Description
Returns a matrix that is the column-wise convolution of g with h, where g and h are integer, real, double-precision, or complex matrices with the same
column dimension. If ng and nh are the number of rows in the matrices g and h, respectively, the (k,j)-th element of the return value is
ng
---->
----i = 1
g
H
i,j
where
H
k-i+1,j
= <
k-i+1,j
/ 0
0
\ h
if k-i+1 < 1
if k-i+1 > nh
otherwise
k-i+1,j
The return value is a matrix with row dimension equal to ng + nh - 1 with the same type and column dimension as g. An FFT is used to compute the
convolution. The polmul: 18.6 function computes a similar value directly.
15.53.b: Example
g = {1., 1., 1., 1., 1.}
conv(g, g)'
returns
[ 1 , 2 , 3 , 4 , 5 , 4 , 3 , 2 , 1 ]
15.54: Two Dimensional Convolution Of Matrices Using FFT
Syntax f = conv2(g, h)
15.54.a: Description
Returns a matrix that is the two dimensional convolution of g with h, where g and h are integer, real, double-precision, or complex matrices. We use
the following notation to specify the return matrix f:
Notation Meaning
mf
number of rows in f
nf
number of columns in f
mg
number of rows in g
ng
number of columns in g
mh
number of rows in h
nh
number of columns in h
If 1 < i < mh and 1 < j < nh we define
H(i, j) = h
i,j
otherwise H(i, j) is zero. The return value f has the same type as g and is defined by
mf = mg + mh - 1
nf = ng + nh - 1
mg
--f
= >
m,n --i=1
ng
-->
--j=1
g
H(m-i+1, n-j+1)
i,j
An two dimensional fft: 14.1.8 is used to compute the convolution.
15.54.b: Example
g = { ...
[1., 1.], ...
[1., 1.] ...
}
conv2(g, g)
returns
{
[1 , 2 , 1], ...
[2 , 4 , 2], ...
[1 , 2 , 1] ...
}
15.55: Sum of Elements of a Matrix
Syntax s = sum(x)
s = sum(x, d)
See Also cumsum: 15.56 , prod: 15.57 , rowsum: 15.45 , colsum: 15.44 , colrange: 15.13
15.55.a: Description
Returns the sum of the elements of the matrix x where x is a logical, integer, real, double-precision or complex matrix. If x is logical, s is integer.
Otherwise s has the same type as x.
15.55.b: Vectors
If x is a vector, s is a scalar and
s = x
* x
1
* ... * x
2
n
where n is the number of elements in x. If you enter
x = [ 1, 2, 3 ]
sum(x)
O-Matrix will respond
6
If you enter
x = { 1, 2, 3 }
sum(x)
O-Matrix will respond
6
15.55.c: Matrices
If x is not a vector, s is a row vector with the same column dimension as x and
s
= x
* x
* ... * x
j
1,j
2,j
m,j
where m is the number of rows in the matrix x. If
x = { [ 1, 2, 3 ], [3, 4, 5] }
sum(x)
you enter
O-Matrix will respond
{
[ 4 , 6 , 8 ]
}
15.55.d: Dimension
If the argument d is present, it specifies which dimension the sum is taken with respect to. It must be an integer, real, or double-precision scalar equal
to 1 or 2. If you enter
x = { [ 1, 2, 3 ], [3, 4, 5] }
sum(x, 2)
O-Matrix will respond
{
6
12
}
15.56: Running Cumulative Sum of Elements of a Matrix
Syntax cumsum(x)
cumsum(x, d)
See Also sum: 15.55 , cumprod: 15.58 , colsum: 15.44 , rowsum: 15.45 , colrange: 15.13
15.56.a: Description
Returns the cumulative sum of the elements of the matrix x as a matrix with the same type and dimension as x where x is an integer, real, doubleprecision or complex matrix.
15.56.b: Vectors
If x is a vector, the i-th element of the return value is
x
+ x
1
+ ... + x
2
i
If you enter
x = [ 1, 2, 3 ]
cumsum(x)
O-Matrix will respond
[ 1 , 3 , 6 ]
If you enter
x = { 1, 2, 3 }
cumsum(x)
O-Matrix will respond
{
1
3
6
}
15.56.c: Matrices
If x is a matrix, the (i,j)-th element of the return value is
x
+ x
1,j
+ ... + x
2,j
i,j
If you enter
x = { [ 1, 2, 3 ], [3, 4, 5] }
cumsum(x)
O-Matrix will respond
{
[ 1 , 2 , 3 ]
[ 4 , 6 , 8 ]
}
15.56.d: Dimension
If the argument d is present, it specifies which dimension the sum is taken with respect to. It must be an integer, real, or double-precision scalar equal
to 1 or 2. If you enter
x = { [ 1, 2, 3 ], [3, 4, 5] }
cumsum(x, 2)
O-Matrix will respond
{
[ 1 , 3 , 6 ]
[ 3 , 7 , 12 ]
}
15.57: Product of Elements of a Matrix
Syntax p = prod(x)
p = prod(x, d)
See Also cumprod: 15.58 , cumsum: 15.56 , rowsum: 15.45 , colsum: 15.44 , sum: 15.55 , colrange: 15.13
15.57.a: Description
Returns the product of the elements of the matrix x where x is an integer, real, double-precision or complex matrix and p has the same type as x.
15.57.b: Vectors
If x is a vector, p is a scalar and
p = x
* x
1
* ... * x
2
n
where n is the number of elements in x. If you enter
x = [ 1, 2, 3 ]
prod(x)
O-Matrix will respond
6
If you enter
x = { 1, 2, 3 }
prod(x)
O-Matrix will respond
6
15.57.c: Matrices
If x is not a vector, p is a row vector with the same column dimension as x and
p
= x
* x
* ... * x
j
1,j
2,j
m,j
where m is the number of rows in the matrix x. If
x = { [ 1, 2, 3 ], [3, 4, 5] }
prod(x)
you enter
O-Matrix will respond
{
[ 3 , 8 , 15 ]
}
15.57.d: Dimension
If the argument d is present, it specifies which dimension the product is taken with respect to. It must be an integer, real, or double-precision scalar
equal to 1 or 2. If you enter
x = { [ 1, 2, 3 ], [3, 4, 5] }
prod(x, 2)
O-Matrix will respond
{
6
60
}
15.58: Running Cumulative Product of Elements of a Matrix
Syntax cumprod( x)
cumprod( x, d)
See Also prod: 15.57 , cumsum: 15.56 , rowsum: 15.45 , colsum: 15.44 , sum: 15.55 , colrange: 15.13
15.58.a: Description
Returns the cumulative product of the elements of the matrix x as a matrix with the same type and dimension as x where x is an integer, real, doubleprecision or complex matrix.
15.58.b: Vectors
If x is a vector, the i-th element of the return value is
x
* x
1
* ... * x
2
i
If you enter
x = [ 1, 2, 3 ]
cumprod(x)
O-Matrix will respond
[ 1 , 2 , 6 ]
If you enter
x = { 1, 2, 3 }
cumprod(x)
O-Matrix will respond
{
1
2
6
}
15.58.c: Matrices
If x is a matrix, the (i,j)-th element of the return value is
x
* x
1,j
* ... * x
2,j
i,j
If you enter
x = { [ 1, 2, 3 ], [3, 4, 5] }
cumprod(x)
O-Matrix will respond
{
[ 1 , 2 , 3 ]
[ 3 , 8 , 15 ]
}
15.58.d: Dimension
If the argument d is present, it specifies which dimension the product is taken with respect to. It must be an integer, real, or double-precision scalar
equal to 1 or 2. If you enter
x = { [ 1, 2, 3 ], [3, 4, 5] }
cumprod(x, 2)
O-Matrix will respond
{
[ 1 , 2 , 6 ]
[ 3 , 12 , 60 ]
}
16: Special Functions
16.a: Contents
erf: 16.1
The Error Function
ierf: 16.2
The Inverse Error Function
erfc: 16.3
The Complementary Error Function
beta: 16.4
The Beta Function
betai: 16.5
The Incomplete Beta Function
gamma: 16.6 The Gamma Function
gammln: 16.7 The Logarithm Of The Gamma Function
gammainc: 16.8 The Incomplete Gamma Function
besselj: 16.9
The Jn Bessel Function
bessely: 16.10 The Yn Bessel Function
besseli: 16.11 The In Bessel Function
besselk: 16.12 The Kn Bessel Function
elliprf: 16.13 Carlson's Elliptic Integrals of the First Kind
elliprd: 16.14 Carlson's Elliptic Integrals of the Second Kind
elliprj: 16.15
Carlson's Elliptic Integrals of the Third Kind
ellipf: 16.16
Legendre's Elliptic Integrals of the First Kind
ellipe: 16.17
Legendre's Elliptic Integrals of the Second Kind
ellipi: 16.18
Legendre's Elliptic Integrals of the Third Kind
kolsmi: 16.19 Kolmogorov-Smirnov Test
psi: 16.20
Psi (digamma) Function
airy: 16.21
Airy Functions
isprime: 16.22 Matrix Elements That are Prime Numbers
lentz: 16.23
Lentz's Method For Evaluating Continued Fractions
16.1: The Error Function
Syntax erf(x)
16.1.a: Description
Returns an element-by-element: 26.n approximation of the error function, where x is a real or double-precision matrix.
The error function is defined by
x
2
/
erf(x) = -------- |
sqrt(pi) /
2
-t
e
dt
0
16.1.b: Example
ginit
x = 0. : .1 : 3.
gtitle("Error Function")
gplot(x, erf(x))
returns the following plot:
16.2: The Inverse Error Function
Syntax ierf(y)
16.2.a: Description
Returns the element-by-element: 26.n inverse of the error function erf: 16.1 . The matrix y is real or double-precision and its elements are between -1
and +1 exclusive.
16.2.b: Example
ginit
x = 0. : .01 : .99
gtitle("Inverse Error Function")
gplot(x, ierf(x))
returns the following plot:
16.2.c: Mlmode
In Mlmode: 25 , this function is automatically included: 3.9 as erfinv instead of ierf. If in Mlmode you enter
clear
x = 0. : .01 : .99;
omgtitle('Inverse Error Function');
plot(x, erfinv(x));
O-Matrix will draw the plot above.
16.3: The Complementary Error Function
Syntax erfc(x)
16.3.a: Description
Returns an element-by-element: 26.n approximation of the complementary error function, where x is a real or double-precision matrix.
The complementary error function is defined by
inf
2
/
-t
| e
dt
/
x
equal to 1 - erf(x).
2
---------sqrt(2 pi)
which is also
16.3.b: Example
ginit
x = 0. : .1 : 3.
gtitle("Complementary Error Function")
gplot(x, erfc(x))
returns the following plot:
16.4: The Beta Function
Syntax beta(z, w)
See Also betai: 16.5 , besselj: 16.9 , gammln: 16.7 , erf: 16.1
16.4.a: Description
Returns the element-by-element: 26.n values for the beta function, where z and w are real or double-precision, and all of their elements are greater than
0.
The beta function is defined by
1
/
beta(z, w) = |
/
(z - 1)
t
(w - 1)
(1 - t)
dt
0
16.4.b: Example
If you enter
z = [1., 2., 3.]
w = [3., 2., 1.]
beta(z, w)
O-Matrix will respond
[
0.333333 , 0.166667 , 0.333333 ]
16.5: The Incomplete Beta Function
Syntax betai( a, b, x)
16.5.a: Description
Returns the element-by-element: 26.n incomplete beta function
x
1
/
betai(a, b, x) = ---------- |
beta(a, b) /
(a - 1)
t
(b - 1)
(1 - t)
dt
0
where a, b, and x are real or double-precision matrices and 0 < x(i,j) < 1.
16.5.b: Example
x = {0. : .05 : 1.}
a = 8.
b = 10.
gplot(x, betai(a, b, x))
returns the following plot:
16.6: The Gamma Function
Syntax gamma( x)
16.6.a: Description
Returns the element-by-element: 26.n gamma function, where x is a an integer, real, double-precision, or complex matrix such that the real part of each
element of x is greater than 0. The return value has the same dimension as x. If x is integer, the return value is double-precision, otherwise it has the
same type as x.
16.6.b: Gamma Function
The gamma function is defined by
+inf
/
- t (x - 1)
gamma(x) = | e
t
dt
/
0
You can use integration by parts to note that if x is equal to an integer greater than zero,
gamma(x) = (x - 1) !
16.6.c: Example
If you enter
x = seq(4)
gamma(x)
{
1
1
2
6
}
16.7: The Logarithm Of The Gamma Function
Syntax gammln(z)
See Also gammaln: 16.7.d , gamma: 16.6 , gammainc: 16.8 , beta: 16.4 , besselj: 16.9 , bessely: 16.10 , erf: 16.1
16.7.a: Description
Returns the element-by-element: 26.n logarithm of the gamma function, where z is a real, double-precision, or complex matrix such that the real part
of each element of z is greater than 0. The return value has the same type and dimension as z.
16.7.b: Gamma Function
The gamma function is defined by
+inf
/
- t (z - 1)
gamma(z) = | e
t
dt
/
0
16.7.c: Example
ginit
x = .1 : .1 : 3.
gtitle("Log of Gamma Function")
gplot(x, gammln(x))
returns the following plot:
16.7.d: Mlmode
In Mlmode: 25 , this function is automatically included: 3.9 as gammaln as instead of gammln . If in Mlmode you enter
clear
x = .1 : .1 : 3.;
omgtitle('Log of Gamma Function');
plot(x, gammaln(x));
O-Matrix will draw the plot above.
16.8: The Incomplete Gamma Function
Syntax gammainc(x, a)
16.8.a: Description
Returns the element-by-element: 26.n incomplete gamma function
x
1
/
gammainc(x, a) = ---------- |
gamma(a) /
- t
e
(a - 1)
t
dt
0
where a, b, and x are real or double-precision matrices and
and
0 < x(i,j) < 1
0 < a
gamma(a) is the gamma function: 16.7.b
.
16.8.b: Example
clear
x = {0. : .1 : 5.}
a = 1.
gplot(x, gammainc(x, a))
returns the following plot:
16.9: The Jn Bessel Function
Syntax besselj( n, x)
See Also bessely: 16.10 , betai: 16.5 , gammln: 16.7 , erf: 16.1
16.9.a: Description
Returns the element-by-element: 26.n Jn Bessel function, where n is a nonnegative integer scalar, and x is a real or double-precision matrix.
Uses the recurrance relation
2 n
(x) = --- J (x) - J (x)
n+1
x
n
n-1
This recursion is not "stable" if |x| < n.
J
16.9.b: Example
x = seq(100) / 10.
gtitle("J2(x)")
gplot(x, besselj(2, x))
returns the following plot:
16.10: The Yn Bessel Function
Syntax bessely( n, x)
See Also besselj: 16.9 , beta: 16.4 , gammln: 16.7 , erf: 16.1
16.10.a: Description
Returns the element-by-element: 26.n Yn Bessel function, where n is a a nonnegative integer scalar, and x is a real or double-precision matrix such that
all of the elements of x are greater than 0.
Uses the recurrance relation
Y
2 n
(x) = --- Y (x) - Y (x)
n+1
x
n
n-1
16.10.b: Example
x = seq(100) / 10.
gtitle("Y2(x)")
gplot(x, bessely(2, x))
returns the following plot:
16.11: The In Bessel Function
Syntax besseli( n, x)
See Also besselk: 16.12 , bessely: 16.10 , betai: 16.5 , gammln: 16.7 , erf: 16.1
16.11.a: Description
Returns the element-by-element: 26.n In Bessel function of the first kind, where n is 0 or 1. and x is a real or double-precision matrix.
16.11.b: Example
x = seq(100) / 10.
gtitle("I0(x)")
gplot(x, besseli(0, x))
returns the following plot:
16.12: The Kn Bessel Function
Syntax besselk( n, x)
See Also besseli: 16.11 , bessely: 16.10 , betai: 16.5 , gammln: 16.7 , erf: 16.1
16.12.a: Description
Returns the element-by-element: 26.n Kn Bessel function of the third kind, where n is 0 or 1. and x is a real or double-precision matrix.
16.12.b: Example
x = seq(100) / 10.
gtitle("K1(x)")
gplot(x, besselk(1, x))
returns the following plot:
16.13: Carlson's Elliptic Integrals of the First Kind
Syntax elliprf( x, y, z)
16.13.a: Description
Computes an element-by-element: 26.n approximation of the elliptic integral defined by
+inf
1 /
-1/2
-1/2
-1/2
R (x, y, z) = - | (t + x)
(t + y)
(t + z)
dt
f
2 /
0
where the arguments x, y and z are real or double-precision matrices with non-negative elements. If any of these arguments is not a scalar, it must have
the same dimension as the other arguments that are not scalars. For each element, only one of these arguments can be zero.
16.13.b: Example
+inf
1 /
-3/2
-1/2
R (x, x, x) = - | (t + x) dt = - (t + x)
f
2 /
0
|t=+inf
|
|
|
|t=0
-1/2
= x
If you enter
x = double(rand(2, 3))
print elliprf(x, x, x)
print x^(-.5d0)
O-Matrix will print two matrices with the same values.
16.14: Carlson's Elliptic Integrals of the Second Kind
Syntax elliprd( x, y, z)
16.14.a: Description
Computes an element-by-element: 26.n approximation of the elliptic integral defined by
+inf
3 /
-1/2
-1/2
-3/2
R (x, y, z) = - | (t + x)
(t + y)
(t + z)
dt
d
2 /
0
where the arguments x, y and z are real or double-precision matrices with non-negative elements. If any of these arguments is not a scalar, it must have
the same dimension as the other arguments that are not scalars. For each element, z cannot be zero and only one of x and y can be zero.
16.14.b: Example
+inf
3 /
-5/2
-3/2
R (x, x, x) = - | (t + x) dt = - (t + x)
d
2 /
0
|t=+inf
|
|
|
|t=0
-3/2
= x
If you enter
x = double(rand(2, 3))
print elliprd(x, x, x)
print x^(-1.5d0)
O-Matrix will print two matrices with the same values.
16.15: Carlson's Elliptic Integrals of the Third Kind
Syntax elliprj( x, y, z, p)
16.15.a: Description
Computes an element-by-element: 26.n approximation of the elliptic integral defined by
+inf
3 /
-1/2
-1/2
-1/2
-1
R (x, y, z, p) = - | (t + x)
(t + y)
(t + z)
(t + p) dt
j
2 /
0
where the arguments x, y and z are real or double-precision matrices with non-negative elements. If any of these arguments is not a scalar, it must have
the same dimension as the other arguments that are not scalars. For each element, z cannot be zero and only one of x and y can be zero.
16.15.b: Example
+inf
3 /
-5/2
-3/2
R (x, x, x, x) = - | (t + x) dt = - (t + x)
j
2 /
0
|t=+inf
|
|
|
|t=0
-3/2
= x
If you enter
x = double(rand(2, 3))
print elliprj(x, x, x, x)
print x^(-1.5d0)
O-Matrix will print two matrices with the same values.
16.16: Legendre's Elliptic Integrals of the First Kind
Syntax ellipf(phi, k)
16.16.a: Description
Computes an element-by-element: 26.n approximation of the elliptic integral defined by
phi
/
2
2
-1/2
F(phi, k) = | [ 1 - k sin (x) ]
dx
/
0
where the arguments phi and k are real or double-precision matrices. If both of these arguments is not a scalar, they must have the same dimension. For
each (i, j),
| phi(i, j) | < pi/2
and
| k(i, j) | < 1
16.16.b: Example
phi
/
F(phi, 0) = | dx = phi
/
0
If you enter
phi = rand(2, 3)
print ellipf(phi, 0.)
print phi
O-Matrix will print two matrices with the same values.
16.17: Legendre's Elliptic Integrals of the Second Kind
Syntax ellipe(phi, k)
16.17.a: Description
Computes an element-by-element: 26.n approximation of the elliptic integral defined by
phi
/
2
2
1/2
E(phi, k) = | [ 1 - k sin (x) ]
dx
/
0
where the arguments phi and k are real or double-precision matrices. If both of these arguments is not a scalar, they must have the same dimension. For
each (i, j),
| phi(i, j) | < pi/2
and
| k(i, j) | < 1
16.17.b: Example
phi
/
E(phi, 0) = | dx = phi
/
0
If you enter
phi = rand(2, 3)
print ellipe(phi, 0.)
print phi
O-Matrix will print two matrices with the same values.
16.18: Legendre's Elliptic Integrals of the Third Kind
Syntax ellipi(phi, n, k)
16.18.a: Description
Computes an element-by-element: 26.n approximation of the elliptic integral defined by
phi
/
2
-1
2
2
-1/2
Pi(phi, n, k) = | [1 + n sin (x) ] [ 1 - k sin (x) ]
dx
/
0
where the arguments phi n and k are real or double-precision matrices. If both of these arguments is not a scalar, they must have the same dimension.
For each (i, j),
| phi(i, j) | < pi/2
and
| k(i, j) | < 1
16.18.b: Example
phi
/
Phi(phi, 0, 0) = | dx = phi
/
0
If you enter
phi = rand(2, 3)
print ellipi(phi, 0., 0.)
print phi
O-Matrix will print two matrices with the same values.
16.19: Kolmogorov-Smirnov Test
Syntax kolsmi(sample, function cum)
16.19.a: Description
Tests the hypothesis that a set of samples come from the candidate distribution specified by the cumulative distribution function cum. The real or
double-precision column vector sample contains the samples of the random variable that we are testing. If s is a column vector with the same type as
sample, the function call cum(s) returns a vector with the same type and dimension as s containing the element-by-element value of the cumulative
distribution. The return value of kolsmi is a scalar with the same type as sample. It is the probability that the maximum difference between the sample
cumulative distribution and the candidate cumulative distribution is greater than or equal to the value corresponding to sample (under the hypothesis
that the candidate distribution is correct).
16.19.b: Example
If you enter
sample = rand(20, 1)
O-Matrix will store twenty realizations of a random variable that is uniformly distributed between zero and one. If you continue by entering
kolsmi(sample, function cnormal)
O-Matrix will print the probability that a normal random variate would yield a sample cumulative distribution that has a greater deviation than the one
corresponding to sample. This statistic should be very small relative to one, because sample does not come from a normal random variable.
16.20: Psi (digamma) Function
Syntax psi(X)
See Also exp: 6.2.6 , gamma: 16.6 , log: 6.2.7 , beta: 16.4
16.20.a: Description
Returns the element-by-element: 26.n values for the psi function, where X is a real or double-precision matrix. The psi function is the logarithmic
derivative of the gamma function.
psi(x)
=
d
-- ln | (x)
dx
If x is negative, it is transformed to a positive argument by the reflection formula psi(1-x) = psi(x) + pi cot(pi x).
16.20.b: Example:
If you enter
-psi(1.0)
O-Matrix will respond
0.577216
which is Euler's constant.
16.21: Airy Functions
Syntax airy(X)
airy(airyKind, X)
See Also besselj: 16.9 , bessely: 16.10 , besseli: 16.11 , besselk: 16.12
16.21.a: Description
Returns the element-by-element: 26.n values for the airy function, Ai(x), of the elements of X where X is a real or double-precision matrix. If present,
the argument airyKind must be an integer scalar. If the value of airyKind is 0 the function returns Ai(x). (same as single argument case) If the value of
airyKind is 1 the function returns the derivative Ai'(x). If the value of airyKind is 2 the function returns the airy function of the second kind, Bi(X). If
the value of airyKind is 3 the function returns the derivative Bi'(X).
16.21.b: Example
If you enter
airy(1.0)
O-Matrix will respond
0.135292
16.22: Matrix Elements That are Prime Numbers
Syntax isprime( x)
See Also ceil: 6.1.11 , floor: 6.1.10 , roundoff: 6.1.13 , int: 6.4.2 , mod: 6.1.14
16.22.a: Description
Returns a logical valued matrix that has the same dimensions as x containing true for the elements of x that are prime and false otherwise.
16.22.b: Example
isprime(1:1:11)'
returns
[ F , T , T , F , T , F , T , F , F , F , T ]
16.23: Lentz's Method For Evaluating Continued Fractions
Syntax lentz( a, b)
16.23.a: Description
The i-th element of the return value is the continued fraction
b(i, 1) + a(i, 1)
------b(i, 2) + a(i, 2)
------b(i, 3) + ...
+ a(i, n)
----------b(i, n + 1)
where a and b are real, double-precision or complex matrices with the same row dimension. The value n in the expression above is the column
dimension of a which must be one less than the column dimension of b. The return value is a column vector with the same row dimension as a and has
the same type as results from coercion: 4.4 between the type of a and the type of b.
16.23.b: Example
The continued fraction representation of the tangent function is
tan(x) =
x
--2
1 - x
--2
3 - x
--2
5 - x
--7 - ...
The tangent of pi / 4 is one. We can compare this
x = PI / 4d0
a = [
x, -x^2, -x^2, -x^2, -x^2]
b = [0, 1,
3,
5,
7,
9]
b = double(b)
print "lentz(a, b) =", lentz(a, b)
to the first five terms of the continued fraction as follows:
16.23.c: Reference
When the maximal difference between terms in the factional representation is less than machine epsilon times the maximum element in b, the
expansion is assumed to have converged and the series is truncated.
17: Integration And Differential Equations
17.a: Contents
trapz: 17.1
Trapezoidal Approximation for Integrals
gaussq: 17.2 Fifth Order Gaussian Quadrature Numerical Integration
gaussq2d: 17.4 Two Dimensional Gaussian Quadrature Integration
gaussleg: 17.5 Computing Gauss-Legendre Quadrature Weights
int2inf: 17.7 Numerical Integration to Infinity
ode4rk: 17.8 A Fourth Order Runge-Kutta ODE Solver
expmat: 17.9 Exponential Of A Matrix
ode45rk: 17.10 Fifth Order Runge-Kutta Method With Fourth Order Error Control
odepade: 17.11 Solving An ODE Using The Matrix Exponential
odestiff: 17.12 Solving Stiff Ordinary Differential Equations
17.1: Trapezoidal Approximation for Integrals
Syntax trapz( y)
trapz( x, y)
trapz( y, d)
trapz( x, y, d)
17.1.a: Description
Computes the trapezoidal approximation for the integral
/ x(N)
|
|
F(x) dx
|
/ x(1)
~=
N-1
-->
--i=1
[ x
i+1
x ] [ F(x ) + F(x ) ] / 2
i
i
i+1
where N is the length of the vector x. The arguments x, y and d are integer, real, double-precision, or complex. The return value has the type that results
from coercion: 4.4 between the type of x and the type of y.
If the argument x is not present, the default value
x
=
i
i
is used. The relationship between F(x), N, and the arguments y, d, is defined below.
trapz(y)
If y is a row vector, N is the column dimension of y and
y = F(i)
i
If y is not a row vector, N is the row dimension of y and
[y
, ... , y
i,1
] = F(i)
i,n
where n is the column dimension of y.
trapz(x, y)
If y is a row vector, N is the column dimension of y and
y = F(x )
i
i
If y is not a row vector, N is the row dimension of y and
[y
, ... , y
i,1
] = F(x )
i,n
i
where n is the column dimension of y.
trapz(y,
trapz(x,
d)
y, d)
The argument d must be equal to one or two. If d is equal to one, N is the row dimension of y and
[y
, ... , y
i,1
] = F(x )
i,n
i
where n is the column dimension of y. If d is equal to two, N is the column dimension of y and
T
[y
, ... , y
i,1
]
i,n
= F(x )
i
where n is the row dimension of y.
17.1.b: Example
The trapezoidal rule is exact for linear functions such as F(x) = x. In addition,
1
1
/
- = |
2
/
x
dx
0
If you enter
clear
x = linspace(0d0, 1d0, 5)
y = x
trapz(x, y)
0.5
17.1.c: Reference
The arguments x and y each must have more than one element. This distinguishes them from the argument d in the syntax trapz( y, d)
17.2: Fifth Order Gaussian Quadrature Numerical Integration
Syntax gaussq(function fvec, a, b, bound)
17.2.a: Description
Returns a fifth-order (three point) Gaussian quadrature approximation for the integral of f(x) over the interval [a, b]. The return value is a scalar
with the same type as a. The function call fvec(xvec) returns the column vector
T
[f(xvec(1)), f(xvec(2)), ... , f(xvec(n))]
with the same type as xvec, where n is the dimension of the column vector xvec. The column vector xvec will have the same type as a. The real or
double-precision scalar a specifies the lower limit for the integration. The scalar b has the same type as a and specifies the upper limit for the
integration. The scalar bound has the same type as a and specifies an upper bound for the quadrature interval size. As this bound gets smaller, the
integration becomes more accurate and the number of necessary function evaluations increases.
17.2.b: Example
The following example integrates the cosine function between 0 and pi/2. The integration interval is broken into sub-intervals each of which is at
most 1 unit long and a fifth-order (three point) Gaussian quadrature approximation is used on each sub-interval. A special version of the cosine
function is defined because O-Matrix intrinsic functions cannot be passed as arguments.
function cosine(x) begin
return cos(x)
end
a
= 0.
b
= pi / 2
bound = 1.
gaussq(function cosine, a, b, bound)
returns
1
The exact integral is the difference in the sine function between 0 and pi/2 which is 1.
17.3: Two Dimensional Integration Using Gauss-Legendre Quadrature
Syntax quad2d(function fvec, xmin, xmax, ymin, ymax ...
, tol, trace, m)
Where tol, trace and m are optional
17.3.a: Description
Computes a numerical approximation for I defined by
/xmax
g(y) = |
f(x, y) * dx
/xmin
I
/ymax
= |
/ymin
g(y) * dy
Both the inner integral defining g(y) and the outer integral defining I are approximated using Gauss-Legendre quadrature. The arguments xmin, xmax,
ymin, ymax are real or double-precision scalars and of the same type.
fvec(x, y)
Returns a real, double-precision or complex column vector that equals
T
[f(x(1), y), ... , f(x(n), y)]
where x is a vector with the same type as xmin, n
is the number of elements in x, and y is a scalar with the same type as ymin.
tol
is a real or double-precision vector with four elements. The first element of tol specifies the relative accuracy for the integration (relative to the integral
of the absolute value of the function). The second element specifies an absolute accuracy for the integration. The total allowable error is the sum of the
absolute and relative error. The third (fourth) element specifies an absolute minimum for the size of a quadrature interval in the x (y) direction.
Individual Quadrature interval sizes will be separately reduced until the accuracy requirement is met but will never be reduced below this value. If tol
is not present, the default value
tol = 1d-3 * [1, 0, (xmax - xmin), (ymax - ymin)]
is used. In addition, if the length of tol is less than 4, the default value is used for the missing elements.
trace
is a logical, integer, real, double-precision or complex scalar. If it is not equal to zero, each function value g(y) corresponds to a single symbol plotted
in the current viewport: 26.aq at (y, g(y)). If trace is not present, the default value false use used.
m
is an integer scalar that is equal to an integer and that specifies the number of weights and abscissa pairs for each quadrature interval. It may also be a
character row vector equal to "quad" or "quad8" which specifies 2 or 4 pairs respectively. The default value for m is 2.
17.3.b: Example
Suppose that
f(x, y) = y * sin(x) + x * cos(y)
xmin
= pi
xmax
= 2 * pi
ymin
= 0
ymax
= pi
If follows that
/ 2 * pi
g(y) = |
[y * sin(x) + x * cos(y)] * dx
/ pi
= y * [cos(pi) - cos(2 * pi)] + (2 * pi - pi) * cos(y)
= - 2 * y + pi * cos(y)
/ pi
= |
[- 2 * y + pi * cos(y)] * dy
/ 0
I
= - 2 * [pi^2 / 2 - 0^2 / 2] + pi * [sin(pi) - sin(0)]
= - pi^2
The program below computes an approximation for the integral above. If you execute the program, O-Matrix will reply
-9.8691
which is close to 2 * pi.
clear
function f(x, y) begin
return y * sin(x) + x * cos(y)
end
xmin = PI
xmax = 2 * PI
ymin = 0d0
ymax = PI
tol
= 1d-3 * [1, 0, 1, 1]
trace = true
m
= 2
quad2d(function f, xmin, xmax, ymin, ymax, tol, trace, m)
17.3.c: Mlmode
In mlmode: 25 this function is called dblquad. In addition, the first argument is a character row vector called fun instead of function fvec. The call
feval(fvec, x, y)
should evaluate the function where x is a vector and y is a scalar. If the file temp.m contains the following text
function f = temp(x, y)
f = y * sin(x) + x * cos(y);
and you enter
fun
= 'temp';
xmin = pi;
xmax = 2 * pi;
ymin = 0;
ymax = pi;
tol
= 1e-3 * [1, 0, 1, 1];
trace = 1;
m
dblquad(fun, xmin, xmax, ymin, ymax, tol, trace, m)
-9.8691
17.4: Two Dimensional Gaussian Quadrature Integration
Syntax gaussq2d(function fvec, limx, function limy)
17.4.a: Description
Returns a fifth-order Gaussian quadrature approximation for
x2
/
|
/
y1(x)
dx
x1
/
|
/
f(x, y) dy
y1(x)
as a scalar with the same type as limx. The real or double-precision vector limx has three elements: the first is the lower limit for integration in the x
direction (x1); the second is the upper limit (x2); and the third is a bound for the size of quadrature intervals in the x direction.
limy(x)
Returns a three-element vector with the same type as limx: the first is the lower limit for integration in the y direction [y1(x)]; the second is the upper
limit [y2(x)]; and the third is a bound for the size of quadrature intervals in the y direction.
fvec(x, yvec)
Returns the column vector
T
[f(x, yvec(1)), f(x, yvec(2)), ... , f(x, yvec(n))]
with the same type as limx, where the scalar x has the same type as limx and yvec is a column vector of length n with the same type as limx.
The third element or limx and of limy(x) control the accuracy and amount of work by determining how many quadrature intervals are necessary.
17.4.b: Example
The following program prints an approximation for the integral
1
1
/
/
| dx | x y dy
/
/
0
0
=
1
2 1
/
y |
| dx x --- |
/
2 |
0
0
=
1
2
1
/
| x dx
/
0
=
1
4
clear
#
function fvec(x, yvec) begin
return x % yvec
end
function limy(x) begin
y1
= 0.
y2
= 1.
ybnd = .2
return {y1, y2, ybnd}
end
x1
= 0.
x2
= 1.
xbnd = .2
limx = {x1, x2, xbnd}
gaussq2d(function fvec, limx, function limy)
Syntax gaussleg(n, aout, wout)
17.5.a: Description
Determines the Gauss-Legendre weights, wout and abscissas aout such that
+1
/
| f(x) dx = wout f(aout ) + ... + wout f(aout )
/
1
1
n
n
-1
where f(x) is any polynomial of degree 2 n - 1 or less.
The integer scalar n specifies the number of points in the quadrature. The input value of aout does not matter. Its output value is a double-precision
column vector of length n containing the abscissas for the quadrature. The input value of wout does not matter. Its output value is a double-precision
column vector of length n containing the weights for the quadrature.
17.5.b: Example
The following example integrates the cosine function between zero and pi/2 using one quadrature interval. The result of the integral is printed in the
command window.
clear
n
= 5
aout = novalue
wout = novalue
gaussleg(n, aout, wout)
ratio = (pi / 2d0) / 2d0
# ratio of [0, pi/2] / [-1, +1]
x
= ratio * (aout + 1d0)
# abscissas in [0, pi/2]
print "approximation for the integral =", ratio * wout' * cos(x)
Syntax [I, e, n] = quadint(function f, a, b, m, tol, trace)
17.6.a: Description
Computes I, an approximation for
/b
| f(x) dx
/a
using the Gauss-Legendre quadrature weights and abscissas. These quadrature weights and abscissas are chosen so that the approximation is exact for
a polynomial of degree 2 m - 1 or less. If the function call f(x) returns a complex value, I is complex. Otherwise I is double-precision. The return
value e is an estimate of the error in the integral. The return value n is the number of values of x at which the function f(x) was evaluated.
f (x )
This function call computes the element-by-element: 26.n element-by-element value of the function f at the points specified by the vector x where x
has the same type as a. The return value can be integer, real, double-precision or complex.
a
is a real or double-precision scalar that specifies the lower limit for the integration.
b
is a real or double-precision scalar that specifies the upper limit for the integration.
m
is a scalar that is equal to an integer and that specifies the number of weights and abscissas for each quadrature interval.
tol
is a real or double-precision vector with three elements. The first element of tol specifies the relative accuracy for the integration (relative to the
integral of the absolute value of the function). The second element specifies an absolute accuracy for the integration. The total allowable error is the
sum of the absolute and relative error. The third element specifies an absolute minimum for the size of a quadrature interval. Individual Quadrature
interval sizes will be separately reduced until the accuracy requirement is met but will never be reduced below this value.
trace
is a scalar. If it is non-zero (true), each function value corresponds to a single symbol plotted in the current viewport: 26.aq at (x, f(x)).
17.6.b: Example
The following example computes the value
/ pi
2 = |
sin(x) dx
/ 0
and plots the value of the integrand while doing so.
clear
function f(x) begin
return sin(x)
end
a
= 0d0
b
= PI
m
= 3
tol
= 1d-5 * {1,1,1}
trace = true
quadint(function f, a, b, m, tol, trace)
17.6.c: Mlmode
In Mlmode: 25 , this function is accessed using the following syntax:
I = quad(fun, a, b, tol, trace)
I = quad8(fun, a, b, tol, trace)
m = 2
m = 4
The argument fun is a string specifying the name of the function that is being integrated. The arguments a and b have the exact same meaning as for
quadint. The arguments tol and trace need not be present in which case the default values
tol
= [ 1e-3 , 0 , 1e-3 * (b - a) ]
trace = 0
are used. The elements of the argument tol have the same meaning as for quadint except that not all the elements need to included and default values
are used for ones that are not included.
Suppose that the file fun.m in the current directory contains the text
function y = fun(x)
y = sin(x);
If in Mlmode you execute the program below,
clear
a
= 0;
b
= pi;
tol
= 1d-5;
trace = 1;
O-Matrix will trace the values of the sine function it used and print the value
2
If you continue by entering
you will notice that few function values are plotted because fewer evaluations of f(x) are required.
17.7: Numerical Integration to Infinity
Syntax int2inf(function fvec, low, eps)
17.7.a: Description
Returns an approximation for
+inf
/
| f(x) dx
/
low
where low is a real or double-precision scalar. Given a column vector xvec of length n and with the same type as low, the function fvec returns the
column vector
/
| f(xvec )
|
1
| f(xvec )
\
|
|
|
|
2
|
...
| f(xvec )
\
n
|
|
|
/
The relative accuracy for the integral is specified by eps which is a scalar with the same type as low . If the approximation converges, the return value
is a scalar with the same type as low. Otherwise, the return value has type equal to "novalue".
17.7.b: Example
If you enter
clear
function fvec(xvec) begin
return exp(-xvec)
end
low = 0.
eps = 1e-5
int2inf(function fvec, low, eps)
1
which is equal to the integral of exp(-x) from zero to infinity.
17.7.c: Reference
This integration method assumes that
2
f(x)
x
-->
0
as x --> +infinity
17.8: A Fourth Order Runge-Kutta ODE Solver
Syntax ode4rk(function f, ti, tf, yi, n)
17.8.a: Description
Uses a fourth-order Runge-Kutta method to solve the differential equation
d
-- y(t) = f(t, y(t))
dt
with initial condition y(ti) = yi. The return value is the numerical approximation for
[y(ti + s), y(ti + 2 s), . . . , y(ti + n s)],
where s = (tf - ti)/n is the step size of the Runge-Kutta method. The return value has the same type
and number of rows as yi, and has n columns.
The scalar ti specifies the initial time point. If yi is complex, ti is double-precision; otherwise, ti has the same type as yi. The scalar tf has the same type
as ti and specifies the final time point. The column vector yi is either real, double-precision, or complex and specifies the value of y(t) at t = ti. The
integer scalar n specifies the number of integration steps between ti and tf.
The function call f(t, y) returns the derivative of y at time t, provided t is a scalar with the same type as ti, and y is a vector with the same type and
dimension as yi. The return value has the same type and dimension as yi.
17.8.b: Example
The follows program plots the solution of the differential equation
y'(t) =
1
y (t)
2
y (0) = 0
1
y'(t) = -y (t)
2
1
y (0) = 1
2
The solution is
y (t) = sin(t)
1
y (t) = cos(t)
2
clear
#
function f(t, y) begin
return {y(2), -y(1)}
end
ti = 0.
tf = 2 * pi
yi = {0., 1.}
n = 30
y = ode4rk(function f, ti, tf, yi, n)
s = (tf - ti) / real(n)
t = tf + seq(n) * s
gplot(t, y')
17.9: Exponential Of A Matrix
Syntax expmat(A, tol, mstep)
17.9.a: Description
Returns the matrix exponential of A, where A is a real, double-precision, or complex matrix square matrix: 26.ak , tol is a real or double-precision
scalar specifying the desired absolute accuracy in each element, mstep is an integer greater than 1 that specifies the base 2 logarithm of the maximum
number of steps to use before giving up on the desired accuracy. The return value has the same type and dimension as A.
The matrix exponential of A is defined by
2
3
I + A + A / 2! + A / 3! + ...
where the powers represent matrix multiplication.
17.9.b: Example
x = {[1., 0.], [0., 2.]}
tol = 1e-4
mstep = 6
expmat(x, tol, mstep)
returns
{
[ 2.71828 , 0 ]
[ 0 , 7.38906 ]
}
Note that for diagonal matrices the matrix exponential is the scalar exponential of the diagonal elements and the scalar exponential of 1 and 2 are
2.71828 and 7.38906, respectively.
17.10: Fifth Order Runge-Kutta Method With Fourth Order Error Control
,,
Syntax
[tout, yout, sout] = ode45rk(function f, ...
t0, tf, y0, tol, level, smin, smax, sini)
Optional sout, tol, level, smin, smax, sini
17.10.a: Description
Solves a system the following system of ordinary differential equations:
dy
-- = f(t, y(t))
dt
and
y(t0) = y0
using a fifth order Runge-Kutta method and using a fourth order Runge-Kutta method to estimate the error in the solution reference: 17.10.d
f (t , y )
This function call returns the value of f(t, y(t)) where t is an integer, real or double-precision scalar, and y is an integer, real or double-precision
column vector with the same length as y0. The return value is an integer, real, double-precision or complex vector with the same dimension as y0.
t0
is an integer, real or double-precision scalar specifying the initial value of t.
tf
is an integer, real or double-precision scalar specifying the final value of t.
y0
is an integer, real, double-precision or complex column vector specifying the value of y(t0).
tol
is an integer, real or double-precision vector that specifies the requested accuracy in the return values in yout. If tol is a column vector with the same
length as y0, tol(j) specifies the accuracy for the elements in the j-th column of yout. All the elements of tol must be greater than zero. If tol is a
scalar, it is equivalent to the case where it is a column vector with the same length as y0 and all the elements have the value specified by the scalar. If
tol is not present in the syntax, the default value
tol
= 1d-3
is used.
level
is a logical integer, real or double-precision scalar that specifies the level of tracing during solution of the differential equation. If level is equal to zero,
no tracing is done. If level is equal to one, the current value of t, the current step size, and the transpose of the current value of y(t) are printed upon
completion of each successful step. If level is not present in the syntax, the default value
level
= 0
is used.
smin
is an integer, real or double-precision scalar that specifies the minimum step size; i.e., difference between successive elements of tout. If this argument
is not present in the syntax, the default value
smin
= (tf - t0) / 1d4
is used.
smax
is an integer, real or double-precision scalar that specifies the maximum step size; i.e., difference between successive elements of tout. If this argument
is not present in the syntax, the default value
smax
= (tf - t0) / 16
is used.
sini
is an integer, real or double-precision scalar that specifies the initial step size. It must satisfy the relations
smin < sini < smax
If this argument is not present in the syntax, the default value
sini
= smax
is used.
tout
is a monotone increasing: 26.y column vector with its first element equal to t0, and its last element equal to tf. In addition,
smin < tout
- tout
i+1
> smax
i
If all the input values are real, tout is real, otherwise it is double-precision.
yout
is a matrix containing an approximate solution of the differential equation. Its row dimension is equal to the row dimension of tout and its column
dimension is equal to the row dimension of y0. The ode45rk routine will try to accomplish the requested accuracy condition which is that for i
between one and the row dimension of tout and j between one and the row dimension of y0,
| yout
j
- y (tout(i)) | <= tol
j
j
If y0 is complex, yout is also complex. Otherwise yout is double-precision.
sout
is a scalar that suggests a value for sini when continuing solution of the differential equation using ode45rk. (A continuation is where the new value of
t0 is equal to the old value of tf and the new value of y0 is approximately equal to y(tf).)
17.10.b: Example
The follows program plots the solution of the differential equation
y'(t) =
1
y (t)
2
y (0) = 0
1
y'(t) = -y (t)
2
1
y (0) = 1
2
The solution is
y (t) = sin(t)
1
y (t) = cos(t)
2
clear
#
function f(t, y) begin
return {y(2), -y(1)}
end
t0
= 0.
tf
= 2. * pi
y0
= {0., 1.}
[tout, yout] = ode45rk(function f, t0, tf, y0)
gplot(tout, yout)
17.10.c: Mlmode
In Mlmode: 25 , this function is accessed using the following syntax
[tout, yout] = ode(yp, t0, tf, y0, tol, level)
where ode is ode23 or ode45 and the arguments tol, level are optional. In addition, each call of the form f(t, y) in ode45rk is translated to a call of
the form feval(yp, t, y).
Suppose that the file yp.m in the current directory contains the text
function dy = yp(t, y)
dy = [y(2); -y(1)];
If in Mlmode you execute the program below, the same plot will be generated as for the ode45rk example above.
clear
t0
= 0.;
tf
= 2. * pi;
y0
= [0.; 1.];
[tout, yout] = ode45('yp', t0, tf, y0)
plot(tout, yout)
17.10.d: Reference
The method uses the Cash-Karp parameters in Section 16.2 of the second edition of Numerical Recipes in Fortran by William H. Press, Saul A.
Teukolsky, William T. Vetterling, and Brian P. Flannery.
17.11: Solving An ODE Using The Matrix Exponential
Syntax odepade( A, tf, yi, n)
17.11.a: Description
Solves the differential equation dy/dt = A y with initial condition y(0) = yi, where A is a real, double-precision, or complex square matrix: 26.ak
specifying the linear differential equation, tf is a scalar specifying the final time point (the initial time point is automatically 0), yi is a column vector
specifying the value of y(t) at t = 0 , and n is an integer scalar specifying the number of time points at which to return the value of y(t). If A is
complex, tf must be double-precision; otherwise, tf must have the same type as A. The matrix A and the vector yi have the same number of rows.
The return value is the matrix
[y(s), y(2 s), . . . , y(n s)]
that is, the j-th column of the return value is y(t) at t = j s, where s = tf / n. The return value has the same type and number of rows as yi, and
has n columns.
This function uses the following Pade approximation for the matrix exponential of B, where B = s A
[
[ I
[
where I is
-
B
2
+
2
B
-10
-
3
B
--120
-1
]
]
]
[
[ I
[
+
B
2
+
2
B
-10
+
the identity matrix.
17.11.b: Example
The following program plots the solution of the differential equation
3
B
--120
]
]
]
d [ y ]
[ 0
-- [ 1] = [
dt [ y ]
[-1
2
1 ]
[ y ]
] * [ 1]
0 ]
[ y ]
2
with the initial condition
y (0) = 0
1
y (0) = 1
2
The solution is
y (t) = sin(t)
1
y (t) = cos(t)
2
A = {[0., 1.], [-1., 0.]}
tf = 2 * pi
yi = {0., 1.}
n = 30
y = odepade(A, tf, yi, n)
s = tf / real(n)
t = seq(n) * s
gplot(t, y')
17.12: Solving Stiff Ordinary Differential Equations
Syntax odestiff(function fval, order, ti, tout, ...
maxstep, minstep, yi, eps, skip)
17.12.a: Description
Uses a backward difference method to solve the differential equation
d
-- y(t) = f(t, y(t))
dt
initial condition y(t) = yi
with
at t = ti. The integer scalar order specifies the order of the backward difference method. The real or doubleprecision scalar ti specifies the initial value for t. The row vector tout has the same type as ti and specifies the values of t at which odestiff should
calculate the value of y. The scalar maxstep has the same type as ti and specifies the maximum step size in t. The scalar minstep has the same type as ti
and specifies the minimum step size in t. The column vector yi has the same type as ti and specifies the initial value of y. The column vector eps has
the same type and dimension as yi and eps(i) is the desired accuracy for the i-th element of y(t). The integer scalar skip specifies the level of tracing
inside of odestiff . If skip = 0, no tracing is done; otherwise, the value of y(t) is printed at time tout(skip), tout(2 skip) ... . The return value
for odestiff has the same type and row dimension as yi, the same number of columns as tout, and its j-th column is the value of y at time tout(j).
fval(tin, yin, fout, dfout)
This function call sets fout the value of f(tin, yin) and dfout to the value
d
-- f(tin, yin)
dy
The scalar tin has the same type as ti. The vector yin has the same type and dimension as yi. The input value of fout does not matter. Its output value
has the same type and dimension and row dimension as yi. The input value of dfout does not matter. Its output value is a square matrix: 26.ak with the
same type and row dimension as yi and its (i,j)-th element is the partial of the i-th element of f(t, y) with respect to the j-th element of y.
17.12.b: Example
The following program plots the solution of the differential equation
y'(t) =
1
y (t)
2
y (0) = 0
1
y'(t) = -y (t)
2
1
y (0) = 1
2
The solution is
y (t) = sin(t)
1
y (t) = cos(t)
2
clear
#
function fval(tin, yin, fout, dfout) begin
fout
= {yin(2), -yin(1)}
dfout = {[0., 1.], [-1., 0.]}
return
end
order
= 4
ti
= 0.
tf
= 2 * pi
maxstep = 1.
minstep = .01
yi
= {0., 1.}
eps
= {1e-4, 1e-4}
skip
= 0
tout
= seq(30)' * (tf - ti) / real(30)
yout
= odestiff(function fval, order, ti, tout, ...
maxstep, minstep, yi, eps, skip)
gplot(tout', yout')
18: Polynomials
Every integer, real, double-precision or complex vector corresponds to a descending polynomial: 26.f . In addition, if it is a column vector, it
corresponds to a polynomial: 26.ac stored in ascending order. Some of the routines below operate on polynomials stored in ascending order while
others operate on polynomials stored in descending order. The routine reverse: 9.25 can be used to convert from one ordering to the other.
18.a: Ascending Polynomial Routines
Displaying A Polynomial: 18.1
Evaluating A Polynomial: 18.2
polmul
Polynomial Multiplication: 18.6
polcomp Composition Of Polynomials As Functions: 18.7
polder
Computing the Derivative of a Polynomial: 18.8
zero2pol Converting A Set Of Roots To A Polynomial: 18.9
pol2zero Using Laguerre's Method to Find The Roots of a Polynomial: 18.12
polcheb Computing Chebyshev Polynomial Coefficients: 18.13
polyfit Least Squares Fit of a Descending Polynomial to Data: 13.4
pol2asc
polval
18.b: Descending Polynomial Routines
Evaluating A Descending Polynomial: 18.3
Evaluating A Descending Polynomial Using Matrix Multiplication: 18.4
poly
Converting A Set Of Roots To A Descending Polynomial: 18.11
polyreduce Remove Leading Zero Coefficients from a Descending Polynomial: 18.14
roots
Finding Roots of a Descending Polynomial: 18.10
conv
Convolution of Vectors (Mlmode): 18.15
deconv
Deconvolution or Descending Polynomial Division: 18.16
residue
Calculate the Residues for a Rational Function in Complex Plane: 18.17
compan
Compute the companion matrix corresponding to polynomial: 18.18
polyval
polyvalm
18.c: Other Routines
monomial
Evaluating A Multiple Dimension Monomial And Its Derivatives: 18.19
18.1: Displaying A Polynomial
Syntax pol2asc( p)
18.1.a: Description
Returns an ASCII representation of the polynomial: 26.ac p[x] as a character row vector, where p is an integer, real, double-precision or complex
column vector. The current format: 8.17.1 for the type corresponding to p is used to convert the values in p to ASCII.
18.1.b: Example
pol2asc(seq(3))
returns
1 + 2 x^1 + 3 x^2
18.2: Evaluating A Polynomial
Syntax polval(p, x)
18.2.a: Description
Returns the evaluation of the polynomial: 26.ac corresponding to p at each of the elements of x. The (i,j)-th element of the return value is
2
p[x
] = p
i,j
+
p
1
x
2
+ p
i,j
n-1
x
3
+ . . . +
p
i,j
x
n
i,j
where n is the length of the vector p. The integer, real, double-precision, or complex column vector p specifies the polynomial to be evaluated. The
integer, real, double-precision, or complex matrix x specifies the points at which to evaluate the polynomial. The return matrix has the same dimension
as x and the same type as a binary operation between p and x. (See the coercion: 4.4 entry in the O-Matrix User's Guide.)
18.2.b: Example
p = {-1, 0, 1}
x = -2. : .1 : +2.
v = polval(p, x)
gplot(x, v)
returns the following plot:
18.3: Evaluating A Descending Polynomial
Syntax polyval( p, x)
18.3.a: Description
Returns the evaluation of the descending polynomial: 26.f corresponding to p at each of the elements of x. The (i,j)-th element of the return value is
n-1
p[x
] = p
i,j
x
1
1
+ ... +
i,j
p
x
n-1
+
i,j
p
n
where n is the length of the vector p. The integer, real, double-precision, or complex vector p specifies the polynomial to be evaluated. The integer,
real, double-precision, or complex matrix x specifies the points at which to evaluate the polynomial. The return matrix has the same dimension as x
and the same type as a binary operation between p and x. (See the coercion: 4.4 entry in the O-Matrix User's Guide.)
18.3.b: Example
p = [-1, 0, 1]
x = -2. : .1 : +2.
v = polyval(p, x)
gplot(x, v)
returns the following plot:
18.4: Evaluating A Descending Polynomial Using Matrix Multiplication
Syntax polyvalm(p, x)
18.4.a: Description
Returns the evaluation of the descending polynomial: 26.f corresponding to p at the square matrix: 26.ak x. The return value is
n-1
p[x] = p
1
x
+ ... +
p
1
x
0
+
p
n-1
x
n
where n is the length of the vector p and
0
i+1
i
x = I and for i = 2, ... , n-1, x
= x * x
where * denotes matrix multiplication and I denotes the identity matrix
with same dimensions as x. The integer, real, double-precision, or complex
vector p specifies the polynomial to be evaluated. The integer, real, double-precision, or complex matrix x specifies the argument to the polynomial.
The return matrix has the same dimension as x and the same type as a binary operation between p and x. (See the coercion: 4.4 entry in the O-Matrix
User's Guide.)
18.4.b: Example
If you enter
p = [1, 1, 1]
x = { ...
[ 1 , -1 ], ...
[ 0 , 1 ] ...
}
polyvalm(p, x)
{
[ 3 , -3 ]
[ 0 , 3 ]
}
If you continue by entering
x * x
+
x
+
identity(2)
{
[ 3 , -3 ]
[ 0 , 3 ]
}
18.5.a: Description
Returns a column vector that corresponds to the polynomial that is the sum of the polynomials corresponding to the integer, real, double-precision or
complex column vectors p and q. If v is a column vector of length n the corresponding polynomial v[x] is
1
v[x] = v
+
v
1
x
2
2
+
v
x
n-1
+ ... + v
3
x
n
The return value has the same type as a binary operation between the type of p and the type of q and its length is the maximum of the lengths of p and
q.
18.5.b: Example
If you enter
p = {1, 2}
q = {1, 2, 3, 4}
O-Matrix will respond
{
2
4
3
4
}
Note that if you attempted to evaluate the expression
p + q
O-Matrix would respond with an error message because the length of p and q are different.
18.6: Polynomial Multiplication
Syntax polmul(p, q)
See Also conv: 15.53 , pol2asc: 18.1 , polcomp: 18.7 , polval: 18.2
18.6.a: Description
Returns a column vector containing the product of p and q as polynomials: 26.ac , where both p and q are real, double-precision, or complex column
vectors. The return value has the same type as a binary operation between p and q. (See the coercion: 4.4 entry in the O-Matrix User's Guide.)
This function computes the result directly using the intrinsic function filter: 14.3 . The conv: 15.53 function computes this product using an FFT.
18.6.b: Example
g = {1, 2}
h = polmul(g, g)
pol2asc(h)
returns
1 + 4 x^1 + 4 x^2
18.7: Composition Of Polynomials As Functions
Syntax polcomp( p, q)
18.7.a: Description
Returns a column vector containing the composition of p and q as polynomial: 26.ac functions, where both p and q are real, double-precision, or
complex column vectors. The return value corresponds to the polynomial p[q[x]] and has the same type as a binary operation between p and q. (See
the coercion: 4.4 entry in the O-Matrix User's Guide.)
18.7.b: Example
p = {1, 2, 3}
q = {1, 2}
h = polcomp(p, q)
pol2asc(h)
returns
6 + 16 x^1 + 12 x^2
18.8: Computing the Derivative of a Polynomial
Syntax polder(p)
18.8.a: Description
Returns the column vector that corresponds to the derivative of the polynomial that corresponds to the integer, real, double-precision or complex
column vector p. If v is a column vector of length n the corresponding polynomial v[x] and its derivative dv[x] are
1
v[x] = v
+
v
1
x
2
+
v
2
x
n-1
+
...
+ v
3
1
dv[x] = v
+
2 v
2
x
x
n
n-2
+
... + (n-1) v
3
x
n
The vector p must have at least one element. The return value has the same type as p. If p had one element, the return value is the scalar zero,
otherwise the return value has one less element than the vector p.
18.8.b: Example
If you enter
p = {1, 1, 1, 1}
polder(p)
{
1
2
3
}
18.9: Converting A Set Of Roots To A Polynomial
Syntax zero2pol(z)
18.9.a: Description
Returns a column vector p that corresponds to a polynomial: 26.ac p[x] which is zero at each of the elements of z where z is a real, double-precision,
or complex column vector; that is
p[z ] = 0 for i = 1, . . . , n
i
where n is the length of the vector z. The return
value has the same type as z, its length is n+1, and the n+1-th element of the return value is 1.
18.9.b: Example
z = {-1, +1}
p = zero2pol(z)
pol2asc(p)
returns
-1 + 0 x^1 + 1 x^2
18.10: Finding Roots of a Descending Polynomial
Syntax roots( p)
18.10.a: Description
Returns a complex column vector that contains the roots of the descending polynomial: 26.f corresponding to the real, double-precision or complex
vector p; i.e.,
n-1
p[x] =
p
x
1
+ ... +
1
p
x
n-1
+
p
n
If z is the return value, it has one fewer elements than p and p[x] evaluated at x = z(i) is zero for each i.
18.10.b: Example
The roots of the polynomial
2
x
-
1
are -1 and +1. If you enter
p = [1., 0, -1.]
roots(p)
{
(-1, 0)
(1, 0)
}
{
(1, 0)
(-1, 0)
}
because the order of the roots is not determined.
18.10.c: Exceptions
If the method fails, the return value has type equal to "novalue". This should be a very rare case.
18.11: Converting A Set Of Roots To A Descending Polynomial
Syntax poly(z)
18.11.a: Vector Argument
If z is a vector, poly returns a row vector p that corresponds to a descending polynomial: 26.f p[x] which is zero at each of the elements of z where z
is an integer real, double-precision, or complex column vector; that is
p[z ] = 0 for i = 1, . . . , n
i
where n is the length of the vector z. The return
has length n+1 and the first element of the return value is 1. If the imaginary part: 26.v of z is zero, the
return value has type double-precision, otherwise the return value is complex.
18.11.b: Matrix Argument
If z is a square matrix: 26.ak , poly returns the polynomial that has zeros at the eigen values of z; i.e.,
poly(eigen(z))
18.11.c: Example
We can compute the product
x^2 - 1 = (x + 1) * (x - 1)
which has the descending polynomial representation
[ 1 , 0 , -1 ]
by
z = [-1, +1]
poly(z)
which returns
[ 1 , 0 , -1 ]
18.12: Using Laguerre's Method to Find The Roots of a Polynomial
Syntax pol2zero(p)
18.12.a: Description
Returns a complex column vector that contains the roots of the polynomial corresponding to the real, double-precision or complex column vector p. If
v is a column vector of length n the corresponding polynomial v[x] is
1
v[x] = v
+
v
1
x
2
2
+
v
x
n-1
+ ... + v
3
x
n
If z is the return value, it has one fewer elements than p and p[x] evaluated at x = z(i) is zero for each i.
18.12.b: Example
The roots of the polynomial
2
x
-
1
are -1 and +1. If you enter
p = {-1., 0., 1.}
pol2zero(p)
{
(-1, 0)
(1, 0)
}
{
(1, 0)
(-1, 0)
}
because the order of the roots is not determined.
18.12.c: Exceptions
If the method fails, the return value has type equal to "novalue". This should be a very rare case.
18.13: Computing Chebyshev Polynomial Coefficients
Syntax polcheb( n)
See Also fncheb: 14.11 , fncpole: 14.13 , polval: 18.2 , pol2asc: 18.1
18.13.a: Description
Returns a double-precision column vector containing the Chebyshev polynomial: 26.ac of degree n, where n is an integer scalar.
18.13.b: Example
T = polcheb(2)
pol2asc(T)
returns
-1 + 0 x^1 + 2 x^2
18.14: Remove Leading Zero Coefficients from a Descending Polynomial
Syntax polyreduce(p)
18.14.a: Description
Removes leading coefficients that are near zero from the descending polynomial: 26.f p (thus the resulting descending polynomial is equivalent). A
coefficient is considered near zero if its absolute value is less than or equal to
2
length(p) * eps * max(abs(p))
where eps is machine epsilon: 24.1 (if p is
real, machine epsilon corresponds to single precision, otherwise it corresponds to double precision.) If the
polynomial p is identically zero, the scalar zero with the same type as p is returned.
18.14.b: Example
If you enter
p = [0, 1, 2]
polyreduce(p)
[ 1 , 2 ]
18.15: Convolution of Vectors (Mlmode)
Syntax y = conv(a, b)
18.15.a: Description
Computes the convolution of two integer, real, double-precision or complex vectors a and b. The type of y is the type that results from coercion: 4.4
between the types of a and b. If na is the length of a and nb is the length of b, the return value has length na + nb - 1 and its i-th element is given by
na
--->
---i = 1
a
* B
i
where B
k - i
= <
k - i
/ 0
0
\ b
if k - i < 1
if k - i > nb
otherwise
k-i
This is equivalent to polynomial multiplication: 18.6 .
18.15.b: Example
If in Mlmode: 25 you enter,
a = [ 1 , 1 , 1 , 1,
conv(a, a)
1];
[ 1 , 2 , 3 , 4 , 5 , 4 , 3 , 2 , 1 ]
18.16: Deconvolution or Descending Polynomial Division
Syntax [b, r] = deconv(y, a)
18.16.a: Description
Deconvolution and descending polynomial: 26.f division are equivalent operations. The descending polynomial b is the quotient resulting from
dividing the descending polynomial y by the descending polynomial corresponding a. The descending polynomial r is the remainder of the division;
i.e.,
y[x] = a[x] * b[x] + r
where * denoted multiplication of the corresponding polynomials. From another point of view
y = conv(a, b) + r
where conv: 18.15 denotes convolution.
18.16.b: Example
You can perform the following polynomial division
2
x + 3 x + 2
-----------x + 1
by entering
y
= [1, 3, 2]
a
= [1, 1]
[b, r] = deconv(y, a)
You can print the quotient polynomial which is x + 2 by entering
b
[ 1 , 2 ]
and you can print the remainder by entering
r
0
18.17: Calculate the Residues for a Rational Function in Complex Plane
Syntax
[r,
[r,
p, k] = residue (b, a)
p, k] = residue (b, a, tol)
18.17.a: Description
Calculates the residues for a rational function of a complex variable. (This is also called the partial fraction expansion.) The descending polynomials:
26.f b and a specify the rational function numerator and denominator respectively.
18.17.b: Return Values
The return complex column vectors r, p, and k specify the partial fraction expansion of the rational function in the following fashion:
Name Description
Length
r
residues
M
p
poles
M
k
direct polynomial N
b[z]
---a[z]
M
--= >
--m=1
where for each m, the
p
r
m
------------e(m)
(z - p )
m
exponent e(m) is
N
-->
--n=1
+
N-n
k * z
n
the maximum integer j such
= p
m
m - j + 1
18.17.c: Tolerance
The tolerance value tol is used to determine whether poles with small imaginary components are considered to be real. It is also used to determine if
two poles are distinct. If the ratio of the imaginary part of a pole to the real part is less than tol, the imaginary part is discarded. If two poles are farther
apart than tol they are distinct. If the argument tol is not present, value 0.001 is used.
18.17.d: Example
Consider the case
2
b[s]
s + s + 1
---- = ------------------a[s]
3
2
s - 5 s + 8 s - 4
=
-2
----s - 2
+
7
-------2
(s - 2)
+
3
----s - 1
If you enter
b = [1, 1, 1]
a = [1, -5, 8, -4]
[r, p, k] = residue(b, a)
O-Matrix will calculate the partial fraction expansion above. If you enter
r
{
(-2,0)
(7,0)
(3,0)
}
which are the residue values in the expansion. If you enter
p
{
(2,0)
(2,0)
(1,0)
}
which are the poles in the expansion. If you enter
k
{ }
because the direct term in the expansion is empty.
18.18: Compute the companion matrix corresponding to polynomial
Syntax compan(c)
18.18.a: Description
Returns the companion matrix corresponding to the descending polynomial: 26.f represented by the vector c. The corresponding companion matrix is
given by
_
| -c(2)/c(1)
|
1
|
0
A = |
.
|
.
|
.
|_
0
-c(3)/c(1)
0
1
.
.
.
.
0
...
...
...
.
...
-c(n)/c(1)
0
0
.
.
.
.
1
_
-c(n+1)/c(1) |
0
|
0
|
.
|
.
|
.
|
0
_|
The eigenvalues of the companion matrix are equal to the roots of the polynomial.
18.18.b: Example
If you enter
c = [ 1, 2, 3, 4]
compan(c)
{
[ -2 , -3 , -4 ]
[ 1 , 0 , 0 ]
[ 0 , 1 , 0 ]
}
18.19: Evaluating A Multiple Dimension Monomial And Its Derivatives
Syntax monomial(n, k, p)
18.19.a: Description
Returns the derivative specified by k, of the multiple dimensional monomial specified by n, at the point specified by p. The return value is a column
vector with the same type and row dimension as the integer, real, double-precision or complex matrix p. The j-th element of the return value is the
derivative evaluated at the j-th row of p. The integer row vectors k and n have the same column dimension as p.
The monomial is defined by
n(1)
m(x) = x
* x
1
n(2)
*
2
n(N)
. . . * x
N
where N is the length of the vector n. The vector k specifies the derivative
k(1)
d
------k(1)
d x
k(2)
d
------k(2)
d x
. . .
k(N)
d
------k(N)
d x
m(x)
Hence, if all the elements of k are zero, the derivative is equal to m(x).
18.19.b: Example
Define the monomial
2
m(x)
=
x
3
*
1
x
2
The value of m(x) at the point [1, 2] is 8. We compute this value as follows
n = [2, 3]
k = [0, 0]
p = [1, 2]
monomial(n, k, p)
The partial of m(x) with respect
k = [0, 1]
monomial(n, k, p)
to the second component of x at the point [1, 2] is 12. This can be computed by continuing the previous example with
19: Graphical User Interface Programming
19.a: General Purpose Dialogs
openfile: 19.1 Opening A File Using The System Browser Dialog
savefile: 19.2 Saving A File Using The System Browser Dialog
chfile: 19.6 Dialog For Choosing File Names
input: 19.3 Obtaining A Text String Using The Input Dialog
input1: 19.4 Putting A Prompt In The Input Dialog
input2: 19.5 Entering Passwords In The Input Dialog
errordlg: 19.7 Posting a Dialog With an Error Message
status: 19.8 Displaying Program Status in a Dialog
easydlg: 19.9 An Easy to Use General Purpose Dialog Routine
19.b: Special Purpose Dialogs
See Interactive GUI Tools: 2.11.
19.c: GUI Primitives
Creating A New Dialog Window
controls: 19.21
Creating and Using Controls In a Dialog Window
delwin: 19.22
Deleting A Window
Creating A New Editor Window
geteditor: 19.12
Getting The Contents Of An Editor Window
Creating A New Table Window
gettable: 19.14
Getting The Values In a Table
getcells: 19.15
Determining Which Cells Are Selected In A Table
setcells: 19.16
Changing The Value In Cells Of A Table
guisize: 19.28
Graphical User Interface Size Parameters
getvisible: 19.19
Determining The Current Size Of The O-Matrix Main Window
getscreen: 19.18
Determining The Size Of The Screen In Pixels
windowgeometry: 19.20 Getting and Setting a Window's Geometry
iconify: 19.23
Iconifying A Window
hide: 19.25
Hiding A Window Or Disabling A Control
show: 19.26
Normalizing A Window Or Enabling A Control
caption: 19.27
Setting the O-Matrix Application Caption
isicon: 19.24
Determining If A Window Is Iconified
19.1: Opening A File Using The System Browser Dialog
Syntax openfile
openfile(caption)
openfile(caption,
openfile(caption,
name)
name, description, extension)
19.1.a: Description
Creates a system file browser dialog, in which the user can select a file to open, and returns a character row vector containing the file name selected by
the user. If specified, the following character row vectors affect the state of the file browser: caption is the caption to be used for the file browser;
name is the default file name; description and extension are the default description and file extension in the dialog. The default file extension must be
between 3 and 5 characters and must begin with the characters "*.". Trailing space characters are ignored in all the arguments to openfile.
If the user chooses a valid file name, the return value of openfile is a character row vector containing the name of the file. Otherwise, the return value
is an empty character row vector; that is, it has column dimension equal to 0.
19.1.b: Example
If you enter
caption
= "Example: openfile"
name
= "autoexec.oms"
description = "O-Matrix Files"
extension
= "*.oms"
openfile(caption, name, description, extension)
O-Matrix will display a system browser dialog. If you choose a file in the dialog, O-Matrix will print the name of the file in the command window.
19.2: Saving A File Using The System Browser Dialog
Syntax savefile
savefile(caption)
savefile(caption,
savefile(caption,
name)
name, description, extension)
19.2.a: Description
Creates a system file browser dialog, in which the user can select a file to save, and returns a character row vector containing the file name selected by
the user. If specified, the following character row vectors affect the state of the file browser: caption is the caption to be used for the file browser;
name is the default file name; description and extension are the default description and file extension in the dialog. The default file extension must be
between 3 and 5 characters and must begin with the characters "*.". Trailing space characters are ignored in all the arguments to savefile.
If the user chooses a valid file name, the return value of savefile is a character row vector containing the name of the file. Otherwise, the return value
is an empty character row vector; that is, it has column dimension equal to 0.
19.2.b: Example
If you enter
caption
= "Example: savefile"
name
= "autoexec.oms"
description = "O-Matrix Files"
extension
= "*.oms"
savefile(caption, name, description, extension)
O-Matrix will display a system browser dialog. If you choose a file in the dialog, O-Matrix will print the name of the file in the command window.
19.3: Obtaining A Text String Using The Input Dialog
Syntax input
19.3.a: Description
Displays a dialog in which the user can enter a a line of text that is returned as a character row vector.
Selecting the "Ok" button or the enter key, signals that the text input is complete. Selecting the "Cancel" button, signals that the operation should be
canceled and returns a vector with 0 column dimension. Selecting the "Help" button display this help section.
19.3.b: Example
If you enter
x = input
O-Matrix will display a dialog box with a line available for text input. If you enter the phrase "Hello World!" and then, in the Command window, enter
print x
O-Matrix will respond
Hello World!
19.4: Putting A Prompt In The Input Dialog
Syntax input( prompt)
19.4.a: Description
Displays prompt as the caption of a dialog: 19.3 in which data can be entered from the keyboard, where prompt is a character row vector. The return
value is the text input in the dialog as a character row vector.
19.4.b: Example
If you enter
degrees = input("Enter angle in degrees: ")
radians = atod(degrees) * PI / 180
O-Matrix will display the following dialog box:
If you enter 180 in the dialog box, O-Matrix will respond
19.5: Entering Passwords In The Input Dialog
19.5.a: Description
Displays a dialog: 19.3 in which data can be entered from the keyboard, where characters entered into the dialog are not echoed. The return value is
the text input in the dialog as a character row vector. The character row vector prompt specifies the caption for the dialog.
19.5.b: Example
If you enter
and in the displayed input line enter
MySecretCode
O-Matrix will display the following dialog box:
19.6: Dialog For Choosing File Names
Syntax chfile(caption, default, description, extension)
19.6.a: Description
Displays a browser dialog in which the user chooses a file. This routine differs from the openfile: 19.1 , savefile: 19.2 routines in that the browser will
start in the directory where the default file is located.
The character row vector caption specifies the caption for the dialog. The caption must begin with one of the following words: "Read" , "Load",
"Open", "Write", "Store", or "Save" . The character row vector default specifies the default file name. This name may contain the entire path that
specifies the file from the root directory, or it may specify the file relative to the current directory. If the second character of default is a colon, the first
character in default specifies a disk drive. No other character in default can be a colon. The character row vector description describes the type of files
that the argument extension refers to (for example description might equal "data files"). The character row vector extension specifies a file extension
(for example "*.dat"). The list of files displayed in the dialog is limited to those with this extension.
The return value of chfile is a character row vector containing the name of the file that the user chooses. This is a complete path name including the
disk drive. If the user chooses the Cancel button in the dialog, an empty character row vector is returned; i.e., its column dimension is zero.
19.6.b: Example
If you enter
caption
default
= "\omwin\autoexec.oms"
description = "O-Matrix Source"
extension
= "*.oms"
chfile(caption, default, description, extension)
O-Matrix will display a browser dialog that lists the files in the \omwin
directory that have the mat extension. If you choose a file, its name will be
printed in the command window.
19.6.c: Reference
The extension parameter must begin with the character * followed by the character . and it must contain at least one more character. You can specify
all files by using the extension *.*.
19.7: Posting a Dialog With an Error Message
Syntax errordlg(msg)
errordlg(msg, callback)
errordlg(msg, topic, file)
19.7.a: Description
Posts an error dialog and then halts the currently executing O-Matrix program. This routine never returns and execution will only resume after the user
chooses one of the buttons in the dialog. In addition, all currently open files are closed, and the currently set error trap: 20.6 is cleared. The error
message contained in the character matrix msg is included in the error dialog together with a push button labeled "Ok". When the user chooses "Ok",
the error dialog is dismissed. If the character row vector callback is present, it specifies a call back: 26.a command that is executed after the error
dialog is dismissed. If the character row vectors topic and file are present, a push button labeled "Help" is included in the dialog. If the user chooses
"Help", the help: 20.7 function is called with the corresponding topic and file as arguments.
19.7.b: Easydlg
This routine uses the easydlg function which is documented in its own winhelp file (see File | Help | Easydlg).
19.7.c: Example
If you enter
function DeepCall(arg1, arg2, arg3) begin
narg = arg(0)
if narg <> 3 then begin
msg = ["Only ", ntoa(narg), " arguments to DeepCall"]
errordlg(msg)
end
print arg1, arg2, arg3
end
DeepCall("One", "Two")
O-Matrix will abort execution before the statement
print arg1, arg2, arg3
and post an error dialog with the message
Only 2 arguments to DeepCall
19.8: Displaying Program Status in a Dialog
Syntax include status.oms
CreateStatusDialog(caption,
SetStatusDialog( value,
nr, nc, option)
dt)
DeleteStatusDialog
DeleteStatusDialog(option)
19.8.a: Description
These routines maintain a dialog that displays the current status of an executing program. They must first be loaded with the command
include status.oms
before they can be used.
CreateStatusDialog(caption, nr, nc, option)
Creates a dialog (not modal) that can be used to display a character matrix. The character row vector caption specifies the caption for the dialog. The
integer scalars nr and nc specifies the maximum number of rows and columns in the character matrix that will be displayed in the dialog. The character
row vector option is be either "enable" or "disable". This enables and disables deletion of the dialog (see discussion of DeleteStatusDialog(
option) below). If there already is a status dialog being displayed when the function CreateStatusDialog is called, it is replaced by the new one.
SetStatusDialog(value, dt)
Changes the contents of the status dialog to be the character matrix value. This matrix cannot have more than nr rows or nc columns where nr and nc
correspond to the previous call to the function CreateStatusDialog, If no status dialog is currently being displayed, a call to SetStatusDialog has
no effect. If the time since the previous call to SetStatusDialog is less than the value dt, the dialog is not changed and the call to SetStatusDialog
has no effect. The value dt can be an integer, real or double-precision scalar. This can be used to avoid the status dialog changing so rapidly that the
DeleteStatusDialog(option)
Changes the current setting for the deletion option in the status dialog to option where option is either "enable" or "disable". This enables and
disables deletion of the window using the system caption bar the "Close" button within the dialog or a call to DeleteStatusDialog with not
arguments present. Note that if the user chooses a button in a dialog while O-Matrix is running, a beep will sound automatically so option should
probably be "disable" while the program is running.
DeleteStatusDialog
Deletes the status window if the current option setting is "enable", otherwise it generates a beep. If no status dialog is currently being displayed, this
call has no effect.
19.8.b: Example
The following example displays a status dialog in which a for loop index is updated once per second.
clear
include status.oms
caption = "Program Status"
nr
= 5
nc
= 50
option = "disable"
CreateStatusDialog(caption, nr, nc, option)
for index = 1 to 100000 begin
line1 = "Use the red hand or wait for execution to stop"
line2 =
[ ...
"Enter the command: DeleteStatusDialog(", ...
dquote("enable"), ...
")" ...
]
line3 = "Select the Close button"
line5 = [ ...
"For loop index: ", ...
ntoa(index) ...
]
value = {line1, line2, line3, "", line5}
dt
= 1
SetStatusDialog(value, dt)
end
19.9: An Easy to Use General Purpose Dialog Routine
Syntax easydlg(caption, buttons): 19.9.1
easydlg(caption, buttons, message): 19.9.2
easydlg(caption, buttons, message, layout): 19.9.3
easydlg(caption, buttons, message, layout, connection): 19.9.4
easydlg(name): 19.9.5
easydlg(option): 19.9.5
19.9.a: Description
The easydlg function is a general purpose routine for simplifying the construction of graphical user interface applications in O-Matrix. Normally, the
programmer must determine the size and position of the controls of a dialog. When using easydlg, the geometry.: 26.s of the dialog and the position
and size of controls within the dialog are computed automatically. In addition, easydlg automates the definition and use of call backs: 26.a .
19.9.b: Modal Dialogs
Dialogs displayed by easydlg are always modal. When your application displays a modal dialog box, the you cannot switch between the dialog box
and another window that has been displayed by O-Matrix. The you must explicitly end the dialog box by clicking one of the buttons defined in the
buttons argument to easydlg.
19.9.c: Call back Function
With easydlg when the user selects one of the buttons specified by buttons, a function whose name corresponds to caption is called and the dialog is
dismissed.
19.9.d: Contents
Easy Dialog Caption and Button Arguments: 19.9.1
Easy Dialog Message Argument: 19.9.2
Easy Dialog Layout Argument: 19.9.3
Easy Dialog Connection Argument: 19.9.4
Easy Dialog First Argument: 19.9.5
A Complex Easy Dialog Example: 19.9.6
19.9.1: Easy Dialog Caption and Button Arguments
Syntax easydlg( caption, buttons)
19.9.1.a: Caption
The caption argument is a character row vector that specifies the caption for the dialog and the name of the call back: 26.a function that is called when
the dialog is dismissed. The dialog caption includes all the characters up to but not including the first under bar in caption. The call back function
name includes all the characters in caption but characters other than letters and decimal digits are converted to under bars. (If the first character in
caption is a decimal digit, it is also converted to an under bar.)
19.9.1.b: Buttons
The buttons argument is a character matrix with each row specifying the name of a button within the dialog. The dialog is dismissed and the call back
function is called when any button within the dialog is selected (see easydlg(options): 19.9.5.1 for an exception to this rule). The call back function has
one argument which is set equal to the name of the button that is chosen.
19.9.1.c: Program
clear
caption = "Buttons_callback"
buttons = {"Ok", "Cancel"}
easydlg(caption, buttons)
function Buttons_callback(button) begin
print "button =", button
end
19.9.1.d: Example
If you paste the program above into the command line, the following dialog will be displayed:
If you then select the Cancel button, the function Buttons_callback will be called and it will print the text
button = Cancel
in the Command window.
19.9.2: Easy Dialog Message Argument
Syntax easydlg( caption, buttons, message)
19.9.2.a: Message
The message argument is a character matrix specifying a message to be placed in the dialog. Each row of the matrix corresponds to a new line in the
message and all the lines start at the same horizontal position. If message is not present, or if it is equal to the empty string "", no message is
displayed.
19.9.2.b: Program
clear
caption = "Message_callback"
buttons = { "Continue", "Cancel"}
message = { ...
"the data will be over written" ...
}
easydlg(caption, buttons, message)
function Message_callback(button) begin
print "button =", button
end
19.9.2.c: Example
If you paste the program above into the command line, the following dialog will be displayed:
If you then select the Continue button, the function Message_callback will be called and it will print the text
button = Continue
in the Command window.
19.9.3: Easy Dialog Layout Argument
Syntax easydlg( caption, buttons, message, layout)
19.9.3.a: Description
The layout argument is a character matrix that specifies the initial value and position of fields where the user can input information into the dialog.
Each row of layout corresponds to a line in the dialog and contains the information for one or two fields. If a row of layout contains a semicolon, the
semicolon separates the information for two fields which are placed in the left and right columns of the dialog. If a row of layout does not contain a
semicolon, the row contains information for one field which is placed in the center column of the dialog. Each field must contain a type, name, width,
and setting which are described below.
19.9.3.b: Field Type
The first piece of information for a field is its type. It is terminated by a comma and must be one of the following:
"textfield"
"label"
"checkbox"
"slider"
"spinbox"
"labelbutton"
"textbutton"
Each of the options is described in the corresponding section listed below:
textfield
Easy Dialog Text Fields: 19.9.3.1
label
Easy Dialog Label Fields: 19.9.3.2
checkbox
Easy Dialog Check Box Fields: 19.9.3.3
Easy Dialog Popup Menu Fields: 19.9.3.4
slider
Easy Dialog Slider Fields: 19.9.3.5
spinbox
Easy Dialog Spinbox Fields: 19.9.3.6
labelbutton Easy Dialog Label Button Fields: 19.9.3.7
textbutton Easy Dialog Text Button Fields: 19.9.3.8
19.9.3.c: Field Name
The second piece of information for a field is its name. It is terminated by a comma and can be any sequence of characters not including a semicolon
or comma. The value of a dialog field can be retrieved using this name: 19.9.5 .
19.9.3.d: Field Width
The third piece of information for a field is a positive integer that specifies its width. It is terminated by a comma. The value of width specifies the
number of characters that the field can display where each character is assumed to have the same width as the character A.
19.9.3.e: Field Setting
The fourth piece of information for a field is its setting. Each field type has its own section in the help file and the corresponding meaning of the field
setting is specified there.
19.9.3.f: Obtaining Field Values
After the dialog is dismissed the field values can be obtained by calling easydlg(name): 19.9.5 where name is equal to the name of the field. The return
value is a character row vector equal to the current value of the field.
19.9.3.1: Easy Dialog Text Fields
Syntax easydlg( caption, buttons, message, layout)
19.9.3.1.a: Description
If a field type: 19.9.3.b in the layout argument is "textfield", the corresponding field setting: 19.9.3.e is the initial value for the field. This setting
can be any sequence of characters not containing a semicolon.
19.9.3.1.b: Program
clear
caption = "Textfield_callback"
buttons = {"Ok", "Cancel"}
message = "Save study to the specified file"
layout = "textfield, File, 15, lib\easydlg.oms"
easydlg(caption, buttons, message, layout)
function Textfield_callback(button) begin
print "button =", button
print "File
=", easydlg("File")
end
19.9.3.1.c: Example
If you paste the program above into the command line, the following dialog will be displayed:
If you change the text field value to lib\easydlg.dat and then select the Ok button, the function Textfield_callback will be called and it will
print the text
button = Ok
File
= lib\easydlg.dat
in the Command window.
19.9.3.2: Easy Dialog Label Fields
Syntax easydlg( caption, buttons, message, layout)
19.9.3.2.a: Description
If a field type: 19.9.3.b in the layout argument is "label", the corresponding field setting: 19.9.3.e is the initial value for the field. This setting can be
any sequence of characters not containing a semicolon.
19.9.3.2.b: Program
clear
caption = "Label_callback"
buttons = {"Ok", "Cancel"}
message = "Save study to the specified file"
layout = "label, File, 15, lib\easydlg.oms"
easydlg(caption, buttons, message, layout)
function Label_callback(button) begin
print "button =", button
end
19.9.3.2.c: Example
If you paste the program above into the command line, the following dialog will be displayed:
If you then select the Cancel button, the function Label_callback will be called and it will print the text
button = Cancel
in the Command window.
19.9.3.3: Easy Dialog Check Box Fields
Syntax easydlg( caption, buttons, message, layout)
19.9.3.3.a: Description
If a field type: 19.9.3.b in the layout argument is "checkbox", the corresponding field setting: 19.9.3.e the field setting is the initial value for the field.
It can be either "true" or "false" depending on whether the box has a check or not. If the user selects the check box, the value of this field will
change.
19.9.3.3.b: Program
clear
caption = "Checkbox_callback"
buttons = {"Ok", "Cancel"}
message = "Save program as the specified file."
layout = { ...
"label, File:, 15, lib\easydlg.mat", ...
"checkbox, Binary, 2, false" ...
}
easydlg(caption, buttons, message, layout)
function Checkbox_callback(button) begin
print "button =", button
print "Binary =", easydlg("Binary")
end
19.9.3.3.c: Example
If you paste the program above into the command line, the following dialog will be displayed:
If you select the check box so that it is checked, and then select the Ok button, the function Checkbox_callback will be called and it will print the text
button = Ok
Binary = true
in the Command window.
19.9.3.4: Easy Dialog Popup Menu Fields
Syntax easydlg( caption, buttons, message, layout)
19.9.3.4.a: Description
If a field type: 19.9.3.b in the layout argument is "popupmenu", the corresponding field setting: 19.9.3.e contains the initial value for the field followed
by the list of values that will be in the popup menu. Each of the values is separated by a comma.
19.9.3.4.b: Program
clear
buttons = {"Ok", "Cancel"}
message = "Save program as the specified file."
setting = "binary, ascii, binary"
layout = { ...
"label, File:, 15, lib\easydlg.mat", ...
}
easydlg(caption, buttons, message, layout)
print "button =", button
print "Format =", easydlg("Format")
end
19.9.3.4.c: Example
If you paste the program above into the command line, the following dialog will be displayed:
If you select the popup menu, choose ascii, and then select the Ok button, the function Popup_Menu will be called and it will print the text
button = Ok
Format = ascii
in the Command window.
19.9.3.5: Easy Dialog Slider Fields
Syntax easydlg( caption, buttons, message, layout)
19.9.3.5.a: Description
If a field type: 19.9.3.b in the layout argument is "slider", the corresponding field setting: 19.9.3.e contains the lower limit, current value, and upper
limit for the field. Each of the values is separated by a comma. The field width must be greater than or equal to the maximum number of characters in
the lower and upper limit, plus two.
19.9.3.5.b: Program
clear
caption = "Slider_callback"
buttons = {"Ok", "Cancel"}
message = { ...
"The time required is proportional to", ...
"the maximum number of iterations." ...
}
layout = "slider, max itr:, 20, 1, 5, 20"
easydlg(caption, buttons, message, layout)
function Slider_callback(button) begin
print "button =", button
print "max itr: =", easydlg("max itr:")
end
19.9.3.5.c: Example
If you paste the program above into the command line, the following dialog will be displayed:
If you change the slider value to 10, and then select the Ok button, the function Slider_callback will be called and it will print the text
button = Ok
max itr = 10
in the Command window.
19.9.3.6: Easy Dialog Spinbox Fields
Syntax easydlg( caption, buttons, message, layout)
19.9.3.6.a: Description
If a field type: 19.9.3.b in the layout argument is "spinbox", the corresponding field setting: 19.9.3.e contains the lower limit, current value, and upper
limit for the field. Each of the values is separated by a comma. The field width must be greater than or equal to the maximum number of characters in
the lower and upper limit, plus two.
19.9.3.6.b: Program
clear
caption = "Spinbox_callback"
buttons = {"Ok", "Cancel"}
message = { ...
"The time required is proportional to", ...
"the maximum number of iterations." ...
}
layout = "spinbox, max_itr:, 5, 1, 5, 20"
easydlg(caption, buttons, message, layout)
function Spinbox_callback(button) begin
print "button =", button
print "max_itr: =", easydlg("max_itr:")
end
19.9.3.6.c: Example
If you paste the program above into the command line, the following dialog will be displayed:
If you change the spinbox value to 10, and then select the Ok button, the function Spinbox_callback will be called and it will print the text
button = Ok
max itr = 10
in the Command window.
19.9.3.7: Easy Dialog Label Button Fields
Syntax easydlg( caption, buttons, message, layout)
19.9.3.7.a: Description
If a field type: 19.9.3.b in the layout argument is "labelbutton", the corresponding field setting: 19.9.3.e is the value for the field. It can be any
sequence of characters not containing a semicolon. The user will be not be able to change this value directly but the button for the value may lead to a
sequence of operations that does change the value.
19.9.3.7.b: Program
clear
File
= "temp.oms"
caption = "Label Button"
buttons = {"Ok", "Cancel"}
message = "Read the specified file"
layout = ["labelbutton, File, 15,", File]
easydlg(caption, buttons, message, layout)
function Label_Button(button) begin
global File
print "button =", button
print "File
=", File
if button == "Ok" then return
if button == "Cancel" then return
File = openfile(caption, File)
print "File
=", File
end
19.9.3.7.c: Example
If you paste the program above into the command line, the following dialog will be displayed:
If you then select the File button, the function Label_Button will be called and it will print the text
button = File
File
= temp.mat
in the Command window. The program will then display the system dialog that is used for selecting files. If you then select the autoexec.oms file in
the c:\omwin directory the following text will print in the Command window:
File
= c:\omwin\autoexec.oms
19.9.3.8: Easy Dialog Text Button Fields
Syntax easydlg( caption, buttons, message, layout)
19.9.3.8.a: Description
If a field type: 19.9.3.b in the layout argument is "textbutton", the corresponding field setting: 19.9.3.e is the value for the field. It can be any
sequence of characters not containing a semicolon. The user may change this value directly or use the button for the value to lead to a sequence of
operations that changes the value.
19.9.3.8.b: Program
clear
File
= "temp.oms"
caption = "Text Button"
buttons = {"Ok", "Cancel"}
message = "Read the specified file"
layout = ["textbutton, File, 15,", File]
easydlg(caption, buttons, message, layout)
function Text_Button(button) begin
global File
print "button =", button
print "File
=", File
if button == "Ok" then return
if button == "Cancel" then return
File = openfile(caption, File)
print "File
=", File
end
19.9.3.8.c: Example
If you paste the program above into the command line, the following dialog will be displayed:
If you change the file value to junk.mat and then select the File button, the function Text_Button will be called and it will print the text
button = File
File
= junk.mat
in the command window. The program will then display the system dialog that is used to select file. If you then select the autoexec.oms file in the
c:\omwin directory, the following text will print in the Command window:
File
= c:\omwin\autoexec.oms
19.9.4: Easy Dialog Connection Argument
Syntax easydlg( caption, buttons, message, layout, connection)
19.9.4.a: Description
The connection argument is a character matrix that specifies relationships between fields in the dialog. Each row of connection and consists of a
connection type followed by a list of field names.
19.9.4.b: Connection Type
The first piece of information in an connection is its type. It is terminated by a comma and must be one of the following:
"enable"
"disable"
Each of the options is described in the corresponding section listed below:
enable Enable Easy Dialog Fields on True: 19.9.4.1
disable Disable Easy Dialog Fields on True: 19.9.4.2
19.9.4.1: Enable Easy Dialog Fields on True
Syntax easydlg( caption, buttons, message, layout, connection)
19.9.4.1.a: Enable Connections
If a row of the connection argument begins with "enable", it specifies an enable connection. A row corresponding to an enable connection has the
form:
enable, FC, F1, F2, ...
where FC denotes the name of a check box and F1, F2, ..., denote the names corresponding to other fields in the dialog. If the field that is named
FC, is true, the fields named F1, F2, ..., are input enabled. Otherwise, the fields named F1, F2, ..., are input disabled; i.e., they are grayed out and
the user cannot change their values.
19.9.4.1.b: Program
clear
cap = "Enable_callback"
but = {"Ok", "Cancel"}
msg = "Choose axis scaling"
lay = { ...
"checkbox, manual, 2, false", ...
"textfield, min, 5, 0", ...
"textfield, max, 5, 0" ...
}
connection = "enable, manual, min, max"
easydlg( cap, but, msg, lay, connection)
function Enable_callback(button) begin
print "button =", button
print "min
=", easydlg("min")
print "max
=", easydlg("max")
end
19.9.4.1.c: Example
If you paste the program above into the command line, the following dialog will be displayed:
Note that the values in the min and max fields are grayed out and cannot be changed. If you set the manual field to true by selecting it, the min and max
fields will be enabled. If you then set the field named max to 10 and select the Ok button, the following text will print in the Command window:
button =", Ok
min
=", 0
max
=", 10
19.9.4.2: Disable Easy Dialog Fields on True
Syntax easydlg( caption, buttons, message, layout, connection)
19.9.4.2.a: Disable Connections
If a row of the connection argument begins with "disable", it specifies an disable connection. A row corresponding to a disable connection has the
form:
disable, FC, F1, F2, ...
where FC denotes the name of a check box and F1, F2, ..., denote the names corresponding to other fields in the dialog. If the field that is named
FC, is true, the fields named F1, F2, ..., are input disabled. Otherwise, the fields named F1, F2, ..., are input enabled; i.e., they are grayed out and
the user cannot change their values.
19.9.4.2.b: Program
clear
cap = "Disable_callback"
but = {"Ok", "Cancel"}
msg = "Choose axis scaling"
lay = { ...
"checkbox, manual, 2, false", ...
"textfield, min, 5, 0", ...
"textfield, max, 5, 0" ...
}
connection = "disable, auto, min, max"
easydlg( cap, but, msg, lay, connection)
function Disable_callback(button) begin
print "button =", button
print "min
=", easydlg("min")
print "max
=", easydlg("max")
end
19.9.4.2.c: Example
If you paste the program above into the command line, the following dialog will be displayed:
If you set the auto field to true by selecting it, the min and max fields will be disabled and you will not be able to change their values. If you then select
the Ok button, the following text will print in the Command window:
button =", Ok
min
=", 0
max
=", 0
Syntax easydlg( caption, buttons, message, layout, connection)
19.9.4.3.a: Disable Connections
If a row of the connection argument begins with "radio", the row specifies a radio connection. A row corresponding to a radio connection has the
form:
where F1, F2, ..., denote the names corresponding to fields: 19.9.3.b in the dialog. One and only one of the check boxes in the connection is true. If
one of the false boxes is selected, it is set to true and the others are set to false. If the true box is selected, no change occurs.
19.9.4.3.b: Program
clear
cap =
but =
msg =
lay =
{"Ok", "Cancel"}
"Choose an integration method."
{ ...
"checkbox, Runge, 2, true", ...
"checkbox, Gear, 2, false", ...
}
easydlg( cap, but, msg, lay, connection)
print "button =", button
print "Runge =", easydlg("Runge")
print "Gear
=", easydlg("Gear")
end
19.9.4.3.c: Example
If you paste the program above into the command line, the following dialog will be displayed:
If you select the Gear field and then press the Ok button, the following text will print in the Command window:
button
Runge
Gear
=", Ok
= false
= true
= false"
19.9.5: Easy Dialog First Argument
Syntax easydlg( name)
easydlg( option)
19.9.5.a: Name
If there is only one argument to easydlg it must be a character row vector. If it does not contain a comma character, it specifies a name argument. The
value of the corresponding field in the dialog that was created by the previous call to easydlg with more than one argument. It is returned as a a
character row vector with leading and trailing spaces deleted. (See Easy Dialog Layout Argument: 19.9.3 for a description of easydlg fields and field
names.)
19.9.5.b: Option
If there is only one argument to easydlg and it must does contain a comma character, it specifies a option argument. The valid options are:
Type
Description
Easy Dialog Dismiss Option: 19.9.5.1
Easy Dialog Enable Option: 19.9.5.2
disable Easy Dialog Disable Option: 19.9.5.3
setvalue Easy Dialog Setvalue Option: 19.9.5.4
dismiss
enable
These options affect the dialog which was created by the previous call to easydlg with more than one argument, and which is assumed to be currently
displayed.
19.9.5.1: Easy Dialog Dismiss Option
Syntax easydlg( option)
19.9.5.1.a: Description
If there is only one argument to easydlg, and it begins with the text
"dismiss, "
it is an Dismiss option. This option has the following form
"dismiss, button1, button2, ...
where button1, button2, ... are the names of buttons in the currently displayed dialog (which was created by easydlg). Normally a dialog created by
easydlg is dismissed when any of the buttons is chosen. The result of this option is to only dismiss the dialog if one of the specified buttons is chosen.
19.9.5.1.b: Program
clear
caption = "Dismiss Option"
buttons = {"Go", "Done"}
message = "Read the specified file."
layout = ...
"textfield, File, 12, \omwin\temp.dat"
easydlg(caption, buttons, message, layout)
easydlg("dismiss, Done")
function Dismiss_Option(button) begin
print "button =", button
print "File
=", easydlg("File")
end
19.9.5.1.c: Example
If you paste the program above into the command line, the following dialog will be displayed:
If you then select the Ok button, the dialog will remain on the screen, the function Disable_Option will be called and it will print the text
button = Go
File
= \omwin\temp.dat
in the Command window. If you select the Exit button, the dialog will be dismissed from the screen, the function Disable_Option will be called and
it will print the text
button = Done
File
= \omwin\temp.dat
in the Command window.
19.9.5.2: Easy Dialog Enable Option
Syntax easydlg( option)
If there is only one argument to easydlg, and it begins with the text
"enable, "
it is an Enable option. This option has the following form
enable, name1, name2, ...
where name1, name2, ... are the names of fields in the currently displayed dialog (which was created by easydlg). The result of this option is to
enable user input to each of the specified fields.
19.9.5.2.a: Program
clear
caption = "Enable Option"
buttons = {"Go", "Exit"}
message = "Select Go to enable Binary field."
layout = { ...
"textfield, File, 12, \omwin\temp.dat", ...
"checkbox, Binary, 2, false" ...
}
easydlg(caption, buttons, message, layout)
easydlg("dismiss, Exit")
easydlg("disable, Binary")
function Enable_Option(button) begin
print "button =", button
print "File
=", easydlg("File")
print "Binary =", easydlg("Binary")
if button <> "Exit" then ...
easydlg("enable, Binary")
end
19.9.5.2.b: Example
If you paste the program above into the command line, the following dialog will be displayed:
Note that the word Binary is grey and you cannot change the value of the check box. If you then select the Go button, the function Enable_Option
will be called and it will print the text
button = Ok
File
= \omwin\temp.dat
Binary = false
in the Command window. In addition the dialog will stay on the screen and Binary field will be enabled (because of the Enable option within the call
back function). You can now change the check box to be set and select the Exit button. The dialog will then be dismissed and the text
button = Ok
File
= \omwin\temp.dat
Binary = true
will be printed in the Command window.
19.9.5.3: Easy Dialog Disable Option
Syntax easydlg( option)
If there is only one argument to easydlg, and it begins with the text
"disable, "
it is an Disable option. This option has the following form
disable, name1, name2, ...
where name1, name2, ... are the names of fields in the currently displayed dialog (which was created by easydlg). The result of this option is to
disable user input to each of the specified fields.
19.9.5.3.a: Program
clear
caption = "Disable Option"
buttons = {"Ok", "Cancel"}
message = "Read the specified file."
layout = { ...
"textfield, File, 12, \omwin\temp.dat", ...
"checkbox, Binary, 2, false" ...
}
easydlg(caption, buttons, message, layout)
easydlg("disable, Binary")
function Disable_Option(button) begin
print "button =", button
print "File
=", easydlg("File")
print "Binary =", easydlg("Binary")
end
19.9.5.3.b: Example
If you paste the program above into the command line, the following dialog will be displayed:
Note that Binary is grey and you cannot change the value of the check box. If you then select the Ok button, the function Disable_Option will be
called and it will print the text
button = Ok
File
= \omwin\temp.dat
Binary = false
in the Command window.
19.9.5.4: Easy Dialog Setvalue Option
Syntax easydlg( option)
If there is only one argument to easydlg, and it begins with the text
"setvalue, "
it is an Setvalue option. This option has the following syntax
setvalue, name, value
where name is the name: 19.9.3.c of a field in the currently displayed dialog (which was created by easydlg). The result of this option is to set the
value currently in the specified field. If the field type: 19.9.3.b is checkbox , value is either true or false. If the field type is popupmenu, value is the
new menu (without specifying its initial setting). The entries in the menu are separated by commas. If the field type is slider or spinbox, value is an
integer between the field limits. If the field type is textfield, textbutton, labelfield, or labelbutton, value is any sequence of characters.
19.9.5.4.a: Program
clear
caption = "Setvalue Option"
buttons = {"Go", "Exit"}
message = { ...
"Count increments each time", ...
"you select the Go Option" ...
}
layout = { ...
"textfield, File, 12, \omwin\temp.dat", ...
"slider, Count, 12, 1, 1, 10" ...
}
easydlg(caption, buttons, message, layout)
easydlg("dismiss, Exit")
function Setvalue_Option(button) begin
print "button =", button
count = easydlg("Count")
print "Count =", count
if button == "Exit" then return
#
count = int(atod(count))
if count < 10 then count = count + 1
count = ntoa(count)
easydlg(["setvalue, Count,", count])
end
19.9.5.4.b: Example
If you paste the program above into the command line, the following dialog will be displayed:
If you then select the Go button, the function Setvalue_Option will be called and it will print the text
button = Go
Count = 1
in the Command window. In addition the dialog will stay on the screen and the value of the Count field will be changed to two. If you select the Exit
button, the dialog will be dismissed, the function Setvalue_Option will be called, and it will print the text
button = Exit
Count = 2
in the Command window.
19.9.6: A Complex Easy Dialog Example
19.9.6.a: Description
This example combines various controls in one dialog.
19.9.6.b: Program
# Initialize O-Matrix
clear
#
# the dialog caption
cap = "Campus Commuter Form"
#
# one button in dialog
buttons = "Done"
#
#
msg = " "
#
# layout for the Name field
name = "textfield, Name, 10, Jane Doe"
#
# popup menu for the Mail field
#
# layout for the Mail field
#
# layout for the Student, Faculty and Staff fields
position = { ...
"checkbox, Student, 2, true", ...
"checkbox, Faculty, 2, false", ...
"checkbox, Staff,
2, false" ...
}
#
# layout for the Day fields
day = { ...
"checkbox, Monday,
2, false", ...
"checkbox, Tuesday,
2, false", ...
"checkbox, Wednesday, 2, false", ...
"checkbox, Thursday, 2, false", ...
"checkbox, Friday,
2, false" ...
}
#
# layout for the Distance field
dis = "slider, Commute Distance, 20, 1, 1, 50"
#
# fields that are split left and right
layout = [ ...
{name, mail, position}, ... fields on left side of dialog
fill(";", 5, 1), ...
separator between fields
day ...
fields on right side of dialog
]
#
# Distance field is centered at the bottom
layout = {layout, dis}
#
# make Student, Faculty, Staff fields a set of radio buttons
connections = "radio, Student, Faculty, Staff"
#
# display the dialog
easydlg(cap, buttons, msg, layout, connections)
#
# call back function
function Campus_Commuter_Form(button) begin
# list of field names
Name = { ...
"Name", ...
"Mail", ...
"Student", ...
"Faculty", ...
"Staff", ...
"Monday", ...
"Tuesday", ...
"Wednesday", ...
"Thursday", ...
"Friday", ...
"Commute Distance" ...
}
# get the value for each field
for i = 1 to rowdim(Name) begin
name = Name.row(i)
print name, "=", easydlg(name)
end
end
19.9.6.c: Example
If you paste the program above into the command line, the following dialog will be displayed:
The value of all the fields will be displayed in the Command window when you select the "Done" button.
19.10.a: Description
Adds the item specified by the character row vector item to the "Tools" menu. If the character row vector parent is "Tools", the item that is created in
the "Tools" menu. Otherwise, parent must match a drag right item that was previously specified. In this case, the new item is added to the list of for
the specified parent.
If a call back: 26.a command is specified, the corresponding command is executed when the menu item is selected. If call back is not present, item
specifies a draw right menu item that can be the parent of other menu items.
19.10.b: Example
submenu. If after executing this program, you select Tools | Beep | 5 times, O-Matrix will beep five times.
clear
parent
= "Tools"
item
= "Beep"
callback = "beep;"
parent
= "Beep"
item
= "5 times"
callback = "Beep(5)"
function Beep(n) begin
for i = 1 to n begin
beep;
sleep(1)
end
end
19.11: Creating A New Editor Window
Syntax addeditor( caption, geometry, call back, data)
addeditor( caption, geometry, call back, data, style)
19.11.a: Description
Creates an editor window with the specified caption: 26.b and geometry: 26.s within the main O-Matrix window. If the value of geometry is novalue:
6.3.16 the new window is sized and positioned automatically by the system. The command specified by call back: 26.a is executed when the user
attempts to close the editor from the caption bar. O-Matrix does not automatically close the editor in this case and the call back command should do so
if that is appropriate. The character row vector data specifies the text to place in the editor when it is created. The character row vector style must have
the value "normal" or "iconic". If style is "normal", the editor is initially displayed in normal mode; if style is "iconic", the editor is initially displayed
as an icon but will have the specified geometry when normalized.
Editors created with this command can be saved using the O-Matrix menu commands "File | Save" and "File | Save As," but the caption does not
change to reflect the specified file name. When the edit window is closed, the user is not automatically prompted to save the text contained within the
editor (even if the editor's contents have been saved to a file previously).
19.11.b: Example
The following program reads the file c:\omwin\autoexec.oms into a character row vector. It then creates an editor window that initially contains the
contents of the file. The contents of the editor are printed in the Command window when the editor is deleted from its caption bar. (Warning: if you
change the contents of this editor window and then use File | Save, you will change you autoexec: 24.1 file.)
clear
#
file
= "c:\omwin\autoexec.oms"
enough
= 10000
data
= fill(" ", 1, enough)
idata
= 1
for i = 1 to nrows(file) begin
line
nc
= coldim(line)
data.col(idata, nc) = line
idata
= idata + nc + 1
data(idata - 1)
= NEW_LINE
end
data
= data.col(1, idata - 1)
#
caption = "Example Editor"
geometry = [100, 100, 400, 400]
callback = "Done"
#
function Done() begin
global caption
data = geteditor(caption)
write("screen", data)
delwin(caption);
end
19.12: Getting The Contents Of An Editor Window
Syntax geteditor( caption)
19.12.a: Description
Returns a character row vector containing the text currently in the editor window specified by caption: 26.b , where caption is a character row vector.
The new line character (ASCII: 24.3 code 10) is used to separate lines in the return value. The editor window must have been created using the
19.12.b: Example
The following program creates an empty editor window. If you enter information in it and then delete it by using its caption bar, the information will
be printed in the command window.
clear
#
data
= fill(" ", 1, 0)
caption = "Example: geteditor"
geometry = [100, 100, 400, 400]
callback = "Done"
#
function Done() begin
global caption
data = geteditor(caption)
write("screen", data)
delwin(caption);
end
19.13: Creating A New Table Window
Syntax addtable(caption, geometry, call back, ...
data, column labels, row labels, style)
data, column labels, row labels, style, field width)
19.13.a: Description
Creates a spread sheet style table window with the specified caption: 26.b and geometry: 26.s within the main O-Matrix window. If the value of
geometry is novalue: 6.3.16 the new window is sized and positioned automatically by the system. The command specified by call back: 26.a is
executed when the user attempts to close the editor from the caption bar. O-Matrix does not automatically close the table in this case and the call back
command should do so if that is appropriate. The integer, real, or double-precision matrix data contains the data that is initially in the table. The
number of rows and columns in the table is set to the number of rows and columns in data. The character matrix column labels specifies the column
labels for the table. The number of rows in column labels must equal the number of columns in data unless column labels is novalue: 6.3.16 , in which
case no column labels are used. The character matrix row labels specifies the row labels for the table. The number of rows in row labels must equal the
number of rows in data unless row labels is novalue: 6.3.16 , in which case no row labels are used. The character row vector style must have the value
"normal" or "iconic". If style is "normal", the table is initially displayed in normal mode; if style is "iconic", the table is initially displayed as an icon
but will have the specified geometry when normalized.
If data is a character matrix, the integer scalar field width must be used to specify the number of characters to place in each cell of the table. This
number value must divide evenly (i.e., without a remainder) into the number of columns in data. If data is not a character matrix, the current format:
8.17.1 setting for the type of data is used to display the values in the table.
All entries are right justified in the corresponding cell of the table. The average character width and number of characters is used to determine the
width of the columns of the table. If an entry or label does not fit in its cell, leading spaces can be used to make the cell wider.
19.13.b: Example
The following program creates a table with the values of x in the first column and the values of y in the second column. The table can be deleted using
the control on the caption bar.
clear
x
= real(seq(10))
y
= 1. / x
caption
= "Example Table"
geometry
= [100, 100, 200, 400]
callBack
= "delwin(caption);"
data
= [x, y]
columnLabels = {"x", "y"}
rowLabels
= novalue
style
= "normal"
format real "f10.5"
data, columnLabels, rowLabels, style)
19.14: Getting The Values In a Table
Syntax gettable(caption)
19.14.a: Description
Returns the values in the table with the specified caption: 26.b , where caption is a character row vector. If the table was created: 19.13 using character
data, the return value is a character matrix, otherwise the return value is double-precision.
19.14.b: Example
If you enter
caption
= "My Table"
geometry
= [100, 100, 200, 120]
callback
= "delwin(caption);"
data
= seq(3) * seq(2)'
columnLabels = novalue
rowLabels
= novalue
style
= "normal"
data, columnLabels, rowLabels, style)
O-Matrix will create a table window with two columns and three rows. You can use the mouse to select a cells in the table and use the keyboard to
enter new values. If you then enter
gettable(caption)
O-Matrix will print the values currently in the table You can delete the table window from its caption bar or by entering
delwin(caption);
19.15: Determining Which Cells Are Selected In A Table
Syntax getcells(caption)
19.15.a: Description
Returns a four-element integer row vector that specifies the currently selected block of cells in the table specified by the character row vector caption.
The returned vector has the same structure as the .blk: 7.6 operator; that is, [row start, column start, number of rows, number of columns]
19.15.b: Example
If you enter
caption
= "My Table"
geometry
= [100, 100, 200, 120]
callback
= "delwin(caption);"
data
= seq(3) * seq(2)'
columnLabels = novalue
rowLabels
= novalue
style
= "normal"
data, columnLabels, rowLabels, style)
O-Matrix will create a table window with two columns and three rows. If you then use the mouse to highlight the first column and at the command line
you enter
getcells(caption)
[ 1
, 1 , 3 , 1 ]
You can delete the table window from its caption bar or by entering
delwin(caption);
19.16: Changing The Value In Cells Of A Table
Syntax setcells(caption, cell, data)
19.16.a: Description
Changes the values of a block of cells in the table specified by the character row vector caption. The input value data is an integer, real, or doubleprecision matrix, or character row vector specifying the values to place in the table.
The two-element integer row vector cell indicates the starting row and column at which data is to be changed. Table rows are numbered from 1 to m,
where m is the number or rows in the table and 1 represents the top row of the table. Table columns are numbered from 1 to n, where n is the number of
columns in the table and 1 represents the left most column of the table.
19.16.b: Example
If you enter
caption
= "My Table"
geometry
= [100, 100, 200, 130]
callback
= "delwin(caption);"
data
= seq(3) * seq(2)'
columnLabels = novalue
rowLabels
= novalue
style
= "normal"
data, columnLabels, rowLabels, style)
O-Matrix will create the following table window:
If you then enter the command
data = {7, 8, 9}
cell = [1, 2]
setcells(caption, cell, data)
O-Matrix will change the table to look like this
You can delete the table window from its caption bar or by entering
delwin(caption);
19.17: Creating A New Dialog Window
Syntax adddialog( caption, geometry, call back)
adddialog( caption, geometry, call back, style)
19.17.a: Description
Creates a dialog window with the specified caption: 26.b and geometry: 26.s within the main O-Matrix window. The command specified by call back:
26.a is executed when the user attempts to close the dialog from the caption bar. O-Matrix does not automatically close the dialog in this case and the
call back command should do so if that is appropriate.
The character row vector style must be "normal", "centered", "iconic", "maximized", or "modal". If style is "centered", the dialog is created with the
width and height specified by geometry but its position is determined by centering it within the main O-Matrix window. If style is "iconic", the dialog
is initially displayed as an icon and it will have the specified geometry when it is normalized. If style is "maximized", the dialog is initially displayed
in full-screen mode and it will have the specified geometry when it is normalized. If style is "modal", the dialog is created as a modal window; that is,
input is only accepted by this dialog window; the other O-Matrix input window are re-enabled when the modal dialog is deleted. If style is not present,
or if it is "normal", the dialog is displayed with the specified geometry and is not modal.
19.17.b: Example
The following program creates a dialog window with a push button labeled "Done". When the user attempts to close the dialog from the caption bar, a
beep is sounded. When the button is pressed, the dialog window is deleted.
clear
#
Caption = "Test Dialog"
geometry = [100, 100, 100, 100]
callback = "beep"
#
geometry = [20, 20, 50, 20]
name
= "Done"
callback = "delwin(Caption);"
19.18: Determining The Size Of The Screen In Pixels
Syntax getscreen
19.18.a: Description
Returns a two-element integer row vector in which the first element is the screen width and the second element is the screen height (in pixels).
19.19: Determining The Current Size Of The O-Matrix Main Window
Syntax getvisible
19.19.a: Description
Returns a two-element integer row vector containing the size of the visible region within the main O-Matrix window in pixels.
19.19.b: Example
You can use the getvisible function to place a window in the middle of the main O-Matrix window. If you enter
size
= getvisible
data
= ["Line 1.", NEW_LINE, "Line 2."]
caption = "Editor Window"
geometry = [size / 4, size / 2]
callback = "delwin(caption);"
O-Matrix will create an editor window in the center of the main window. You can delete the editor using its caption bar.
19.20: Getting and Setting a Window's Geometry
Syntax windowgeometry(caption)
windowgeometry(caption, geometry)
19.20.a: Description
Returns or sets the position and size of a window.
windowgeometry(caption)
Returns the current geometry: 26.s of the window with the specified caption: 26.b . If the window is currently displayed as an icon or in full screen
mode, the geometry corresponds to when the window was last displayed in normal mode.
windowgeometry(caption, geometry)
If the second argument geometry is present, the window geometry is set to the specified value and the return value corresponds to the geometry before
this change.
19.20.b: Examples
If you enter
windowgeometry("Graphic 0")
O-Matrix will print a four element integer row vector in which the first element is the right coordinate of the start of the window, the second element is
the down coordinate of the windows start, the third element is its width, and the fourth element is its height. If you enter
g = windowgeometry("Command")
g(1) = 1
g(2) = 1
windowgeometry("Command", g)
O-Matrix will move the command window to the upper left corner of the work space.
19.21: Creating and Using Controls In a Dialog Window
Syntax addcontrol(caption, geometry, control type, ... )
setcontrol(handle, value)
getcontrol(handle)
19.21.a: Description
The function addcontrol adds controls to a dialog: 19.17 window. The function setcontrol sets the current state of a control and the function
getcontrol gets the current state of a control. Each of the sections listed below discusses these functions for a specific control type. Trailing spaces in
the control type specification are ignored. Controls can be enabled and disabled using the show: 19.26 and hide: 19.25 functions.
19.21.b: Contents
Using Push Buttons In A Dialog Window: 19.21.1
Using Text Labels In A Dialog Window: 19.21.2
Using Text Input Fields In A Dialog Window: 19.21.3
Using Radio Buttons In A Dialog Window: 19.21.4
Using A Check Box In A Dialog Window: 19.21.5
Using A Multi-Selection List In A Dialog Window: 19.21.6
Using A List Box In A Dialog Window: 19.21.7
Using A Popup Menu In A Dialog Window: 19.21.8
Using A Slider In A Dialog Window: 19.21.9
Using A Bit Map In A Dialog Window: 19.21.10
19.21.1: Using Push Buttons In A Dialog Window
Syntax addcontrol(caption, geometry, "pushbutton", name, call back)
19.21.1.a: Description
Adds a push button control, with the specified geometry: 26.s , to the Dialog window specified by caption: 26.b . The character row vector name
specifies the text to be placed on the button. The command specified by call back: 26.a is executed when the button is pressed. (The return value is the
control handle: 26.e for the push button but it is not currently used.)
19.21.1.b: Example
The following program creates a dialog window with two push buttons labeled "Ok" and "Cancel". When one of the buttons is pressed, the name of the
corresponding button is echoed in the command window and the dialog is deleted.
clear
#
Caption = "Test Dialog"
geometry = [100, 100, 200, 100]
callback = "delwin(Caption);"
#
geometry = [20, 20, 50, 20]
name
= "Ok"
callback = [ "print", dquote(name), "; delwin(Caption);"]
#
geometry = [130, 20, 50, 20]
name
= "Cancel"
callback = [ "print", dquote(name), "; delwin(Caption);"]
19.21.2: Using Text Labels In A Dialog Window
19.21.2.a: Description
Dialog "label" controls are used to display text information and do not accept user input.
geometry, "label", text)
Adds a "label" control, with the specified geometry: 26.s , to the Dialog window specified by caption: 26.b . The character row vector text specifies the
text that is initially placed in the label control. The return value is the handle: 26.e for the label control.
setcontrol(handle, text)
Changes the text displayed in the "label" control specified by handle to the value specified text, where handle is the value returned by addcontrol
when the "label" control was created and text is a character row vector. The return value of setcontrol is true, if the control can be set as requested,
and false otherwise.
19.21.2.b: Example
The following program creates a dialog window with two lines of text. It waits three seconds and then changes the text in the second line. You can
close the window using its menu caption bar.
clear
#
Caption = "Test Dialog"
geometry = [100, 100, 200, 100]
callback = "delwin(Caption);"
#
geometry = [20, 20, 100, 20]
text
= "Line one"
#
geometry = [20, 40, 100, 20]
text
= "Line two"
handle = addcontrol(Caption, geometry, "label", text);
#
sleep(3)
setcontrol(handle, "Line 2");
19.21.3: Using Text Input Fields In A Dialog Window
19.21.3.a: Description
Dialog "textfield" controls are used to display text information that the user can change.
geometry, "textfield")
geometry, "textfield", text)
geometry, "textfield", text, call back)
Adds a "textfield" control, with the specified geometry: 26.s , to the Dialog window specified by caption: 26.b . The character row vector text specifies
the initial text to be placed in the field. The command specified by call back: 26.a is executed whenever the contents of the text field is changed by the
user. The return value is the control handle: 26.e for the text field.
getcontrol(handle)
Returns the text displayed in the "textfield" control specified by handle, where handle is the value returned by addcontrol when the "textfield"
control was created. The return value is a character row vector.
setcontrol(handle,
text)
Changes the text displayed in the "textfield" control specified by handle to the value specified text, where handle is value returned by addcontrol
when the "textfield" control was created and text is a character row vector. The return value of setcontrol is true, if the control can be set as
requested, and false otherwise.
19.21.3.b: Example
The following program creates a dialog window with a push button labeled "Done" and a text field. The first time the button is pressed, the contents of
the text field is changed to "modify this". The second time the button is pressed, the contents of the text field is printed in the command window and
the dialog is deleted.
clear
#
Caption = "Test Dialog"
geometry = [100, 100, 200, 100]
callback = "delwin(Caption);"
#
geometry = [20, 20, 160, 20]
text
= "initial value"
Handle
#
geometry = [70, 50, 50, 20]
name
= "Done"
callback = "Done"
#
count
= 0
function Done() begin
global Handle, count, Caption
count = count + 1
if count == 1 then begin
setcontrol(Handle, "modify this");
return
end
print getcontrol(Handle)
delwin(Caption);
end
19.21.4: Using Radio Buttons In A Dialog Window
19.21.4.a: Description
Dialog "radiobuttons" controls are used to display a list from which the user can make one choice.
Adds a "radiobuttons" control, with the specified geometry: 26.s , to the Dialog window specified by caption: 26.b . The row dimension of the
character matrix names specifies the number of radio buttons in this set and each row contains the text that is placed to the right of the corresponding
button. The command specified by call back: 26.a is executed when the currently chosen button is changed by the user. The return value is the
control handle: 26.e for the set of radio buttons.
The geometry specifies the size of each individual radio button, including its label. The height for the total set of radio button is the height specified in
geometry times the number of rows in the matrix names.
getcontrol(handle)
Returns the current choice for the "radiobuttons" control specified by handle, where handle is the value returned by addcontrol when the
"radiobuttons" control was created. The return value is a logical column vector with the same row dimension as names in the corresponding call to
addcontrol. One and only one element of the return value is true and the corresponding row of names is the current choice from the set of radio
buttons.
setcontrol(handle, flag)
Changes the current choice for the "radiobuttons" control specified by handle to the value specified flag, where handle is value returned by
addcontrol when the "radiobuttons" control was created and flag is a logical column vector with the same row dimension as names. One and only
one element of flags is true and the corresponding row of names is the current choice from the set of radio buttons. The return value of setcontrol is
true, if the control can be set as requested, and false otherwise.
19.21.4.b: Example
The following program creates a dialog window with a push button labeled "Done" and a set of radio buttons. Initially, the last choice of the radio
buttons is selected. When the button is pressed, the name of the currently chosen radio button is printed in the command window and the dialog is
deleted.
clear
#
Caption = "Test Dialog"
geometry = [100, 100, 200, 150]
callback = "delwin(Caption);"
#
geometry = [20, 20, 100, 20]
Names
= { "One", "Two", "Three"}
Handle
setcontrol(Handle, {false, false, true});
#
geometry = [70, 90, 50, 20]
name
= "Done"
callback = "Done"
#
function Done() begin
global Caption, Names, Handle
flag = getcontrol(Handle)
print Names.row(flag)
delwin(Caption);
end
19.21.5: Using A Check Box In A Dialog Window
19.21.5.a: Description
Dialog "checkbox" controls are used to display a true or false option that the user can change.
geometry, "checkbox", name)
geometry, "checkbox", name, call back)
Adds a "checkbox" control, with the specified geometry: 26.s , to the Dialog window specified by caption: 26.b . The character row vector name
specifies the label that is placed to the right of the check box. The command specified by call back: 26.a is executed whenever the state of the check
box is changed by the user. The return value is the control handle: 26.e for the check box.
getcontrol(handle)
Returns the current state of the "checkbox" control specified by handle, where handle is the value returned by addcontrol when the "checkbox"
control was created. The return value is a logical scalar.
setcontrol(handle, flag)
Changes the current state of the "checkbox" control specified by handle to the value specified flag, where handle is value returned by addcontrol
when the "checkbox" control was created and flag is a logical scalar. The return value of setcontrol is true, if the control can be set as requested, and
false otherwise.
19.21.5.b: Example
The following program creates a dialog window with a push button labeled "Done" and a check box. The check box is initially set true. When the user
changes the check box state, the new state is printed in the command window. When the button is pressed, the dialog is deleted.
clear
#
Caption = "Test Dialog"
geometry = [100, 100, 200, 100]
callback = "delwin(Caption);"
#
geometry = [20, 20, 150, 20]
text
= "Check Box"
StateLbl = "State ="
callback = "print StateLbl, getcontrol(Handle)"
Handle
= addcontrol(Caption, geometry, "checkbox", text, callback);
setcontrol(Handle, true);
#
geometry = [70, 50, 50, 20]
name
= "Done"
callback = "delwin(Caption);"
#
19.21.6: Using A Multi-Selection List In A Dialog Window
19.21.6.a: Description
Dialog "multilist" controls are used to display a list from which the user can make one or more selections. These controls behave identical to listbox:
19.21.7 controls with the exception that more than one item may be selected.
geometry, "multilist", list)
geometry, "multilist", list, call back)
Adds a "multilist" control, with the specified geometry: 26.s , to the window specified by caption: 26.b . The geometry specifies the size of the multiselection list. The character matrix list specifies the choices in the list. The command specified by call back: 26.a is executed whenever the current
selection in the list is changed by the user. The return value is the control handle: 26.e for the multilist selection box.
getcontrol(handle)
Returns the current section in the "multilist" control specified by handle, where handle is the value returned by addcontrol when the "multilist"
control was created. The return value is a logical column vector with the same row dimension as list in the corresponding call to addcontrol .
setcontrol(handle, list)
Changes the list of choices in the "multilist" control specified by handle to the list specified by list, where handle is the value returned by addcontrol
when the "multilist" control was created and list is a character matrix. The return value of setcontrol is true, if the control can be set as requested,
and false otherwise.
19.21.6.b: Example
The following program creates a dialog window with a push button labeled "Print" and a "multilist" control. When the button is pressed, the value
corresponding to the "multilist" control is transposed and printed in the Command window.
clear
#
caption = "Multi List Box Example"
geometry = [100, 100, 250, 200]
callback = "delwin(caption);"
#
geometry = [10, 10, 140, 100]
list
= {"One", "Two", "Three"}
Handle
= addcontrol(caption, geometry, "multilist", list )
#
geometry = [35, 145, 90, 20]
name
= "Print"
callback = "Print"
#
function Print() begin
global Handle
print getcontrol(Handle)'
end
19.21.7: Using A List Box In A Dialog Window
19.21.7.a: Description
Dialog "listbox" controls are used to display a static list from which the user may select one item. These controls behave identical to multilist: 19.21.6
controls with the exception that only one item may be selected.
geometry, "listbox", list)
geometry, "listbox", list, call back)
Adds a "listbox" control, with the specified geometry: 26.s , to the window specified by caption: 26.b . The geometry specifies the size of the list box.
The character matrix list specifies the choices in the list box. The command specified by call back: 26.a is executed whenever the current selection in
the list is changed by the user. The return value is the control handle: 26.e for the list box.
getcontrol(handle)
Returns the current section in the "listbox" control specified by handle, where handle is the value returned by addcontrol when the "listbox" control
was created. The return value is a logical column vector with the same row dimension as list in the corresponding call to addcontrol.
setcontrol(handle, list)
Changes the list of choices in the "listbox" control specified by handle to the list specified by list, where handle is the value returned by addcontrol
when the "listbox" control was created and list is a character matrix. The return value of setcontrol is true, if the control can be set as requested, and
false otherwise.
19.21.7.b: Example
The following program creates a dialog window with a push button labeled "Print" and a "listbox" control. When the button is pressed, the value
corresponding to the "listbox" control is transposed and printed in the Command window.
clear
#
caption = "List Box Example"
geometry = [100, 100, 250, 200]
callback = "delwin(caption);"
#
geometry = [10, 10, 140, 100]
list
= {"One", "Two", "Three"}
Handle
= addcontrol(caption, geometry, "listbox", list )
#
geometry = [35, 145, 90, 20]
name
= "Print"
callback = "Print"
#
function Print() begin
global Handle
print getcontrol(Handle)'
end
19.21.8: Using A Popup Menu In A Dialog Window
19.21.8.a: Description
Dialog "popupmenu" controls are used to display a list from which the user can make one choice.
Adds a "popupmenu" control, with the specified geometry: 26.s , to the window specified by caption: 26.b . The geometry specifies the size of the
menu when it is popped up. The character matrix menu specifies the choices in the popup menu. The integer scalar index specifies which row of menu
is used for the initial setting of the popup menu (it must be between 1 and the row dimension of menu). The command specified by call back: 26.a is
executed whenever the contents of the popup menu is changed by the user. The return value is the control handle: 26.e for the popup menu.
getcontrol(handle)
Returns the current section in the "popupmenu" control specified by handle, where handle is the value returned by addcontrol when the
"popupmenu" control was created. The return value is a character row vector.
setcontrol(handle,
Changes the list of choices in the "popupmenu" control specified by handle to the list specified menu, where handle is value returned by addcontrol
when the "popupmenu" control was created and menu is a character matrix. The return value of setcontrol is true, if the control can be set as
requested, and false otherwise.
19.21.8.b: Example
The following program creates a dialog window with a push button labeled "Done" and a popup menu. The first time the button is pressed, the list of
choices in the popup menu is changed. The second time the button is pressed, the current menu choice is printed in the command window and the
dialog is deleted.
clear
#
Caption = "Test Dialog"
geometry = [100, 100, 200, 100]
callback = "delwin(Caption);"
#
geometry = [20, 20, 70, 100]
= {"One", "Two", "Three"}
index
= 2
Handle
#
geometry = [70, 50, 50, 20]
name
= "Done"
callback = "Done"
#
count
= 0
function Done() begin
global count, Handle, Caption
count = count + 1
if count == 1 then begin
menu = {"A 1", "B 2", "C 3", "D 4"}
return
end
print getcontrol(Handle)
delwin(Caption);
end
19.21.9: Using A Slider In A Dialog Window
19.21.9.a: Description
Dialog "slider" controls display an integer value that the user can change. (In fact, from the users point of view, any ordered value can be displayed.)
addcontrol(caption, geometry, "slider", lower, upper, call back)
Adds a "slider" control, with the specified geometry: 26.s , to the window specified by caption: 26.b . The integer scalars lower and upper specify the
lower and upper limits for the sliders value. The command specified by call back: 26.a is executed whenever the user moves the slider. The return
value is the control handle: 26.e for the text field.
If geometry(3) > geometry(4), the slider moves in the horizontal direction. Otherwise, the slider moves in the vertical direction. If the slider moves
horizontally, the value lower corresponds to the left and upper corresponds to the right side of the slider control. If the slider moves vertically, the
value lower corresponds to the bottom and upper corresponds to the top of the slider control.
getcontrol(handle)
Returns the current position of the "slider" control specified by handle, where handle is the value returned by addcontrol when the "slider" control
was created. The return value is an integer scalar.
setcontrol(handle,
index)
Changes the current position of the "slider" control specified by handle to the value specified index, where handle is value returned by addcontrol
when the "slider" control was created and index is an integer scalar between the corresponding values of lower and upper. The return value of
setcontrol is true, if the control can be set as requested, and false otherwise.
19.21.9.b: Example
The following program creates a dialog window with a push button labeled "Done" and a slider with a label that contains the slider's value. The slider
starts in the middle position and when the slider is moved, the label is changed to reflect the new slider position. When the button is pressed, the dialog
is deleted.
clear
#
Caption = "Test Dialog"
geometry = [100, 100, 200, 120]
callback = "delwin(Caption);"
#
geometry = [20, 20, 160, 20]
lower
= 1
upper
= 100
initial = 50
Slider
= addcontrol(Caption, geometry, "slider", lower, upper, "Callback")
setcontrol(Slider, initial);
#
geometry = [90, 40, 30, 20]
text
= clipstr(ntoa(initial))
Label
#
geometry = [70, 70, 50, 20]
name
= "Done"
callback = [ "print getcontrol(Slider); delwin(Caption);"]
#
function Callback() begin
global Slider, Label
value = getcontrol(Slider)
value = clipstr(ntoa(value))
setcontrol(Label, value);
end
19.21.10: Using A Bit Map In A Dialog Window
19.21.10.a: Description
Adds a bitmap, with the specified geometry: 26.s , to the window specified by caption: 26.b . The character row vector file specifies the file that
contains the bitmap (*.BMP).
19.21.10.b: Example
The following program creates a dialog window with a push button labeled "Done" and a bitmap. When the button is pressed, the dialog is deleted.
clear
#
Caption = "Test Dialog"
geometry = [100, 100, 100, 100]
callback = "delwin(Caption);"
#
geometry = [50 - 16, 10, 32, 32]
file
= "c:\windows\cars.bmp"
#
geometry = [50 - 25, 50, 50, 20]
name
= "Done"
callback = "delwin(Caption);"
19.22: Deleting A Window
Syntax delwin(caption)
19.22.a: Description
Deletes the window specified by the character row vector caption: 26.b .
19.23: Iconifying A Window
Syntax iconify( caption)
19.23.a: Description
Iconifies the window with the specified caption: 26.b . An iconified widow can be normalized using the show: 19.26 function. If the value of caption is
"omatrix", the main O-Matrix application window is iconified.
19.23.b: Example
If you enter
iconify("Graphic 0")
the default graphics window will be iconified. If you continue by entering
show("Graphic 0")
the graphics window will be normalized.
19.24: Determining If A Window Is Iconified
Syntax isicon(caption)
19.24.a: Description
Returns true if the window with the specified caption: 26.b is displayed as an icon and false otherwise.
19.25: Hiding A Window Or Disabling A Control
Syntax hide(caption)
hide(handle)
19.25.a: Description
If caption is a character row vector, hides the window with the specified caption: 26.b . If caption is "toolbar" and no such window exists, the OMatrix toolbar is disabled (i.e., grayed out). If caption is "omatrix" then the entire O-Matrix application is hidden. That is no user interface or icon
appears on the desktop.
Note that when running the O-Matrix VM (The re-distributable run-time engine provided with the O-Matrix Development Kit), the O-Matrix startup
state is to be displayed. For many applications in which you have provided the desired end-user interface it is desirable to run O-Matrix hidden,
show("omatrix")
If handle is an integer column vector with two elements, the control specified by handle is disabled (i.e., grayed out), where handle is the value
returned by the call to addcontrol: 19.21 that created the control. Controls with the bitmap: 19.21.10 style cannot be disabled.
19.25.b: Caption Example
If you enter
hide("Graphic 0")
the default graphics window will disappear. You can use
show("Graphic 0")
to make the window reappear.
19.25.c: Handle Example
The following program creates a dialog window with a push button labeled "Disable". When the button is pressed, it is disabled and cannot be
activated again. The dialog can be deleted using the control on its caption bar.
clear
#
Caption = "Test Dialog"
geometry = [100, 100, 150, 100]
callback = "delwin(Caption);"
#
geometry = [40, 20, 70, 20]
name
= "Disable"
callback = "hide(Handle);"
Handle
= addcontrol(Caption, geometry, "pushbutton", name, callback)
19.26: Normalizing A Window Or Enabling A Control
Syntax show(caption)
show(handle)
19.26.a: Description
If caption is a character row vector, the window with the specified caption: 26.b is displayed in normal mode. If caption is "toolbar" and no such
window exists, the O-Matrix toolbar is enabled (i.e., not grayed out). If caption is "omatrix", the main O-Matrix application is made visible.
If handle is an integer column vector with two elements, the control specified by handle is enabled (i.e., not grayed out), where handle is the value
returned by the call to addcontrol: 19.21 that created the control. Controls with the bitmap: 19.21.10 style cannot be enabled.
19.26.b: Caption Example
If you enter
hide("Graphic 0")
the default graphics window will disappear. You can use
show("Graphic 0")
to make the window reappear.
19.26.c: Handle Example
The following program creates a dialog window with a check box labeled "Done" and a push button labeled "Enable". When the button is pressed, the
check box is enabled. When the check box is checked, the dialog is deleted.
clear
#
Caption = "Test Dialog"
geometry = [100, 100, 150, 100]
callback = "delwin(Caption);"
#
geometry = [20, 20, 60, 20]
name
= "Done"
callback = "delwin(Caption);"
Handle = addcontrol(Caption, geometry, "checkbox", name, callback)
setcontrol(Handle, false);
hide(Handle)
#
geometry = [40, 50, 70, 20]
name
= "Enable"
callback = "show(Handle);"
19.27: Setting the O-Matrix Application Caption
Syntax caption( captionString)
19.27.a: Description
Sets the O-Matrix application caption to the string specified by the character row vector, captionString
19.27.b: Example
If you enter the command
caption("My Application")
the O-Matrix application will appear as:
19.28: Graphical User Interface Size Parameters
19.28.a: Description
The routines in this section provide information that is useful when positioning controls within a dialog. The values returned by the functions in this
section may change for different operating systems. For this reason it is better to use these function instead of using the values directly.
19.28.b: Contents
Determining The Size of Text In a Dialog Window: 19.28.1
Determining the Size of a Dialog's Border: 19.28.2
Determining Width of Window Controls on Caption Bar: 19.28.3
Determine the Extra Space Needed for a Text Field: 19.28.4
Determine the Extra Space Needed for a Popup Menu: 19.28.5
Determine the Extra Width Needed for Radio Buttons: 19.28.6
19.28.1: Determining The Size of Text In a Dialog Window
19.28.1.a: Syntax
textsize(text)
TextSize(text)
19.28.1.b: Description
Description Returns a matrix containing the number of pixels wide and high that is used to display each row of text using the current system font. The
routine textsize is an intrinsic function and requires text to be a character row vector. The routine TextSize is defined in the include file
guisize.oms and allows text to be an arbitrary character matrix. The Return value is a two column integer matrix in which the first column is the
width of the corresponding row of text and the second column is the height of the corresponding row of text.
19.28.1.c: Example
If you enter
text = "line 1"
textsize(text)
O-Matrix will respond with a two element row vector in which the first element is the width and the second element is the height of "line 1" in pixels.
If the file guisize.oms has not yet been included, enter the command
include guisize.oms
If you enter
text = {"line 1", "line two"}
TextSize(text)
O-Matrix will respond with a 2 by 2 matrix in which the first row contains the size of "line 1" in pixels and the second matrix contains the size of "line
two" in pixels.
19.28.1.d: Reference
The current display adapter resolution and system font affects the value returned by these routines. Trailing blanks with in each row of text are ignored
unless the entire line is blank in which case the size of one space is returned. If text has zero row dimension, the return value is the integer row vector
[0, 0].
19.28.2: Determining the Size of a Dialog's Border
19.28.2.a: Syntax
bordersize
19.28.2.b: Description
returns the number of pixels used to draw a dialogs border as a two element integer row vector. The first element is the total border width and the
second element is the total border height. This is the difference between the dialogs declared size and the area available for placing controls with in the
dialog. This routine is defined in the include file guisize.oms
19.28.2.c: Example
If the file guisize.oms has not yet been included, enter the command
include guisize.oms
If you enter
bordersize
O-Matrix will respond
[8, 25]
which is the number of pixels currently used for the dialogs border. It is better to use this function instead of the values directly incase these values
change in a future version of O-Matrix.
19.28.3: Determining Width of Window Controls on Caption Bar
19.28.3.a: Syntax
wincontrolwidth
19.28.3.b: Description
The space used for window controls in the dialog caption bar cannot be used for the caption itself. This routine returns the difference between the
dialogs declared width an the width available for the caption as an integer scalar. It is defined in the include file guisize.oms
19.28.3.c: Example
If the file guisize.oms has not yet been included, enter the command
include guisize.oms
If you enter
wincontrolwidth
O-Matrix will respond
67
which is the pixel width currently used for the window controls. It is better to use this function instead of the values directly incase these values change
in a future version of O-Matrix.
19.28.4: Determine the Extra Space Needed for a Text Field
19.28.4.a: Syntax
textfieldspace
19.28.4.b: Description
Returns the number of pixels required for space between the inside and outside of a "textfield" control. This is the difference between the space
reserved for the control in the call to addcontrol: 19.21 and the space available for the text. It is returned as a two element integer row vector with the
first element corresponding to the width and the second element corresponding to the height. This routine is defined in the include file guisize.oms
19.28.4.c: Example
If the file guisize.oms has not yet been included, enter the command
include guisize.oms
If you enter
textfieldspace
O-Matrix will respond
[10, 10]
which is current difference. It is better to use this function instead of the values directly incase these values change in a future version of O-Matrix.
19.28.5: Determine the Extra Space Needed for a Popup Menu
19.28.5.a: Syntax
popupspace
19.28.5.b: Description
Returns the number of pixels required for space between the inside and outside of a "popupmenu" control. This is the difference between the space
reserved for the control in the call to addcontrol: 19.21 and the space available for each line of the menu in the control. It is returned as a two element
integer row vector with the first element corresponding to the width and the second element corresponding to the height. This is defined in the include
file guisize.oms
19.28.5.c: Example
If the file guisize.oms has not yet been included, enter the command
include guisize.oms
If you enter
popupspace
O-Matrix will respond
[30, 10]
which is current difference. It is better to use this function instead of the values directly incase these values change in a future version of O-Matrix.
19.28.6: Determine the Extra Width Needed for Radio Buttons
19.28.6.a: Syntax
19.28.6.b: Description
Returns the number of pixels of width required between the inside and outside of a "radiobuttons" control. This is the difference between the width
reserved for the control in the call to addcontrol: 19.21 and the width available for the name of the buttons. It is returned as an integer scalar. This
routine is defined in the include file guisize.oms
19.28.6.c: Example
If the file guisize.oms has not yet been included, enter the command
include guisize.oms
If you enter
O-Matrix will respond
30
which is current difference. It is better to use this function instead of the values directly incase these values change in a future version of O-Matrix.
20.a: Contents
normfunction: 20.1 Vector And Matrix Norms
path: 20.2
Source Code Search Path
defined: 20.3
Determine if an Identifier is Defined in Current Environment
variables: 20.4
Listing Variables Defined in The Current Environment
error: 20.5
Using the Standard O-Matrix Error Dialog
errortrap: 20.6
Trapping O-Matrix Errors Under Program Control
help: 20.7
Invoking Help From Within An O-Matrix Program
garbage: 20.9
Garbage Collection of System Allocated Memory
eval: 20.10
Evaluating a Character Matrix
execmat: 20.11
Delayed Execution of Commands in a Matrix
execfile: 20.12
Including A File During Program Execution
sprintf: 20.13
Converting Values To Ascii Using C Language Formatting
interrupt: 20.14
Setting Response Time During Execution
runall: 20.15
Running All the Files in a Directory
filediff: 20.16
Print the Differences Between Ascii Files
update: 20.17
Comparing And Updating Source Files
20.1: Vector And Matrix Norms
Syntax norm( x )
norm( x, p )
20.1.a: Description
Returns the norm of x where x is an integer, real, double-precision, or complex matrix. If x is integer or real, the return value is a real scalar, otherwise
the return value is a double-precision scalar. If the argument p is present, it can be a positive integer, real, or double-precision scalar. It can also be the
character vectors "fro", "inf", or "-inf".
If x is an empty matrix: 26.o , the return value is equal to zero.
20.1.b: Scalars
In all cases, the norm of a scalar is equal to its absolute value. If you enter
norm(-5)
O-Matrix will respond
5
20.1.c: Vectors
20.1.c.a: Frobenius Norm
If x is a vector and p is equal to "fro", the Frobenius norm of x is computed. The Frobenius norm of x is the square root of the sum of the squares of the
absolute value of the elements of x. For example
norm([3, 4], "fro")
will result in
5
20.1.c.b: Maximum Norm
If x is a vector and p is equal to "inf" the return value is the maximum of the absolute value of the elements of x. For example
norm([3, 4], "inf")
will result in
4
20.1.c.c: Minimum Norm
If x is a vector and p is equal to "-inf" the return value is the minimum of the absolute value of the elements of x. For example
norm([3, 4], "-inf")
will result in
3
20.1.c.d: P-Norm
If x is a vector and p is a number other than plus or minus infinity, the return value is equal to
/ p
p
p \ (1/p)
| x + x + ... + x |
\ 1
2
n /
20.1.d: Matrices
20.1.d.a: Euclidian Norm
If x is not a vector or an empty matrix and p is not present or it is equal to 2, the return value is the maximum absolute singular value: 12.13
corresponding to the matrix x. For example,
x = { ...
[3, 0], ...
[0, 4] ...
}
norm(x)
will result in
4
20.1.d.b: Frobenius Norm
If x is not a vector or an empty matrix and p is equal to "fro", the Frobenius norm of x is computed. The Frobenius norm of x is the square root of the
sum of the squares of the absolute value of the elements of x. For example
x = { ...
[3, 0], ...
[0, 4] ...
}
norm(x, "fro")
will result in
5
20.1.e: One Norm
If x is not a vector or an empty matrix and p is equal to 1, the return value is the maximum with respect to the columns of x of the sum of the absolute
value of the elements in each column. For example,
x = { ...
[1, 2], ...
[3, 4] ...
}
norm(x, 1)
will result in
6
20.1.f: Infinity Norm
If x is not a vector or an empty matrix and p is equal to "inf", the return value is the maximum with respect to the rows of x of the sum of the absolute
value of the elements in each row. For example,
x = { ...
[1, 2], ...
[3, 4] ...
}
norm(x, "inf")
will result in
7
20.1.g: Reference
The values plus and minus infinity can be used in place of "inf" and "-inf" respectively.
20.2: Source Code Search Path
Syntax path
path(newpath)
20.2.a: Description
If the argument newpath is not present the return value of the path function is a character row vector containing the search path. If the argument
newpath is present, the search path is changed to this value.
20.2.b: Search Path
The search path is a sequence of directory names separated by semicolons. Leading white space: 26.ar is ignored in each of the directory names. When
searching for a source code file, O-Matrix first looks in the current directory for the file. If it cannot be found there O-Matrix looks in the directories
specified by the current search path. These directories are searched in the order that they appear in the path. If the file name exists in more than one
path, the first file found is chosen.
20.2.c: Example
If you enter
path("c:\omwin; c:\omwin\lib; c:\omwin\function")
O-Matrix will set to the search path to the three directories c:\omwin, c:\omwin\lib and c:\omwin\function. If you then enter
include colsum.oms
O-Matrix will include the file c:\omwin\function\colsum.oms if you continue by entering
path
O-Matrix will respond
c:\omwin; c:\omwin\lib; c:\omwin\function
If you continue by entering the clear command, O-Matrix will reset the path as specified in the autoexec: 24.1 file.
20.2.d: Reference
The directories specified by the path function can use the notation parent\..\ to specify the parent directory. If you enter
path( [cwd, "\..\; ", path] )
the parent directory of the current directory is included in the search path.
20.2.e: Mlmode
There are two separate search paths, one is used for O-Matrix mode and the other is for Mlmode: 25 . If you are in O-Matrix mode, you can access the
Mlmode search path using the function mlpath.
20.3: Determine if an Identifier is Defined in Current Environment
Syntax defined( id)
20.3.a: Description
Determines the meaning of the identifier specified by id in the current environment: 21.10 where id is a character row vector. The return value is a
character row vector with the following meaning
Value
Meaning
"undefined" not defined and there is no corresponding automatic include file: 3.9
"dll"
dll: 22.3.1 function
"label"
code transfer label: 5.6
"constant" constant: 3.3
"variable" variable
"function" function defined: 11.1 by source code
"intrinsic" intrinsic function
"file"
not defined but there is a corresponding automatic include file: 3.9
20.3.b: Example
If you enter
clear
function f(x) begin
return defined("x")
end
f(1)
O-Matrix will respond
variable
20.4: Listing Variables Defined in The Current Environment
Syntax variables
20.4.a: Description
Returns a character matrix containing a list of the variables that are defined in the current file and function; i.e., the variables that are currently in
scope: 26.aj . Each row of the return value corresponds to one variable and is divided into six columns. The columns are separated by commas, thus
the align: 9.1 function can be used to line the columns up. The first column contains the name of the variable. The second column contains the type:
6.4.1 of the variable. The third (fourth) column contains the number of rows (columns) in the corresponding matrix. The fifth (sixth) column contains
the name of the function (file) that the variables scope is restricted to. If the fifth (sixth) column is just spaces, the variable is not restricted to a specific
function (file).
20.4.b: Example
If at the O> prompt you enter
clear
x = 1
const y = 2
function f() begin
global x
z = 3
variables
end
f
O-Matrix will respond
x,int,1,1,f,
z,int,1,1,f,
There is nothing listed in the sixth column because the scope of f is not restricted to a particular file. The function f is listed in the fifth column for x
because the scope of the global statement is limited to the function. The name y does not appear because it corresponds to a constant.
20.5: Using the Standard O-Matrix Error Dialog
Syntax error( msg)
error( msg, topic)
See Also usage: 20.5.d , halt: 5.7 , errortrap: 20.6 , errordlg: 19.7 , help: 20.7
20.5.a: Description
Posts the standard O-Matrix error dialog and then halts the currently executing O-Matrix program.
msg
is a matrix that specifies an error message that is included in the error dialog. This is the beginning of the actual error message. It is either an
empty matrix: 26.o or it must be a character matrix. If all the character in msg are white space: 26.ar characters, the error routine returns without
posting the error dialog. Otherwise O-Matrix execution is halted: 5.7 and error never returns to the routine that called it.
topic
If the Help button in the error dialog is selected, the file specified by the character row vector topic in the directory c:\omwin\htm is displayed in your
web browser. This file specification does not include the extension of the file which must be .htm. If the specified file is not present in the
c:\omwin\htm directory, the file c:\omwin\htm\index.htm is displayed. If topic is not present, the file c:\omwin\htm\contents.htm is displayed
which corresponds to topic being equal to "contents".
20.5.b: Example
If you enter
error("Error in call to sin", "sin")
O-Matrix will display an error dialog with an error message and the first line of the error message will be
Error in call to sin
If you then select the Help button in the error dialog, O-Matrix will display the file c:\omwin\htm\sin.htm in your default web browser.
20.5.c: Reference
The message specified by msg is just the beginning of the error message posted in the error dialog. Other information, such as the corresponding
source code location where the call to error was made, is included in the error dialog. The routine errordlg: 19.7 does not include this extra
information.
You can use the errortrap: 20.6 routine to trap calls to the error function just like error messages that are generated by the O-Matrix system. Note that
the first rowdim(msg) rows of the message passed to the error trapping routine will contain the message specified by msg. Also not that if the file
specified by topic is not present, the topic passed to the error trapping routine is "index".
20.5.d: Mlmode
In Mlmode: 25 , this function can be accessed using the name usage as well as the name error. If in Mlmode you enter
usage('Improver argument')
O-Matrix will display an error dialog with an error message and the first line of the message will be
Improper argument
20.6: Trapping O-Matrix Errors Under Program Control
Syntax errortrap
errortrap(function trap)
See Also error: 20.5 , help: 20.7 , halt: 5.7 , stop: 3.13
20.6.a: Description
O-Matrix detects certain errors while compiling or executing, such as invalid data in a file. The errortrap function enables a program written in OMatrix to translate an O-Matrix error message to something more useful to the person running a particular O-Matrix program.
errortrap
If trap is not present in the call to errortrap, error trapping is turned off and the normal O-Matrix error dialog is used.
trap)
Sets up the function trap as the transfer point if and when an error occurs. If an error occurs after a call of this form, all active function calls are
aborted, all active include: 3.8 files are aborted, and the trap function is called with the parameters described below:
errortrap(function
trap(topic, msg)
The argument topic is a character row vector containing the O-Matrix help topic that corresponds to the help button in the normal error dialog. The
argument msg is a character matrix containing the message that the normal dialog would display.
20.6.b: Example
The following is a simple error handler that adds extra information to the error message:
clear
ExtraInformation = novalue
function trap(topic, msg) begin
global ExtraInformation
print ExtraInformation
print msg
end
errortrap(function trap)
Suppose that the file TEMP.DAT contains the following
1 2 3 4
5 6 ; 8
text
If you enter the error handler above and then enter
ExtraInformation = "Reading input data file:"
O-Matrix will print the following in the Command window
read: invalid character for int type
Line 2 File C:\OMWIN\TEMP.DAT
Executing at or below line 22 in file
command line
19
end
20
errortrap(function trap)
21
ExtraInformation = "Reading input data file:"
->
23
(the line numbers will be different). You can restore normal error processing by entering:
errortrap
20.7: Invoking Help From Within An O-Matrix Program
Syntax help
help(topic)
help(topic, file)
20.7.a: Description
Displays the help page from the specified file and topic, where file and topic are character row vectors. If topic is not present, the CONTENTS.HTM file,
within the HELP subdirectory of the O-Matrix installation directory, is sent to the default web browser.
If topic is present and file is not present, topic is the name of a file, without its ".htm" extension, in the HELP subdirectory of the O-Matrix installation
directory.
If file is present, it specifies a file where the help information is stored. If the file name ends in the four characters ".hlp", it is a windows help file. If
the file name begins with the five characters "http:", it is a complete world wide web address. If the file name begins with the "\" character, or if its
second character is the colon character ":", it is a complete path specification. Otherwise the file name is relative to the O-Matrix installation directory.
When file is present, topic specifies the help topic within the file (for HTML files this is the NAME field corresponding to an anchor within the file). If
topic is an empty matrix: 26.o , no topic is specified within the file.
Leading and trailing white space: 26.ar in topic and file are ignored.
20.7.b: Example
help
You can display the help for a particular function in O-Matrix by specifying its name. If you enter
help("colmax")
the O-Matrix help for the colmax function will be displayed in the default web browser on your system.
If the file name ends in ".hlp" it is assumed to be a Windows help file. If you enter
file = "c:\windows\winhelp.hlp"
topic = "printing"
help(topic, file)
The help for print a topic in windows help will be displayed.
You can also specify files in the O-Matrix installation directory. If you enter
an
file = "examples.hlp"
topic = "acosh"
help(topic, file)
example for the acosh function will display in
file = "htm\glossary_Frame1.htm"
topic = "Element-By-Element"
help(topic, file)
windows help. The file could also be an HTML file, If you enter
the O-Matrix definition of an Element-By-Element function will be displayed. (Note that O-Matrix stores its help files in the HTM subdirectory of the
installation directory.)
If the file begins with "http:", it should be a valid web address. If your computer is connected to the Internet, you can bring up the O-Matrix home page
by entering:
file = "http://www.omatrix.com"
topic = ""
help(topic, file)
save file name
20.8.a: Save Command
The save command saves the current O-Matrix program, constants, symbols and data values in the file named file name: 26.p . The created file, file
name is a binary, "pcode" file which will load significantly faster than source files. The use of pcode files also enables you to distribute applications
without source code, protecting proprietary work.
This command is only available with the O-Matrix Development Kit: 23 license.
The load command loads the O-Matrix program, constants, symbols and data values from the file named file name: 26.p . This file must have been
created using the save command. In addition, the same version of O-Matrix must be used when executing the save command.
20.8.c: Example
If at the command line enter
clear
function f(x) begin
return x^2
end
y = seq(5)'
save test.omx
O-Matrix will save your program and data in a binary file called test.omx in the current directory. If you exit O-Matrix, then restart and then enter:
print y
O-Matrix will respond
[ 1 , 2 , 3 , 4 , 5 ]
If you continue by entering
print f(y)
O-Matrix will respond
[ 1 , 4 , 9 , 16 , 25 ]
20.8.d: Restrictions
The load and save commands cannot appear inside of a function.
20.8.e: Windows and Dialogs
When you execute the load command, all of the windows, dialogs, and toolbar are set to their initial state; i.e., the dialogs are dismissed, the default
windows are visible and empty, and the toolbar is enabled.
20.8.f: Memory
If you save and then load your program, O-Matrix will return program and data memory that it is not currently using to the system. This may be useful
if your data or program space is currently much smaller than it was previously during this O-Matrix session.
20.8.g: Reference
Note that when you execute the load command, no O-Matrix statements are executed. Only the program state and variable values are restored. Thus
you can speed up program initialization by executing a save command at the end of the initialization and then just executing a load command to start
the program next time.
20.9: Garbage Collection of System Allocated Memory
Syntax garbage
20.9.a: Description
O-Matrix does on the fly garbage collection of memory; i.e., when memory is no longer needed, it is returned to one of its pools of available memory.
In addition, fragmentation is avoided by joining neighboring memory when possible. Still, this memory is retained by O-Matrix and not returned to the
system pool. The garbage script returns most of the O-Matrix memory pools to the system.
20.9.b: Example
If you enter
clear
function f(x) begin
print "f(", x, ")"
end
x = 1
garbage
f(x)
f(1)
20.9.c: Limitations
The garbage script cannot be used inside of begin - end: 5.2 pair.
20.9.d: Mlmode
In Mlmode: 25 , this function is called pack instead of garbage. If you continue the example above by entering
mlmode
pack
f(x)
f(1)
20.10: Evaluating a Character Matrix
Syntax eval(cmd)
20.10.a: Description
Compiles and executes the O-Matrix command contained in the character row vector cmd.
20.10.b: Simple Example
If you enter
x = 5
eval("x = x + x")
print x
O-Matrix will respond
10
20.10.c: Returning A value
The eval function will return a value when cmd is an expression. If you enter
y = eval("1 + 2")
print y
O-Matrix will respond
3
20.10.d: Multiple Return Values
If the cmd is a call to a function that returns multiple values, the eval function will return those values. If you enter
clear
function
x =
y =
end
[u, v] =
print u,
[x, y] = f(a, b) begin
2 * a
2 * b
eval("f(1, 2)")
v
O-Matrix will respond
2, 4
20.10.e: Variable Scoping
The eval function references variables as if they were in the currently executing file and function. If you enter
x = 1
function f() begin
x = 3
eval("x = x + x")
print x
end
f
O-Matrix will respond
6
when it executes the function f. If you continue by entering
x
O-Matrix will respond
1
because the variable x in the main program is different from the variable x with in the function f.
20.10.f: Creating New Variables
If a variable is created by a call to the eval function it cannot be used until after the call is executed. If you enter
clear
begin
eval("a = 1")
eval("print a")
end
O-Matrix will respond
1
If on the other hand you enter
clear
begin
eval("a = 1")
print a
end
O-Matrix will respond with an error message saying that the variable a is not yet defined at the print statement. This is because the call to the eval
function has not yet been executed at the time when the print statement is compiled.
20.10.g: Restrictions
If there is more than one command in a call to eval only the first command is executed. If you enter
eval("print 1; print 2")
O-Matrix will respond
1
20.11: Delayed Execution of Commands in a Matrix
Syntax execmat( mat)
20.11.a: Description
Executes the commands in the character matrix mat outside of the context of the current file and function. (the eval: 20.10 function can be used to
execute commands inside the context of the current file and function.)
20.11.b: Example
If you enter
x = 5
function f(x) begin
execmat("print x")
end
f(10)
O-Matrix will respond
5
even though inside the function f the variable x has the value 10. This is because the command print x is executed in the context of the main
program.
20.11.c: Reference
The commands are written to a temporary file and then the execfile: 20.12 function is used to execute that file. If an error occurs while executing the
commands, the temporary file will be used to reference and display the error message.
20.12: Including A File During Program Execution
Syntax execfile(file name)
20.12.a: Description
Compiles and executes the specified file, where file name is a character row vector. This differs from the include statement in three ways: (1) file
name is any valid O-Matrix expression and can depend on information obtained during execution; (2) the file is not included for compilation and
execution until the corresponding function call to execfile is executed; and (3) the file is executed regardless of whether it has been executed before.
20.12.b: Example
This function does not execute the specified file until the corresponding O-Matrix statement is executed, whereas the include statement includes the
file at compilation time. If the file TEMP.OMS contains the text
print i
and you enter
clear
for i = 1 to 3 begin
include TEMP.OMS
end
O-Matrix will respond
1
2
3
because one copy of the print statement was compiled inside of the for loop. On the other hand, if you enter
for i = 1 to 3 begin
execfile("TEMP.OMS")
end
O-Matrix will respond
4
4
4
because the print statement was included three times during the for loop but executed after the for loop finished.
20.13: Converting Values To Ascii Using C Language Formatting
Syntax sprintf( format string, A, B, ...)
See Also fprintf: 20.13.e , ntoa: 9.5 , format: 8.17.1 , print: 3.12 , write: 8.10
20.13.a: Description
Returns a character row vector that contains an ASCII representation of the list of values A, B, ... This function is very similar to the sprintf function
in the C compute language (see page 154 of The C programming Language by B.W. Kernighan and D.M. Ritchie). It allows for multiple format
specifications to be used when creating a single ASCII string. (The ntoa: 9.5 function is simpler but it only uses one format specification to create a
character matrix.)
The argument format string specifies the manner in which the values in the list A, B, ... are converted to a sequence of ascii: 24.3 characters.
Characters that are not part of a conversion specification are copied directly to the output string with the following C language style escaping of special
characters:
Escape Sequence Resulting Output character
%%
single percent sign
\\
single backslash
\n
new line
\ooo
octal ascii: 24.3 code is ooo
\xhh
hexadecimal ascii: 24.3 code is hh
20.13.b: Conversion Specification
If the pair of characters %% appears in format string they are copied to the output string as a single % (see %% escape sequence above). Otherwise the
character % denotes the beginning of a format conversion specification. A format conversion specification has the following form:
percent sign width dot precision type
The following table describes each of the components in the form above:
Symbol
Characters
Optional
no
sign
yes
width
* or a number yes
dot
.
yes
precision * or a number yes
type
dioxXucsfeEgG no
The following table describes each of the format types in the table above. In this table, the column labeled precision specifies if the specific format
type allows for a dot and precision field:
Type Precision Description
d
no
integer to decimal
i
no
integer to decimal
o
no
positive integer to octal
u
no
positive integer to decimal
x
no
integer to lower case hex
X
no
integer to upper case hex
c
no
from and to ASCII character
s
yes
from and to vector of ASCII characters
f
yes
floating point to fixed point
e
yes
floating point to e scientific notation
E
yes
floating point to E scientific notation
g
yes
combination of f and e formats
G
yes
combination of f and E formats
precent
%
20.13.c: Order Of Conversion
The list of matrices A, B, ... are converted in order. Within each matrix, its elements are converted in column major order: 26.c . If a conversion
specification has no * characters in it, it corresponds to one element. If it has one * character, the specification corresponds to two elements with the
first corresponding to the *. If it has two * characters, the specification corresponds to three elements with the first two corresponding to the *
characters.
20.13.d: Example
20.13.d.a: Integer Formatting
If you enter
s = sprintf("%d", -10)
print type(s), s
O-Matrix will respond
char -10
If you enter
sprintf(":%5i:", -10)
O-Matrix will respond
:
-10:
If you enter
sprintf(":%-5o:%-5u:", 10, 10)
O-Matrix will respond
:12
:10
:
If you enter
sprintf(":%5x:%5X:%05X:", 10, 10, 10)
O-Matrix will respond
:
a:
A:0000A:
If you enter
sprintf(":%-5o:", 10)
O-Matrix will respond
:12
:
20.13.d.b: Floating Point Formatting
The default precision is size places. If you enter
sprintf(":%f:%.6f:", 1.0, 2.0)
O-Matrix will respond
:1.000000:2.000000:
If you enter
sprintf(":%10f:%-10.6f:", 1.0, 2.0)
O-Matrix will respond
:
1.000000:2.000000
:
If you enter
sprintf(":%e:%.6E:", 1.0, 2.0)
O-Matrix will respond
:1.000000e+000:2.000000E+000:
sprintf(":%15e:%-15.6E:", 1.0, 2.0)
O-Matrix will respond
:
1.000000e+000:2.000000E+000
:
The g and G formats only display the number of digits necessary to get the requested precision. If you enter
sprintf(":%g:%.6G:", pi, 2.0)
O-Matrix will respond
:3.14159:2:
If you enter
sprintf(":%g:%.6G:", 1e+10, 2e+20)
O-Matrix will respond
:1e+010:2e+020:
20.13.d.c: String Formation
The c format type can be used to convert a single value using its corresponding ASCII code. If you enter
sprintf("%c, %d, %e", "ABC")
O-Matrix will respond
A, 66, 6.700000e+001
The s format can be used to convert an entire matrix using the corresponding ascii: 24.3 codes. If you enter
sprintf(":%s:%s:", "ABC", [65, 66, 67])
O-Matrix will respond
:ABC:ABC:
If you enter
sprintf(":%10c:%10s:", "A", "ABC")
O-Matrix will respond
:
A:
ABC:
If you enter
sprintf(":%-10c:%-10s:", "A", "ABC")
O-Matrix will respond
:A
:ABC
:
If you enter
sprintf(":%10.2s:%-10.2s:", "ABC", "ABC")
O-Matrix will respond
:
AB:AB
:
20.13.d.d: The Star Conversion Character
The * character is used to specify the value for width or precision when they depends on some other value. If you enter
sprintf(":%*d:", 5, 1)
O-Matrix will respond
:
1:
If you enter
sprintf(":%*.*f:", [10, 2, pi])
O-Matrix will respond
:
3.14:
20.13.e: Mlmode
In Mlmode: 25 , the function fprintf acts the same as sprintf with the exception that the result is printed to the command window instead of
returned as the function value. If in Mlmode you enter
x = 1;
y = 2;
fprintf('one = %g\ntwo = %g\n', x, y);
O-Matrix will respond
one = 1
two = 2
20.14: Setting Response Time During Execution
Syntax interrupt( interval)
20.14.a: Description
The integer, real, or double-precision scalar interval specifies the number of seconds that O-Matrix will execute a program before checking if the user
has typed in the editor window, chosen a command from the O-Matrix menu, or requested any other activity within O-Matrix.
20.14.b: Execution Speed
The larger the value of interval, the faster O-Matrix will run but the slower it will be to respond to user activities in the O-Matrix window. If interval is
0, O-Matrix will not suspend execution and check for other activities.
20.14.c: Light Restrictions
The interval value zero is not available in O-Matrix Light. In addition, the interval cannot be larger than 60 in O-Matrix Light.
20.14.d: Example
The default interval is 3 seconds. This is too long an interval if you are editing a file while O-Matrix is executing. If you enter
interrupt(.1)
for i = 1 to 10000 begin
print i
end
O-Matrix will scroll the values of i in the Command window. If you then choose File | Edit New Program from the menu, O-Matrix will open a
window in which you can edit a program while O-Matrix continues to print the values in the Command window. You can use the red hand to halt
execution of the program.
20.15: Running All the Files in a Directory
Syntax runall(dir, wait)
20.15.a: Description
Runs all the *.OMS and *.oms files that are in the directory specified by that character row vector dir. The current working directory is set to dir during
execution of the files and then is restored to its original value. The nonnegative integer scalar wait specifies the number of seconds to wait between
running each file. If wait is not zero, each file is displayed in an editor window while it is being executed. Nonzero wait values are good for
demonstrations and the zero wait value is good for automated testing.
20.15.b: Example
Suppose that the directory c:\omwin\temp only contains the files temp1.oms and temp2.oms where temp1.oms contains
and
clear
gplot(seq(10))
gupdate
temp2.oms contains
clear
gplot(seq(10)^2)
gupdate
If you enter
dir = "c:\omwin\temp"
wait = 5
runall(dir, wait)
O-Matrix will execute and display the two files.
20.16: Print the Differences Between Ascii Files
Syntax filediff(fx, fy, nr, nc)
filediff(fx, fy, nr, nc, ext)
20.16.a: Description
Prints the difference between two ASCII files or directories. The character row vector fx specifies the first file or directory. The character row vector fy
specifies the second file or directory. The integer scalar nr specifies the number of rows of a file that must match when realigning files. This must be
greater than or equal one. The integer scalar nc specifies the number of columns, from each row, to include in the pattern matching. If a row does not
have enough columns, it is blank filled. If the argument ext is present, both fx and fy must be directories. In this case only subdirectories and files with
extension equal to ext are compared. In this context, the extension of a file name is any sequence of characters at the end of the file name including one
or more periods if so desired.
20.16.b: Example
Suppose that the file temp.1 contains the text
line
line
line
line
and the file
line
line
line
line
one.
two.
three.
four.
temp.2 contains the text
one.
three.
four.
five.
If you enter
fx = "temp.1"
fy = "temp.2"
nr = 2
nc = 80
filediff(fx, fy, nr, nc)
O-Matrix will respond
difference: temp.1 <> temp.2
<line two.
>line five.
The < character is printed in front of text that is in the first file and not the second while the > character is printed in front of text that is in the second
file and not the first.
20.17: Comparing And Updating Source Files
Syntax update(file, directory)
update(file, directory, function callback)
20.17.a: Description
Compares a new version of a file with an old version in the specified directory and then posts a dialog that asks the user if the new one should replace
the old one. If the user agrees, the old version of the file is overwritten with a copy of the new one. The character row vector file specifies the name of
the new file relative to the current directory (as would be returned by cwd: 6.5.5 ). The character row vector directory specifies the name of the
directory in which the old version of the file is stored. The old version of the file has the same name in directory as the new version has in the current
directory.
The user cannot choose his option until O-Matrix is done executing the thread of commands in which the call to update is a part. When the user does
make his choice, a new execution thread is started. If the function callback is present, the function call callback(replace) is make after update
finishes its operation. The argument replace is true if the file was replaced and false otherwise.
20.17.b: Example
Suppose that the file temp.oms in the current directory contains
In
clear
version = "new"
#
print "This is the", version, "version"
print "done"
addition, the file temp.oms in the directory c:\omwin\programs contains
clear
version = "old"
#
print "This is the", version, "version"
print "done"
If at the command line you enter
file
= "temp.oms"
directory = "c:\omwin\programs"
update(file, directory)
O-Matrix will print
difference: temp.oms <> c:\omwin\programs\temp.oms
<version = "new"
>version = "old"
in the command window and then ask if you wish to replace the old version with the new on. (Note that text from the new version is preceded by < and
text from the old version is preceded by >.) If you agree, the file temp.oms in the directory c:\omwin\programs will be replaced. In any event, a
message telling if the file has been replaced is printed in the command window.
20.17.c: Reference
Only the first 100 character in each line are considered when determining the differences between the files.
21: O-Matrix Code Debugger
21.a: Description
The following sections describe the debugger commands in order which they are most commonly used. The quick reference table: 21.c lists commands
in alphabetical order.
21.b: Contents
quit: 21.1
Quitting Execution From Within The Debugger
dbinclude: 21.2 Listing Included Files
active: 21.3
Listing Active Variables in The Current Environment
continue: 21.4
Exiting The Debugger And Continuing Execution
dall: 21.5
Deleting All Break and Watch Points
debug_break: 21.6 Setting And Listing Debugger Break Points
skip: 21.7
Skipping Breakpoints
dbreak: 21.8
Deleting Breakpoints
dbfile: 21.9
Setting Debugger Listing and Environment File
env: 21.10
Displaying The Environment Call Stack
env1: 21.11
Setting The Current Debugger Environment
dbformat: 21.12 Changing Output Format From Within the Debugger
dbglobal: 21.13 Creating Global Variables From Temporary Ones
list: 21.14
Listing Lines In The Current Debugger File
next: 21.15
Stepping Over Function Calls
open: 21.16
Determining What Files Are Open
dbprint: 21.17
Print Values Inside the Debugger
dbhome: 21.18
Clearing the Debugger Window
step: 21.19
Stepping Into Function Calls
dbtrace: 21.20
Line By Line Tracing Of Execution
user: 21.21
Listing The User Defined Functions
watch: 21.22
Creating And Listing Watch Points
dwatch: 21.23
Listing And Deleting Watch Points
which: 21.24
Determine What An Identifier Refers To
21.c: Quick Reference Table
The following table contains all the debugger commands in abbreviated form and alphabetical order:
Syntax
Description
a
Listing Active Variables in The Current Environment: 21.3
b
Setting And Listing Debugger Break Points: 21.6
b line
Setting And Listing Debugger Break Points: 21.6
b index, skip
Skipping Breakpoints: 21.7
c
Exiting The Debugger And Continuing Execution: 21.4
da
Deleting All Break and Watch Points: 21.5
db
Deleting Breakpoints: 21.8
db index
Deleting Breakpoints: 21.8
dw
Listing And Deleting Watch Points: 21.23
dw index
Listing And Deleting Watch Points: 21.23
Displaying The Environment Call Stack: 21.10
Setting The Current Debugger Environment: 21.11
fi
Setting Debugger Listing and Environment File: 21.9
fi name
Setting Debugger Listing and Environment File: 21.9
fo int form
Changing Output Format From Within the Debugger: 21.12
fo real form
Changing Output Format From Within the Debugger: 21.12
fo double form
Changing Output Format From Within the Debugger: 21.12
fo complex form Changing Output Format From Within the Debugger: 21.12
fp
Setting Debugger Listing and Environment File: 21.9
g new = existing
Creating Global Variables From Temporary Ones: 21.13
h
Clearing the Debugger Window: 21.18
i
Listing Included Files: 21.2
l
Listing Lines In The Current Debugger File: 21.14
l start
Listing Lines In The Current Debugger File: 21.14
l start, number
Listing Lines In The Current Debugger File: 21.14
n
Stepping Over Function Calls: 21.15
o
Determining What Files Are Open: 21.16
p name
Print Values Inside the Debugger: 21.17
p name(i)
Print Values Inside the Debugger: 21.17
p name(i, j)
Print Values Inside the Debugger: 21.17
q
Quitting Execution From Within The Debugger: 21.1
s
Stepping Into Function Calls: 21.19
t flag
Line By Line Tracing Of Execution: 21.20
t flag, file
Line By Line Tracing Of Execution: 21.20
u
Listing The User Defined Functions: 21.21
wa
Creating And Listing Watch Points: 21.22
wa name
Creating And Listing Watch Points: 21.22
wa name, fun
Creating And Listing Watch Points: 21.22
wa name, , file
Creating And Listing Watch Points: 21.22
wa name, fun, file Creating And Listing Watch Points: 21.22
whname
Determine What An Identifier Refers To: 21.24
e
e
index
21.1: Quitting Execution From Within The Debugger
Syntax
quit
continue: 21.4
Abbreviation
q
Menu Command Debug | Exit Debugger
21.1.a: Description
Exits the debugger and activates the Command window and the O>: 26.z prompt.
21.1.b: Example
If you enter
x = 1 / 0
at the O> prompt, O-Matrix will respond with an error message and ask whether to transfer control to the O> prompt ("Continue"), to the DEBUG>: 26.k
prompt ("Debug"), or to the help system ("Help").
If you transfer control to the DEBUG> prompt, O-Matrix will list the source line that caused the error. You can new exit the debugger by entering
q
which transfer control to the O> prompt.
21.2: Listing Included Files
Syntax
include
include: 3.8
Abbreviation
i
21.2.a: Description
This debugger command lists all of the files that have been included since the last clear: 3.2 command was executed.
21.2.b: Example
If at the O> prompt you enter
clear
include function\colsum.oms
stop
O-Matrix will activate the Debugger window. If you then enter
include
O-Matrix will respond
C:\OMWIN\AUTOEXEC.OMS
C:\TEMP\TMP1.OMS
C:\OMWIN\FUNCTION\COLSUM.OMS
C:\OMWIN\FUNCTION\ONES.OMS
The file autoexec.oms is automatically included after every clear command. The file tmp1.oms is a temporary file that O-Matrix uses to record input
from the command prompt. The file colsum.oms was included by the include command at the O> prompt. The file ones.oms was included by the file
colsum.oms. If you installed O-Matrix in a directory other than c:\omwin, that directory will appear in the list above. In addition, your temporary file
may be located in a different directory and it may have a different name.
21.3: Listing Active Variables in The Current Environment
Syntax
active
watch: 21.22 , env: 21.10 , dbprint: 21.17 , user: 21.21
Abbreviation
a
21.3.a: Description
Lists the variables and constants that are accessible in the current environment. This command also lists the attributes of all the variables and constants
that are visible in the current environment: 21.10 . The following table describes the attribute columns:
Name
matrix name
Type
matrix type
nr
number of rows in the matrix
nc
number of columns in the matrix
Function function that matrix is defined in
File
file that restricts function or matrix scope
21.3.b: Example
If at the O> prompt you enter
clear
u = 8
function f() begin
x = 1
const y = 4
stop
end
f
O-Matrix will activate the Debugger window. If you then enter
active
O-Matrix will respond
Name
.
.
.
x
y
Type
.
.
.
int
int
nr
.
.
.
1
1
nc
.
.
.
1
1
Function, File
.
.
.
f,
f,
where the vertical dots represent constants that are defined in autoexec.oms: 24.1 and are always visible. Note that u was not listed because it is not
currently visible inside of the function f. In addition, there is nothing listed in the File column because the function f is not local to a particular file.
(Note that the Function and File headings may not be visible unless you scroll the window to the right.)
If you continue this example by entering
env 1
active
O-Matrix will list the variables that are visible outside of the function f, namely
Name
.
.
.
u
Type
.
.
.
int
nr
.
.
.
1
nc
.
.
.
1
Function, File
.
.
.
,
Note that in the case of the variable u both the Function and File columns are empty because u is not restricted in scope to a particular function or file.
21.3.c: Watch Points
If you wish to set a watch: 21.22 point on a particular variable, you will have to reference the same name, function, and file as listed by the active
command.
21.4: Exiting The Debugger And Continuing Execution
Syntax
continue
step: 21.19 , next: 21.15
Abbreviation
c
21.4.a: Description
Exits the debugger and continues O-Matrix execution. This command cannot be used when the debugger is entered because of an error.
21.4.b: Example
If at the O>: 26.z prompt you enter
clear
for i = 1 to 2 begin
print i
stop
end
O-Matrix will respond
1
in the Command window and then activate the Debugger window and display the DEBUG>: 26.k prompt. If you then enter
continue
O-Matrix will respond
2
in the Command window and then activate the Debugger window and display the DEBUG>: 26.k prompt. If you then enter
continue
O-Matrix will activate the Command window and display the O>: 26.z prompt.
21.5: Deleting All Break and Watch Points
Syntax
dall
dwatch: 21.23 , dbreak: 21.8
Abbreviation da
21.5.a: Description
Deletes all the currently active debugger break and watch points.
21.5.b: Example
If the file temp.oms contains
and
clear
function fun(x) begin
y = 5
x = y^2
end
z = 7
fun(z)
at the DEBUG> prompt you enter
file temp.oms
O-Matrix will list the beginning lines of temp.oms in the debug window. If you then enter
break 4
break 2
break
O-Matrix will respond with the following list
index
1
2
skip
0
0
line
4
2
file
C:\OMWIN\TEMP.OMS
C:\OMWIN\TEMP.OMS
(Note that the break command with no arguments lists all the current break points.) If you continue by entering
dall
break
O-Matrix will respond
No breakpoints currently set
---------------------------------------------------------------------
21.6: Setting And Listing Debugger Break Points
Syntax
break
break
line
dbreak: 21.8 , skip: 21.7 , stop: 3.13 , continue: 21.4
Abbreviation
b
Menu Command Debug | Set Breakpoint . . .
Debug | List Breakpoints
21.6.a: Description
Sets a breakpoint (where execution will be suspended) at the specified line in the current debugger listing file. If line is not present in the command,
the current breakpoints are listed.
The hand icon in the toolbar: 2.5.6 , together with an editor window, can be used to make the setting of break points much easier.
21.6.b: Example
If the file TEMP.OMS in the current working directory contains
function fac(n) begin
if n==1 then return 1
return n * fac(n - 1)
end
and at the O>: 26.z prompt you enter
clear
stop
O-Matrix will activate the Debugger window and display the DEBUG>: 26.k prompt. If you then enter
file TEMP.OMS
O-Matrix will list the file TEMP.OMS with line numbers. If you enter
dall
break 2
break
O-Matrix will respond
index
1
skip
0
line
2
file
C:\OMWIN\TEMP.OMS
(the actual file name will depend on the current directory). If you continue by entering
continue
O-Matrix will activate the Command window and display the O>: 26.z prompt. If you continue by entering
include TEMP.OMS
fac(1)
O-Matrix will activate the Debugger window, with the arrow pointing to the second line of TEMP.OMS and a message identifying the index of the
debugger break point that caused it to stop. If you then enter
continue
O-Matrix will respond
1
which is the value of fac(1).
21.7: Skipping Breakpoints
Syntax
break index, skip
debugger break: 21.6
Debug | Skip Breakpoint . . .
21.7.a: Description
Sets the number of times to skip the breakpoint with the specified index.
21.7.b: Example
If the file TEMP.OMS in the current working directory contains
clear
function fac(n) begin
f = 1
for i = 1 to n begin
f = f * i
print i
end
return f
end
and at the DEBUG>: 26.k prompt you enter If you enter
file TEMP.OMS
list 1 7
O-Matrix will display the TEMP.OMS file with line number 5 corresponding to the statement f = f * i. If you enter
dall
break 5
break
O-Matrix will respond
index
1
skip
0
line
5
file
C:\OMWIN\TEMP.OMS
(the actual file name will depend on the current directory). Entering
break 1 3
will instruct O-Matrix to skip the breakpoint, with index one, three times. If you enter
continue
O-Matrix will activate the Command window and display the O>: 26.z prompt. If you continue with
include TEMP.OMS
print fac(5)
O-Matrix will print
1
2
3
in the Command window and then activate the Debugger window with the arrow pointing to the statement
f = f * i
and a message identifying the index of the breakpoint that caused it to stop. If you then enter
continue
O-Matrix will print
4
in the Command window and then stop. If you then enter
continue
O-Matrix will respond
5
120
in the Command window, because 120 is the value of fac(5).
21.8: Deleting Breakpoints
Syntax
dbreak
dbreak
index
dall: 21.5 , debugger break: 21.6
Abbreviation
d
Menu Command Debug | Delete Breakpoint . . .
Debug | List Breakpoints
21.8.a: Description
Deletes breakpoints. If index is not present, the current breakpoints are listed.
21.8.b: Example
If the file TEMP.OMS is in the current working directory and contains
function fac(n) begin
if n==1 then return 1
return n * fac(n - 1)
end
and at the DEBUG>: 26.k prompt you enter
file TEMP.OMS
O-Matrix will list the file TEMP.OMS with line numbers. If you enter
dall
break 2
break 3
break
O-Matrix will respond
index
1
2
skip
0
0
line
2
3
file
C:\OMWIN\TEMP.OMS
C:\OMWIN\TEMP.OMS
(the actual file name will depend on the current directory). If you continue by entering
dbreak 1
dbreak
O-Matrix will respond
index
skip
line
file
1
0
3
C:\OMWIN\TEMP.OMS
Note that after the first breakpoint was deleted, the index value of the second breakpoint was changed.
21.9: Setting Debugger Listing and Environment File
Syntax
file name
file
fprint
Abbreviation
environment: 21.10 and active: 21.3
fi
fp
Menu Command Debug | Set File . . .
Debug | Show File
21.9.a: Description
The file command, sets the current debugger listing file to the one specified by name. If name is not present, the listing file is set to the command line
input. The fprint command, prints the name of the current debugger listing file.
21.9.b: Example
If the file temp.oms in the current working directory contains
local x = 5
function factorial(n) begin
if n == 1 then return 1
return factorial(n - 1) * n
end
and at the DEBUG> prompt you enter
file temp.oms
O-Matrix will set the Debugger listing file as temp.oms and print the following lines from the beginning of the file.
1 local x = 5
2 function factorial(n) begin
3
if n == 1 then return 1
4
return factorial(n - 1) * n
5 end
(Note that the actual number of lines listed depends on the previous list: 21.14 command that set the number of listing lines.) Subsequent Debugger
listing commands refer to the specified file. If you then request a listing of two lines starting at line four by entering
list 4 2
O-Matrix will respond
4
return factorial(n - 1) * n
5 end
21.9.c: Active Variables
The file command also changes the file corresponding to active: 21.3 variables. This is useful for printing variables that are local to a file and not with
in any function. If you continue the example above by entering
quit
clear
include temp.oms
stop
active
The variable x will not be included in the active list.
file temp.oms
active
The variable x will be included in the active list.
If you then enter
21.10: Displaying The Environment Call Stack
Syntax
environment
environment number: 21.11
Abbreviation
e
Menu Command Debug | List Environment
21.10.a: Description
Lists the currently executing functions with corresponding line numbers and file names.
21.10.b: Example
If the file TEMP.OMS in the current working directory contains
clear
function f(x) begin
stop
end
function g(x) begin
f(2 * x)
end
and you enter
include TEMP.OMS
g(1)
O-Matrix will activate the debugger window. If you then enter
env
O-Matrix will respond
Currently Executing Environments
index function
line file
1
16
2 g
6 C:\OMWIN\TEMP.OMS
3 f
3 C:\OMWIN\TEMP.OMS
Current Debugger Environment Settings
index function
3 f
file
C:\OMWIN\TEMP.OMS
environment corresponds to the g(1) command and
The first executing
is not inside of any file or function. The line number for this entry may
depends on other commands you entered during this session. The second executing environment corresponds to the f(2 * x) statement in TEMP.OMS.
The third executing environment corresponds to the stop statement in TEMP.OMS. The current debugger environment settings determine which
function and file are used when listing and printing active: 21.3 variables.
21.11: Setting The Current Debugger Environment
Syntax
env index
env: 21.10
Abbreviation
e
Menu Command Debug | Set Environment . . .
21.11.a: Description
Sets the current environment and listing file within the debugger.
21.11.b: Example
If the file TEMP.OMS in the current working directory contains
clear
function f(x) begin
stop
end
function g(x) begin
f(2 * x)
end
and you enter
include TEMP.OMS
g(1)
O-Matrix will activate the debugger window. If you then enter
env
O-Matrix will respond
Currently Executing Environments
index function
line file
1
16
2 g
6 C:\OMWIN\TEMP.OMS
3 f
3 C:\OMWIN\TEMP.OMS
Current Debugger Environment Settings
index function
file
3 f
C:\OMWIN\TEMP.OMS
If you enter
env 2
O-Matrix will list the file TEMP.OMS with an arrow pointing to the currently executing line in the second environment. If you continue by entering
env
O-Matrix will respond
Currently Executing Environments
index function
line file
1
16
2 g
6 C:\OMWIN\TEMP.OMS
3 f
3 C:\OMWIN\TEMP.OMS
Current Debugger Environment Settings
index function
file
2 g
C:\OMWIN\TEMP.OMS
If you then enter
print x
O-Matrix will respond
1
because that is the value of x inside of the function g. If you enter
env 3
O-Matrix will list the file TEMP.OMS with an arrow pointing to the currently executing line in the third environment. If you continue by entering
print x
O-Matrix will respond
2
because that is the value of x inside of the function f.
21.12: Changing Output Format From Within the Debugger
Syntax
format
format
format
format
int form
real form
double from
complex form
debug printing: 21.17
Abbreviation fo
21.12.a: Description
Sets the output format for the corresponding type of matrices. This command has the same syntax and effect at the DEBUG> prompt as it does at the O>.
A more detailed description can be found in the format sections for integers: 8.17.2 and floating point: 8.17.3 values.
21.12.b: Example
If at the O> prompt you enter
clear
for i = 1 to 2 begin
print pi
if i == 1 then stop
end
O-Matrix will respond
3.14159
in the Command window and then activate the Debugger window. If you then enter
format real "f5.2"
print pi
O-Matrix will respond
3.14
in the Debugger window. If you then enter
continue
O-Matrix will respond
3.14
in the Command window.
21.12.c: Reference
The format command affects subsequent output in both the Debugger and Command windows.
21.13: Creating Global Variables From Temporary Ones
Syntax
global new variable = existing variable
global: 11.7 and print: 21.17
Abbreviation
g
Menu Command Debug | Global . . .
21.13.a: Description
Defines a new global variable and assigns it the current value of an existing variable. This makes the current value of the existing variable available
once control returns to the O>: 26.z prompt. (Some values are local to a specific environment: 21.10 and are not available when control returns to the
O> prompt.)
21.13.b: Example
If the file TEMP.OMS in the current working directory contains
and
clear
function f(x) begin
y = x^2
stop
end
f(seq(10))
at the O> prompt you enter
include TEMP.OMS
O-Matrix will activate the Debugger window with that arrow pointing to the stop statement. If you then enter
global z = y
continue
O-Matrix will return control to the O> prompt. If you then enter
gplot(z)
O-Matrix will plot the global variable z, which has the same value as the temporary variable y had at the stop statement.
21.14: Listing Lines In The Current Debugger File
Syntax
list
list
list
start
start, number
env: 21.10 , and file: 21.9
Abbreviation
l
21.14.a: Description
Lists the specified number of lines, starting at the specified line, in the current debugger listing file. If number is not present, the same number of lines
are listed as in the previous list command. If start is not present, the same starting line is used as in the previous listing for the current file.
(Whenever the current file changes, the starting line is set to the first line in the file.)
21.14.b: Example
If at the DEBUG>: 26.k prompt you enter
file autoexec.oms
O-Matrix will list the beginning of the AUTOEXEC.OMS file in the Debugger window. If you then enter
list 60, 10
O-Matrix will list lines 60 though 69 of the AUTOEXEC.OMS file. In addition, the debugger will include 10 lines in all subsequent listings until another
list command specifies the number of lines.
21.15: Stepping Over Function Calls
Syntax
next
step: 21.19 , trace: 21.20 and continue: 21.4
Abbreviation
n
21.15.a: Description
Executes one O-Matrix line in the current function, or main program, and lists the current file with an arrow pointing to the next execution line.
The lighting bolt icon in the toolbar: 2.5.6 can be used to execute the debugger next command.
21.15.b: Example
If you enter
clear
function f(x) begin
return 2 * x
end
for i = 1 to 3 begin
stop
print f(i)
end
O-Matrix will activate the Debugger window with the arrow pointing to the stop statement. If you then enter
next
O-Matrix will display an arrow pointing to the print statement. If you then enter
next
O-Matrix will print 2 (the value of f(1)) in the Command window and show the arrow pointing to the end statement in the Debugger window. Note
that if your last debugger command were step, instead of next, O-Matrix would have stopped inside the function f(x).
21.16: Determining What Files Are Open
Syntax
open
read: 8.3 , write: 8.10 , close: 8.13
Abbreviation
o
21.16.a: Description
prints a list of the files that are currently open. This includes O-Matrix source code files and temporary files created by O-Matrix.
21.16.b: Example
If at the O> prompt you enter
and
clear
write("junk.dat", 1)
then at the Debug> prompt you
open
enter
O-Matrix will respond
C:\OMWIN\JUNK.DAT
C:\TEMP\TMP40.OMS
Note that the directory containing junk.dat is the current directory and may not be c:\omwin . In addition, the file tmp40.oms is used for tracking
command line input and may be a completely different name when you run this example. If you continue at the O> prompt by entering
close
and then at the Debug> prompt you enter
open
O-Matrix will respond
C:\TEMP\TMP40.oms
21.17: Print Values Inside the Debugger
Syntax
name
name(i)
name(i,j)
active: 21.3
print
print
print
Abbreviation p
Menu Command Debug | Print ...
21.17.a: Description
Prints elements of the matrix name. If at the O> prompt you enter
and
x = {1, 2, 3}
y = {[1, 2], [3, 4]}
then at the Debug> prompt you
print x
enter
O-Matrix will respond
{
1
2
3
}
If you then enter
print x(3)
O-Matrix will respond
3
If you then enter
print y(2, 2)
O-Matrix will respond
4
21.17.b: Reference
The indices i and j in the syntax must be integer scalars; i.e., expressions are not supported. If the syntax print name(i) is used, the corresponding
matrix must be a vector.
The active: 21.3 command can be used to determine which variables can currently be printed.
21.18: Clearing the Debugger Window
Syntax
home
clc: 6.5.22
Abbreviation h
21.18.a: Description
Clears the Debugger window.
21.18.b: Example
If at the O> prompt you enter
x = seq(100)
x = x * x'
stop
O-Matrix will activate the Debugger window with the arrow pointing to the stop statement. If you then enter
print x
O-Matrix will fill the Debugger window with numbers. If you continue by entering
home
O-Matrix will clear the debugger window.
21.19: Stepping Into Function Calls
Syntax
step
next: 21.15 , trace: 21.20 and continue: 21.4
Abbreviation
s
21.19.a: Description
Executes on O-Matrix line and lists the current file with an arrow pointing to the next execution line.
21.19.b: Example
If you enter
clear
function f(x) begin
return 2 * x
end
for i = 1 to 3 begin
stop
f(i)
end
O-Matrix will activate the Debugger window with the arrow pointing to the stop statement. If you then enter
step
O-Matrix will display an arrow pointing to the f(x) statement. If you then enter
step
O-Matrix will show the arrow pointing to the function statement. Note that if your last debugger command were next, instead of step, O-Matrix
would not have stopped inside the function f(x).
21.20: Line By Line Tracing Of Execution
Syntax
flag
flag, file
step: 21.19 , next: 21.15 , list: 21.14
trace
trace
Abbreviation t
Menu Command Debug | Tracing . . .
21.20.a: Description
The value of flag can be on, off, or a decimal number of seconds. If flag is on, O-Matrix will trace execution in the Debugger window. If flag is off,
tracing is turned off. If flag is a decimal number, tracing is turned on and slowed so that the time in seconds between printing lines is equal to the
decimal number. If file is specified, only statements in that particular file are traced.
21.20.b: Example
If the file TEMP1.OMS in the current working directory contains
and
function f(x) begin
return x
end
the file TEMP2.OMS in contains
x = {1, 2, 3}
f(x)
and at the O>: 26.z prompt you enter
clear
include TEMP1.OMS
stop
and then at the DEBUG>: 26.k prompt enter
trace on
quit
and at the O>: 26.z prompt you enter
include TEMP2.OMS
O-Matrix will display the following in the Debugger window:
C:\OMWIN\TEMP2.OMS
1 x = {1, 2, 3}
2 f(x)
C:\OMWIN\TEMP1.OMS
1 function f(x) begin
2
return x
Note that O-Matrix prints the filename every time it changes. Also note that a blank line is printed when control returns to the command line.
If you continue this example by entering
trace on TEMP2.OMS
at the DEBUG>: 26.k prompt, followed by
include TEMP2.OMS
at the O>: 26.z prompt, O-Matrix will respond
1 x = {1, 2, 3}
2 f(x)
in the Debugger window. Note that none of the filenames are printed in this case because there is only one file being traced.
21.21: Listing The User Defined Functions
Syntax
user
active: 21.3
Abbreviation
u
21.21.a: Description
prints a list of the O-Matrix functions that are not intrinsic to the language.
21.21.b: Example
If at the O> prompt you enter
and
clear
include function\colsum.oms
then at the Debug> prompt you enter
user
O-Matrix will respond
Function, File
ones,
colsum,
the colsum file includes the ones
Because
within the specified file.
file. Note that if there were an entry in the File column, the corresponding function would only be available
21.22: Creating And Listing Watch Points
Syntax
watch
watch
watch
watch
watch
name
name, function
name, function, file
name, , file
dwatch: 21.23 , dall: 21.5
Abbreviation
wa
Menu Command Debug | SetWatchpoint . . .
Debug | ListWatchpoints
21.22.a: Description
If you set a watch on a variable, O-Matrix will suspend execution whenever that variable changes its values (unless that variable is the parameter in a
function definition). The command
watch
lists the variable watches that are currently set. The command
watch name
sets a watch on the variable with the specified name where the variable is not inside of any function nor is it local to any file. The command
watch name, function
sets a watch on the variable with the specified name with and in the specified function where function is not local to any file. The command
watch name, function, file
sets a watch on the variable with the specified name and with in the specified function where the function is local to the specified file. The command
watch name, , file
sets a watch on the variable with the specified name and that is local to the specified file where the variable is not inside of any function.
21.22.b: Example Without File Specification
If the current directory is c:\omwin\programs and the file temp1.oms contains
and
clear
function fun(x) begin
y = 5
x = y^2
end
z = 7
fun(z)
at the DEBUG> prompt you enter
watch y, fun
watch z
O-Matrix will set a watch on the variable y in the function fun and one the global variable z. If you then enter
watch
O-Matrix will respond with the following list
Index
1
2
Variable
y
z
If you quit the debugger and at
Function, File
fun,
,
the O> prompt you enter
include temp1.oms
O-Matrix will execute the program until it completes the assignment to z. It will then stop execution and activate the Debugger window with the arrow
pointing to the statement
z = 7
In addition, it will print the message
watch point: z, ,
If you then enter the command
print z
O-Matrix will respond
7
If you then enter the command
continue
O-Matrix will execute the program until it completes the assignment to y in the function fun. It will then stop execution and activate the Debugger
window with the arrow pointing to the statement
y = 5
In addition, it will print the message
watch point: y, fun,
If you then enter the commands
print y
O-Matrix will respond
5
which is the value that was assigned to y in the function fun.
21.22.c: Parameters
If a variable is a parameter with in a function, and the argument corresponding to the parameter is a variable; i.e., not an expression or a constant, you
must set a watch point on the argument in order to stop when the parameter changes. If you continue the example above by entering
continue
O-Matrix will stop execution with an arrow pointing to the statement
x = y^2
and it will print the message
watch point: z, ,
On the other hand, if you had deleted the watch point on z and set a watch point on the parameter x in the function fun above, O-Matrix would not
have stopped at the assignment
x = y^2
21.22.d: Example With File Specification
If the current directory is c:\omwin\programs and the file temp2.oms contains
and
clear
local function fun(x) begin
y = 5
x = y^2
end
local z = 7
fun(z)
at the DEBUG> prompt you enter
watch y, fun, temp2.oms
watch z, , temp2.oms
O-Matrix will set a watch on the variable y in the function fun and one the variable z in the file temp2.oms. If you then enter
watch
O-Matrix will respond with the following list
Index
1
2
Variable
y
z
If you quit the debugger and at
Function, File
fun, C:\OMWIN\PROGRAMS\TEMP2.OMS
, C:\OMWIN\PROGRAMS\TEMP2.OMS
the O> prompt you enter
include temp2.oms
O-Matrix will execute the program until it completes the assignment to z. It will then stop execution and activate the Debugger window with the arrow
pointing to the statement
local z = 7
In addition, it will print the message
watch point: z, , C:\OMWIN\PROGRAMS\TEMP2.OMS
If you then enter the command
print z
O-Matrix will respond
7
If you then enter the command
continue
O-Matrix will execute the program until it completes the assignment to y in the function fun. It will then stop execution and activate the Debugger
window with the arrow pointing to the statement
y = 5
In addition, it will print the message
watch point: y, fun, C:\OMWIN\PROGRAMS\TEMP2.OMS
If you then enter the commands
print y
O-Matrix will respond
5
which is the value that was assigned to y in the function fun.
21.23: Listing And Deleting Watch Points
Syntax
dwatch
dwatch
index
watch: 21.22 , dall: 21.5 , dbreak: 21.8
Abbreviation
dw
Menu Command Debug | Delete WatchPoint . . .
21.23.a: Description
If index is present, deletes the watch point that has the corresponding index. If index is not present, the current watch points are listed.
21.23.b: Example
If at the DEBUG> prompt you enter
watch y, fun
watch z
dwatch
O-Matrix will respond
Index
1
2
Variable
y
z
Function, File
fun,
,
If you continue by entering
dwatch 1
dwatch
O-Matrix will respond
Index
1
Variable
z
Function, File
,
If you continue by entering
dwatch 1
dwatch
O-Matrix will respond
no watch points to list
21.24: Determine What An Identifier Refers To
Syntax
which name
active: 21.3 , user: 21.21
Abbreviation
wh
21.24.a: Description
Searches the current environment to determine what the specified name refers to. O-Matrix and Mlmode keywords and intrinsic functions are checked
for as well as a variable with the specified name. In addition, the current O-Matrix path: 20.2 is searched for a file named name.oms.
21.24.b: Example
If you enter
which colsum
O-Matrix will respond
C:\OMWIN\FUNCTION\COLSUM.OMS
If on the other hand you enter
which PI
O-Matrix will respond
PI is a constant
22: Linking With Other Languages, Programs and COM Components
22.a: Contents
Using O-Matrix as a COM Automation Client: 22.1
The O-Matrix COM Server: 22.2
Creating O-Matrix DLL Functions: 22.3
Transferring Data To The System Clipboard: 22.4
Transferring Data From The System Clipboard: 22.5
Using DDE to Communicate with other Programs: 22.6
Creating an OMDDE Client: 22.7
Creating an OMDDE Server: 22.8
22.1: Using O-Matrix as a COM Automation Client
22.1.a: Description
O-Matrix provides functions to enable COM Automation scripting. These functions allow you to use O-Matrix as a scripting language for Office
applications such as Excel, Word and Access; Graphics applications such as SigmaPlot, Surfer, and Origin; Data Acquisition tools such as LabView;
And, proprietary server applications.
The O-Matrix automation functions are designed to simplify the use of COM Automation servers. Passing data to and from, and controlling
automation servers is much easier with the O-Matrix client functions than in Visual Basic, C++, and typical technical computing environments.
Operations such as passing the data of an O-Matrix solution to Excel and creating a plot can typically be performed with just a few lines of O-Matrix
code.
22.1.b: O-Matrix COM Automation Client Function Reference
cocreate: 22.1.1 Creating a Connection to a COM/Automation Server
cowith: 22.1.3
Setting a COM object
coendwith: 22.1.4 Releasing a COM object
coinvoke: 22.1.7 Invoking a COM Server Method
copropget: 22.1.6 Getting a Property of the Current COM object
copropput: 22.1.5 Setting a Property in the Current COM object
covariant: 22.1.8 Setting Variable as Variant
codispsave: 22.1.9 Saving a COM Server Dispatch Pointer
codispset: 22.1.10 Setting the IDispatch Pointer of a COM Object
costats: 22.1.11 Displaying the Status of a COM connection
corelease: 22.1.2 Releasing a COM/Automation Server Connection
22.1.c: O-Matrix Automation Samples
The omwin\example\automation directory of your distribution provides additional, more in depth examples of using the O-Matrix COM client
functions. The examples in the function reference use Excel since that application is common among O-Matrix users but the samples in the
automation directory give illustrations of using O-Matrix to automate other applications. The O-Matrix COM client functions may also be reviewed
and run by selecting the AUTOMATION category in the O-Matrix Example Navigator.
22.1.1: Creating a Connection to a COM/Automation Server
Syntax cocreate(server program ID)
cocreate
22.1.1.a: Description
Creates a connection to the COM automation server that is identified with the character row vector server program ID. If no argument is specified the
function returns a character row vector that identifies the currently connected server.
cocreate
O-Matrix may be connected to no more than one server at a time. If cocreate is called while a server is connected the current connection is released
before the new request is established. Calling the O-Matrix clear command will terminate all server connections.
22.1.1.b: Example
If at the command prompt you enter
cocreate("Excel.Application")
O-Matrix will initialize the Windows OLE/COM services and create a connection to the Excel Application object. If you continue the example above
by entering
cocreate
O-Matrix will respond
Excel.Application
If you continue the example by entering
cocreate("Word.Application")
cocreate
O-Matrix will respond
Word.Application
22.1.2: Releasing a COM/Automation Server Connection
Syntax corelease
22.1.2.a: Description
Release and frees allocated resources of the COM automation server that was connected by the most recent call to cocreate
22.1.3: Setting a COM object
Syntax cowith(object name)
cowith(object name, ObjectArg1)
cowith(object name, ObjectArg1, ObjectArg2)
cowith
22.1.3.a: Description
Sets the current object to be used by the coinvoke, copropget, and copropput functions. The character row vector object name specifies the object to
be referenced. If present, the arguments ObjectArg1 and ObjectArg2 may be an integer, real, or double-precision matrix, a logical scalar, or a character
row vector. The ObjectArg values are passed to object name when the object is retrieved.
If cowith is called without arguments the function returns an integer scalar which is the current depth in the object hierarchy. (That is the number of
times that cowith has been called for which there is not a corresponding coendwith call.)
Some automation servers expose their functionality in a hierarchy of objects. The property or method functionality you wish to access might be part of
a child object. In Visual Basic this hierarchy navigation is typically provided with the "dot" notation as in <parent object>.<child object> For
example, in Visual Basic you access the FileSystemObject through the parent Scripting object,
Set fileSystemObject = CreateObject("Scripting.FileSystemObject")
O-Matrix does not store handles to child objects but allows you to perform property and method operations relative to the current object. The O-Matrix
cowith and coendwith functions push and pop child objects of a hierarchy to enable navigation of automation objects models that are designed with a
nested hierarchy.
22.1.3.b: Examples
22.1.3.b.a: Referencing an Excel Object Without Arguments
The Excel Automation server defines an object hierarchy where Workbook and Worksheet objects are children of the Excel Application object. If at the
O-Matrix prompt you enter
clear
cocreate("Excel.Application") # Create connection to the Excel Automation server
copropput("Visible", 1) # Set the Visible property of .Application to make Excel visible
O-Matrix will start Excel and make it visible on the desktop. After the call to cocreate, Application is the current object, and
Visible is a property of
the Application object. If you continue the example by entering
cowith("Workbooks")
# Make the Excel.Application.Workbooks active
# call Add method of workbooks to create new Excel workbook
The call to cowith makes Workbooks, which is a child object of Application the current object.
22.1.3.b.b: Referencing an Excel Object That Requires Arguments
Child objects are often defined in automation servers as a property or method that requires an argument. (Often referred to as collections in Visual
Basic.) The cowith function can reference one of these objects by specifying up to two arguments.
Individual cells in Excel are accessed by referencing a Range object with the desired cell or cells as an argument to the Range reference. If at the OMatrix prompt you enter
clear
cocreate("Excel.Application")
copropput("Visible", 1)
cowith("Workbooks")
coendwith
O-Matrix will start Excel, make it visible, and add a new workbook to the Workbooks child object of the Application object. If you continue the
example by entering
cowith("Range", "A1")
O-Matrix will access the A1 cell of Workbooks child object, Range. You can verify that O-Matrix is now referencing the specified Range object by
entering
copropput("Value", 3)
which will display 3 in the first cell of Excel. If you wish to terminate Excel you need to navigate back up the Excel object hierarchy to the Excel
Application object. If you continue the previous example by entering
coendwith
# navigate up to Worksheet parent object
coendwith
# navigate up to Application object
coinvoke("Quit") # exit Excel
O-Matrix will navigate back to the root object of the Excel object hierarchy and exit the application.
22.1.4: Releasing a COM object
Syntax coendwith
22.1.4.a: Description
Changes the current object to the parent of the object that is referenced before calling coendwith.
22.1.4.b: Example
See the cowith manual entry for examples of using coendwith and cowith.
22.1.5: Setting a Property in the Current COM object
Syntax copropput( property name)
copropput( property name, property arguments)
22.1.5.a: Description
Sets a property value of the current object, specified by the character row vector, property name. The property specified by property name must be
defined in the currently active object. See the O-Matrix cowith and coendwith commands for a description of navigating automation server object
hierarchies.
The property arguments which are passed to the specified property name may be integer, real, or double-precision matrices, logical scalars, or
character row vectors.
22.1.5.b: Examples
If at the O-Matrix prompt you enter
cocreate("Excel.Application")
O-Matrix will start Excel. By default, the Excel automation server starts Excel as a background process without the user interface visible. If you wish
Excel to be visible you may continue the above example by entering
copropput("Visible", 1)
which sets the Excel.Application object property, Visible to 1.
22.1.6: Getting a Property of the Current COM object
Syntax copropget( property name)
copropget( property name, property arguments)
22.1.6.a: Description
Retrieves the value of a property in the current object specified by the character row vector property name. The specified property must exist in the
current object. See the O-Matrix cowith and coendwith functions for an explanation of navigating object model hierarchies. If present, property
arguments may be integer, real, or double precision matrices, logical scalars, or character row vectors. The values of method arguments are passed to
property name.
22.1.6.b: Examples
The caption that Excel displays is stored as a property in Excel' root object, Application. If, at the O-Matrix prompt you enter
clear
cocreate("Excel.Application")
print copropget("Caption")
coinvoke("Quit")
O-Matrix will respond
Microsoft Excel
which is the default application caption used by Excel.
22.1.7: Invoking a COM Server Method
Syntax coinvoke(method name)
coinvoke(method name, method arguments)
22.1.7.a: Description
Calls a method in the current object specified by the character row vector method name. The specified method must exist in the current object. See the
O-Matrix cowith and coendwith functions for an explanation of navigating object model hierarchies. If present, method arguments may be integer,
real, or double precision matrices, logical scalars, or character row vectors. The values of method arguments are passed to method name.
If the specified method name does not return a result, the result of coinvoke will be the O-Matrix constant novalue. If method name does return a
result, the value created by coinvoke will be an integer, real, or double precision matrix, a logical scalar, or character row vector.
22.1.7.b: Examples
22.1.7.b.a: A Method With Arguments That Returns a Result
The Excel Application object provides a method CentimetersToPoint to convert a scalar from centimeters to points. If, at the O-Matrix prompt you
enter
clear
cocreate("Excel.Application")
coinvoke("CentimetersToPoints", 5.5)
coinvoke("Quit")
O-Matrix will respond
155.906
22.1.7.b.b: A Method Without Arguments That Returns a Result
Some server methods do not require any data from the client and only perform an operation that returns a result If at the O-Matrix prompt you enter
clear
cocreate("Excel.Application")
fileName = coinvoke("GetSaveAsFileName")
Excel will post a dialog for entering a file name and after pressing OK your input result will be saved to the O-Matrix variable, fileName. If you
continue the example by entering
print fileName
O-Matrix will echo the name of the file that you entered in the dialog.
22.1.7.b.c: A Method That Does Not Return a Result
Some methods do not return a result and are used primarily for passing data to a server or for performing operations. The call to coinvoke("Quit") in
the example above does not return a result.
22.1.8: Setting Variable as Variant
Syntax covariant( methodName, argumentNumber)
covariant
22.1.8.a: Description
Specifies that argument number, argumentNumber to method methodName should be passed to the server as a VARIANT. The argument methodName
must be a character row vector which specifies a valid method name in the current object of the currently connected server. The argument
methodNumber must be an integer scalar greater than 0 and less than the number of arguments expected in the call to methodName.
By default, O-Matrix passes argument values to COM servers in the native type they are represented in by O-Matrix. Some servers expect arguments
as VARIANTS. The covariant function can be used to force arguments to the VARIANT type.
22.1.9: Saving a COM Server Dispatch Pointer
Syntax codispsave(object ID, object name)
22.1.9.a: Description
Saves the COM IDispatch pointer specified by the character row vector object name with the identifier specified by the character row vector object ID.
The value of object ID may be used in subsequent calls to codispset to set the IDispatch pointer value in other COM objects or servers.
22.1.9.b: Example
If at the command prompt you enter
clear
fileName = [OM_INSTALL, "\example\automation\craterlake.h5"]
O-Matrix will create a connection to the Array Viewer Avis.AvFileLoader object and load the sample data file craterlake.h5. The
Avis.AvFileLoader server contains objects which may be required by other Array Viewer objects. If you continue the example above by entering
codispsave("Avis.Root", "Root")
# save IDispatch* for Root object to ID Avis.Root
O-Matrix will save a reference to the Root IDispatch pointer with an identifier reference Avis.Root. This identifier can be used to set the saved
IDispatch pointer to an object in another server. If you continue the example above by entering
cocreate("ArrayViewer.Document")
codispset("RootGroup", "Avis.Root")
copropput("Visible", 1)
# Set ArrayViewer.Document.RootGroup to saved IDispatch
O-Matrix will create a new instance of the Array Viewer and set the IDispatch pointer of the Array Viewer RootGroup object to the value referenced
by Avis.Root.
22.1.10: Setting the IDispatch Pointer of a COM Object
Syntax codispset( object name, object ID)
22.1.10.a: Description
Sets the IDispatch pointer value of the object specified by the character row vector object name to the value of the pointer referenced by the character
row vector object ID. The value of object ID must be set by a previous call to codispsave.
22.1.11: Displaying the Status of a COM connection
Syntax costats( diagnostics)
costats
22.1.11.a: Description
If costats is called without any arguments O-Matrix displays status and diagnostic information about the current automation server connection that
was established by the most recent call to cocreate.
The logical-valued scalar diagnostics specifies whether the O-Matrix COM client functions should provide diagnostic information. By default the OMatrix COM client functions will display feedback information during execution. For example, some object methods might return a value that is not
supported by O-Matrix but the call is still successful in that the client only cares about the operation of the method.
22.2: The O-Matrix COM Server
22.2.a: Description
O-Matrix can be used as a Microsoft COM server from Visual Basic, C++, VBA, Java, .NET languages, Matlab, or any client that supports COM
interfacing.
When you install O-Matrix, the file devkit\OMServer.dll is registered on your system as COM component. Each client building tool has its own
method for recognizing and binding to COM type libraries. You can inspect the interfaces of the OMServer library in Excel by pressing Alt-F11 to
invoke the VBA editor. Open the 'Tools | References' dialog and one of the selections will be OMatrixServer X.X Type Library where XX is the current
version.
The O-Matrix COM server can also be used with the O-Matrix Development Kit (http://www.omatrix.com/omrte.html) to create stand-alone, turnkey
systems that can be distributed royalty-free.
In addition to the examples provided in this documentation there are numerous examples in VB script, VB, C++, C#, Java, and Matlab available in the
22.2.a.a: O-Matrix COM Server Function Reference
comstart: 22.2.1
Starting O-Matrix
comopen: 22.2.2
Create a Connection with an O-Matrix Server
comeval: 22.2.3
Evaluating an O-Matrix Expression
computdata: 22.2.4
Transfer a Data Array to O-Matrix
computmatrix: 22.2.5 Loading Data from the COM Server to an O-Matrix Variable
computvariant: 22.2.6 Transferring Variant Data to O-Matrix
comncols: 22.2.7
Determine the Number of Columns of a Transferred Matrix
comnrows: 22.2.8
Determine the Number of Rows of a Transferred Matrix
comgetmatrix: 22.2.9 Transfer O-Matrix Variables to the COM Server
comgetdata: 22.2.10 Transfer Data to an O-Matrix COM Server Client
comgetvariant: 22.2.11 Transfer Data to an O-Matrix COM Server Client
comisbusy: 22.2.12
Determining if O-Matrix is Busy
comtimeout: 22.2.13 Setting the O-Matrix Server Timeout Period
comclose: 22.2.14
Terminating a Connection with an O-Matrix Server
22.2.a.b: Diagnostics
comstatus: 22.2.15 Status Values Returned from the O-Matrix COM Server Functions
22.2.1: Starting O-Matrix
Syntax status = OMServer.Start( profileString)
22.2.1.a: Description
Start a new instance of O-Matrix or the O-Matrix Run-Time Engine. The character row vector profileString is the Windows profile string which
specifies the installation location for O-Matrix. The profile string is located in the [OMatrix] section of the WIN.INI file in the system directory,
(typically \windows). The profileString for O-Matrix is of the form StartupPath<version number>, and the profileString for the run-time engine is of
the form, StartupPath<version number>RTE. For example, on a machine that has O-Matrix version 5.81 installed, and version 5.81 of the run-time
engine installed, the WIN.INI file will contain a section that looks like
[OMatrix]
StartupPath5.81RTE=c:\omrte
StartupPath5.81=c:\omwin
The OMServer.Start method only
creates a new instance of O-Matrix or the O-Matrix run-time engine. The OMServer.Open: 22.2.2 method must be
called before your client application can communicate with O-Matrix.
The returned value status is an integer OM Server Status: 22.2.15 code. This value will equal 1 if this function succeeded.
22.2.1.b: Example
See the file StartOM.VBS in the COM\Scripts directory of your installation for examples of starting O-Matrix and the run-time engine.
22.2.2: Create a Connection with an O-Matrix Server
Syntax status = OMServer.Open
22.2.2.a: Description
Initialize the O-Matrix COM server and creates a connection to a running instance of O-Matrix. O-Matrix must be running before calling this function.
The returned value status is an integer OM Server Status: 22.2.15 code. This value will equal 1 if a connection was successfully established.
22.2.2.b: Example
Start Visual Basic and create a new project. Bind to the O-Matrix server type library by selecting OMatrixServer Type Library from the 'Project |
References' dialog. In the Project Properties dialog select Sub Main from the Startup Object field. Add a new module to the project and paste the
following code into the new module.
Public OM As New OMServer
Sub Main()
Dim status As Integer
status = OM.Open
If status = 1 Then
MsgBox ("Connection to O-Matrix established")
Else
MsgBox ("Unable to establish connection to O-Matrix")
End If
End Sub
Press the F5 key and your application will post a dialog displaying the connection status.
22.2.3: Evaluating an O-Matrix Expression
Syntax status = OMServer.Eval(command)
22.2.3.a: Description
Passes the argument command to O-Matrix for execution. The argument command must be a string that represents a valid O-Matrix expression. The
returned value status is an integer OM Server Status: 22.2.15 code. This value will equal 1 if this function succeeded.
22.2.3.b: Example
Start Visual Basic and create a new project. Bind to the O-Matrix server type library by selecting OMatrixServer Type Library from the 'Project |
References' dialog. In the Project Properties dialog select Sub Main from the Startup Object field. Add a new module to the project and paste the
following code into the new module.
Public OM As New OMServer
Sub Main()
Dim status As Integer
status = OM.Open
If status <> 1 Then
MsgBox ("Unable to establish connection to O-Matrix")
End If
status = OM.Eval("s =seq(3)^2")
If status = 1 Then
status = OM.Eval("gplot(s)")
End If
If status <> 1 Then
MsgBox ("Unable to execute O-Matrix command")
End If
End Sub
Run the project and O-Matrix will display a line plot of the exponential sequence s
22.2.4: Transfer a Data Array to O-Matrix
Syntax status = OMServer.PutData( arraySize,dataSrc,NRows,NCols)
22.2.4.a: Description
Transfers a data array to O-Matrix. The argument dataSrc must be a double-precision one-dimensional array containing values to transfer to O-Matrix.
The argument arraySize is a positive integer scalar specifying the number of elements in the dataSrc vector. The arguments NRows and NCols are
integer scalars specifying the number of rows and columns in the resultant O-Matrix matrix. Note that NRows*NCols must equal arraySize.
The returned value status is an integer OM Server Status: 22.2.15 code. This value will equal 1 if this function succeeded.
22.2.4.b: Example
Public OM As New OMServer
Sub Main()
Dim status As Integer
Dim omData(5) As Double
Dim ix As Integer
For ix = 0 To 5
omData(ix) = ix
Next ix
status = OM.Open
If status <> 1 Then
MsgBox ("Unable to establish connection to O-Matrix")
End If
status = OM.PutData(6, omData(0), 2, 3)
If status <> 1 Then
MsgBox ("Unable to transfer data to O-Matrix")
End If
End Sub
Press the F5 key to run the example.
This example creates a 6-element array, omData and passes this variable to O-Matrix as 2 row by 3 column matrix. You can verify that the data is
available in O-Matrix by entering
at the command line in O-Matrix. This will display the following result in the Command output window
{
[ 0 , 2 , 4 ]
[ 1 , 3 , 5 ]
}
Practical applications will typically call the PutMatrix: 22.2.5 immediately after calling the PutData function.
Syntax status = OMServer.PutMatrix( omVarName)
22.2.5.a: Description
Transfers the matrix stored in the COM server from a previous call to PutData to O-Matrix as the variable omVarName. The argument omVarName
must be a string value that is a valid O-Matrix identifier. If the variable omVarName is active in the currently connected O-Matrix, it will be overwritten
by this function call. All data transmitted to O-Matrix are transferred as double-precision scalars, vectors or two-dimensional matrices. For client
environments that do not support numeric COM data, see the OMServer.PutVariant: 22.2.6 method.
The returned value status is an integer OM Server Status: 22.2.15 code. This value will equal 1 if this function succeeded.
22.2.5.b: Example
This example continues the sample given in the PutData: 22.2.4 example.
Public OM As New OMServer
Sub Main()
Dim status As Integer
Dim omData(1, 2) As Double
Dim ix As Integer
Dim jx As Integer
For ix = 0 To 1
For jx = 0 To 2
omData(ix, jx) = ix + jx
Next jx
Next ix
status = OM.Open
If status <> 1 Then
MsgBox ("Unable to establish connection to O-Matrix")
End If
status = OM.PutData(6, omData(0, 0), 2, 3)
If status <> 1 Then
MsgBox ("Unable to transfer data to O-Matrix")
End If
status = OM.PutMatrix("omData")
If status <> 1 Then
MsgBox ("Unable to