.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "MATLAB 1p" .TH MATLAB 1p "2023-06-17" "perl v5.36.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" PDL::MATLAB \- A guide for MATLAB users. .SH "INTRODUCTION" .IX Header "INTRODUCTION" If you are a \s-1MATLAB\s0 user, this page is for you. It explains the key differences between \s-1MATLAB\s0 and \s-1PDL\s0 to help you get going as quickly as possible. .PP \&\fBThis document is not a tutorial\fR. For that, go to PDL::QuickStart. This document \fBcomplements\fR the Quick Start guide, as it highlights the key differences between \s-1MATLAB\s0 and \s-1PDL.\s0 .SH "Perl" .IX Header "Perl" The key differences between \s-1MATLAB\s0 and \s-1PDL\s0 are broadcasting, and \fBPerl\fR. .PP Broadcasting means you can get a reference to just a part of your data, and operate on it in a way that makes sense for your application. Those operations will be reflected in the original data. .PP Perl is a general purpose programming language with thousands of modules freely available on the web. \s-1PDL\s0 is an extension of Perl. This gives \s-1PDL\s0 programs access to more features than most numerical tools can dream of. At the same time, most syntax differences between \s-1MATLAB\s0 and \s-1PDL\s0 are a result of its Perl foundation. .PP \&\fBYou do not have to learn much Perl to be effective with \s-1PDL\s0\fR. But if you wish to learn Perl, there is excellent documentation available on-line () or through the command \f(CW\*(C`perldoc perl\*(C'\fR. There is also a beginner's portal (). .PP Perl's module repository is called \s-1CPAN\s0 () and it has a vast array of modules. Run \f(CW\*(C`perldoc cpan\*(C'\fR for more information. .SH "TERMINOLOGY: NDARRAY" .IX Header "TERMINOLOGY: NDARRAY" \&\s-1MATLAB\s0 typically refers to vectors, matrices, and arrays. Perl already has arrays, and the terms \*(L"vector\*(R" and \*(L"matrix\*(R" typically refer to one\- and two-dimensional collections of data. Having no good term to describe their object, \s-1PDL\s0 developers coined the term "\fIndarray\fR" to give a name to their data type. .PP An \fIndarray\fR consists of a series of numbers organized as an N\-dimensional data set. ndarrays provide efficient storage and fast computation of large N\-dimensional matrices. They are highly optimized for numerical work. .PP For more information, see "\fBndarrays vs Perl Arrays\fR" later in this document. .SH "COMMAND WINDOW AND IDE" .IX Header "COMMAND WINDOW AND IDE" Unlike \s-1MATLAB, PDL\s0 does not come with a dedicated \s-1IDE.\s0 It does however come with an interactive shell and you can use a Perl \s-1IDE\s0 to develop \&\s-1PDL\s0 programs. .SS "\s-1PDL\s0 interactive shell" .IX Subsection "PDL interactive shell" To start the interactive shell, open a terminal and run \f(CW\*(C`perldl\*(C'\fR or \f(CW\*(C`pdl2\*(C'\fR. As in \s-1MATLAB,\s0 the interactive shell is the best way to learn the language. To exit the shell, type \f(CW\*(C`exit\*(C'\fR, just like \s-1MATLAB.\s0 .SS "Writing \s-1PDL\s0 programs" .IX Subsection "Writing PDL programs" One popular \s-1IDE\s0 for Perl is called Padre (). It is cross platform and easy to use. .PP Whenever you write a stand-alone \s-1PDL\s0 program (i.e. outside the \&\f(CW\*(C`perldl\*(C'\fR or \f(CW\*(C`pdl2\*(C'\fR shell) you must start the program with \f(CW\*(C`use PDL;\*(C'\fR. This command imports the \s-1PDL\s0 module into Perl. Here is a sample \&\s-1PDL\s0 program: .PP .Vb 3 \& use PDL; # Import main PDL module. \& use PDL::NiceSlice; # Import additional PDL module. \& use PDL::AutoLoader; # Import additional PDL module. \& \& $y = pdl [2,3,4]; # Statements end in semicolon. \& $A = pdl [ [1,2,3],[4,5,6] ]; # 2\-dimensional matrix. \& \& print $A x $y\->transpose; .Ve .PP Save this file as \f(CW\*(C`myprogram.pl\*(C'\fR and run it with: .PP .Vb 1 \& perl myprogram.pl .Ve .SS "New: Flexible syntax" .IX Subsection "New: Flexible syntax" In current versions of \s-1PDL\s0 (version 2.4.7 or later) there is a flexible matrix syntax that can look extremely similar to \s-1MATLAB:\s0 .PP 1) Use spaces to separate elements: .PP .Vb 1 \& $y = pdl q[ 2 3 4 ]; .Ve .PP 2) Use a ';' to delimit rows: .PP .Vb 1 \& $A = pdl q[ 1,2,3 ; 4,5,6 ]; .Ve .PP Basically, as long as you put a \f(CW\*(C`q\*(C'\fR in front of the opening bracket, \&\s-1PDL\s0 should \*(L"do what you mean\*(R". So you can write in a syntax that is more comfortable for you. .SH "MODULES FOR MATLAB USERS" .IX Header "MODULES FOR MATLAB USERS" There are two modules that \s-1MATLAB\s0 users will want to use: .IP "PDL::NiceSlice" 5 .IX Item "PDL::NiceSlice" Gives \s-1PDL\s0 a syntax for slices (sub-matrices) that is shorter and more familiar to \s-1MATLAB\s0 users. .Sp .Vb 2 \& % MATLAB \& b(1:5) \-\-> Selects the first 5 elements from b. \& \& # PDL without NiceSlice \& $y\->slice("0:4") \-\-> Selects the first 5 elements from $y. \& \& # PDL with NiceSlice \& $y(0:4) \-\-> Selects the first 5 elements from $y. .Ve .IP "PDL::AutoLoader" 5 .IX Item "PDL::AutoLoader" Provides a MATLAB-style autoloader for \s-1PDL.\s0 If an unknown function \&\f(CW\*(C`foo()\*(C'\fR is called, \s-1PDL\s0 looks for a file called \f(CW\*(C`foo.pdl\*(C'\fR. If it finds one, it reads it. .SH "BASIC FEATURES" .IX Header "BASIC FEATURES" This section explains how \s-1PDL\s0's syntax differs from \s-1MATLAB.\s0 Most \&\s-1MATLAB\s0 users will want to start here. .ie n .SS "General ""gotchas""" .el .SS "General ``gotchas''" .IX Subsection "General gotchas" .IP "Indices" 5 .IX Item "Indices" In \s-1PDL,\s0 indices start at '0' (like C and Java), not 1 (like \s-1MATLAB\s0 or \s-1FORTRAN\s0). For example, if \f(CW$y\fR is an array with 5 elements, the elements would be numbered from 0 to 4. This is different, but less difficult as soon as you need to do calculations based on offsets. .IP "Displaying an object" 5 .IX Item "Displaying an object" \&\s-1MATLAB\s0 normally displays object contents automatically. In the \s-1PDL\s0 shells you display objects explicitly with the \f(CW\*(C`print\*(C'\fR command or the shortcut \f(CW\*(C`p\*(C'\fR: .Sp \&\s-1MATLAB:\s0 .Sp .Vb 4 \& >> a = 12 \& a = 12 \& >> b = 23; % Suppress output. \& >> .Ve .Sp \&\s-1PDL\s0 Shell (perldl or pdl2): .Sp .Vb 6 \& pdl> $x = 12 # No output. \& pdl> print $x # Print object. \& 12 \& pdl> p $x # "p" is a shorthand for "print" in the shell. \& 12 \& pdl> .Ve .Sp In pdl2 there is the \f(CW\*(C`do_print\*(C'\fR command that will toggle the \*(L"quiet\*(R" mode, which defaults to on. In \*(L"print\*(R" mode, expressions you enter on the command line will have their values printed. .SS "Creating ndarrays" .IX Subsection "Creating ndarrays" .IP "Variables in \s-1PDL\s0" 5 .IX Item "Variables in PDL" Variables always start with the '$' sign. .Sp .Vb 2 \& MATLAB: value = 42 \& PerlDL: $value = 42 .Ve .IP "Basic syntax" 5 .IX Item "Basic syntax" Use the \*(L"pdl\*(R" constructor to create a new \fIndarray\fR. .Sp .Vb 2 \& MATLAB: v = [1,2,3,4] \& PerlDL: $v = pdl [1,2,3,4] \& \& MATLAB: A = [ 1,2,3 ; 3,4,5 ] \& PerlDL: $A = pdl [ [1,2,3] , [3,4,5] ] .Ve .IP "Simple matrices" 5 .IX Item "Simple matrices" .Vb 6 \& MATLAB PDL \& \-\-\-\-\-\- \-\-\-\-\-\- \& Matrix of ones ones(5) ones 5,5 \& Matrix of zeros zeros(5) zeros 5,5 \& Random matrix rand(5) random 5,5 \& Linear vector 1:5 sequence 5 .Ve .Sp Notice that in \s-1PDL\s0 the parenthesis in a function call are often optional. It is important to keep an eye out for possible ambiguities. For example: .Sp .Vb 1 \& pdl> p zeros 2, 2 + 2 .Ve .Sp Should this be interpreted as \f(CW\*(C`zeros(2,2) + 2\*(C'\fR or as \f(CW\*(C`zeros 2, (2+2)\*(C'\fR? Both are valid statements: .Sp .Vb 12 \& pdl> p zeros(2,2) + 2 \& [ \& [2 2] \& [2 2] \& ] \& pdl> p zeros 2, (2+2) \& [ \& [0 0] \& [0 0] \& [0 0] \& [0 0] \& ] .Ve .Sp Rather than trying to memorize Perl's order of precedence, it is best to use parentheses to make your code unambiguous. Remember you may need to come back to your code, and parentheses make your own (as well as others') comprehension easier. .IP "Linearly spaced sequences" 5 .IX Item "Linearly spaced sequences" .Vb 2 \& MATLAB: >> linspace(2,10,5) \& ans = 2 4 6 8 10 \& \& PerlDL: pdl> p zeroes(5)\->xlinvals(2,10) \& [2 4 6 8 10] .Ve .Sp \&\fBExplanation\fR: Start with a 1\-dimensional ndarray of 5 elements and give it equally spaced values from 2 to 10. .Sp \&\s-1MATLAB\s0 has a single function call for this. On the other hand, \s-1PDL\s0's method is more flexible: .Sp .Vb 10 \& pdl> p zeros(5,5)\->xlinvals(2,10) \& [ \& [ 2 4 6 8 10] \& [ 2 4 6 8 10] \& [ 2 4 6 8 10] \& [ 2 4 6 8 10] \& [ 2 4 6 8 10] \& ] \& pdl> p zeros(5,5)\->ylinvals(2,10) \& [ \& [ 2 2 2 2 2] \& [ 4 4 4 4 4] \& [ 6 6 6 6 6] \& [ 8 8 8 8 8] \& [10 10 10 10 10] \& ] \& pdl> p zeros(3,3,3)\->zlinvals(2,6) \& [ \& [ \& [2 2 2] \& [2 2 2] \& [2 2 2] \& ] \& [ \& [4 4 4] \& [4 4 4] \& [4 4 4] \& ] \& [ \& [6 6 6] \& [6 6 6] \& [6 6 6] \& ] \& ] .Ve .IP "Slicing and indices" 5 .IX Item "Slicing and indices" Extracting a subset from a collection of data is known as \fIslicing\fR. \&\s-1PDL\s0 and \s-1MATLAB\s0 have a similar syntax for slicing, but there are two important differences: .Sp 1) \s-1PDL\s0 indices start at 0, as in C and Java. \s-1MATLAB\s0 starts indices at 1. .Sp 2) In \s-1MATLAB\s0 you think \*(L"rows and columns\*(R". In \s-1PDL,\s0 think \*(L"x and y\*(R". .Sp .Vb 10 \& MATLAB PerlDL \& \-\-\-\-\-\- \-\-\-\-\-\- \& >> A pdl> p $A \& A = [ \& 1 2 3 [1 2 3] \& 4 5 6 [4 5 6] \& 7 8 9 [7 8 9] \& ] \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \& (row = 2, col = 1) (x = 0, y = 1) \& >> A(2,1) pdl> p $A(0,1) \& ans = [ \& 4 [4] \& ] \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \& (row = 2 to 3, col = 1 to 2) (x = 0 to 1, y = 1 to 2) \& >> A(2:3,1:2) pdl> p $A(0:1,1:2) \& ans = [ \& 4 5 [4 5] \& 7 8 [7 8] \& ] .Ve .RS 5 .IP "\fBWarning\fR" 5 .IX Item "Warning" When you write a stand-alone \s-1PDL\s0 program, if you want the \*(L"nice slice\*(R" syntax, you have to include the PDL::NiceSlice module. See the previous section "\fB\s-1MODULES FOR MATLAB USERS\s0\fR" for more information. .Sp .Vb 3 \& use PDL; # Import main PDL module. \& use PDL::NiceSlice; # Nice syntax for slicing. \& use PDL::AutoLoader; # MATLAB\-like autoloader. \& \& $A = random 4,4; \& print $A(0,1); .Ve .RE .RS 5 .RE .SS "Matrix Operations" .IX Subsection "Matrix Operations" .IP "Matrix multiplication" 10 .IX Item "Matrix multiplication" .Vb 2 \& MATLAB: A * B \& PerlDL: $A x $B .Ve .IP "Element-wise multiplication" 10 .IX Item "Element-wise multiplication" .Vb 2 \& MATLAB: A .* B \& PerlDL: $A * $B .Ve .IP "Transpose" 10 .IX Item "Transpose" .Vb 2 \& MATLAB: A\*(Aq \& PerlDL: $A\->transpose .Ve .SS "Functions that aggregate data" .IX Subsection "Functions that aggregate data" Some functions (like \f(CW\*(C`sum\*(C'\fR, \f(CW\*(C`max\*(C'\fR and \f(CW\*(C`min\*(C'\fR) aggregate data for an N\-dimensional data set. This is a place where \s-1MATLAB\s0 and \&\s-1PDL\s0 take a different approach: .IP "In \s-1MATLAB,\s0 these functions all work along one dimension." 10 .IX Item "In MATLAB, these functions all work along one dimension." .Vb 7 \& >> A = [ 1,5,4 ; 4,2,1 ] \& A = 1 5 4 \& 4 2 1 \& >> max(A) \& ans = 4 5 4 \& >> max(A\*(Aq) \& ans = 5 4 .Ve .Sp If you want the maximum for the entire data set, you can use the special \&\f(CWA(:)\fR notation which basically turns the entire data set into a single 1\-dimensional vector. .Sp .Vb 5 \& >> max(A(:)) \& ans = 5 \& >> A = ones(2,2,2,2) \& >> max(A(:)) \& ans = 1 .Ve .IP "\s-1PDL\s0 offers two functions for each feature." 10 .IX Item "PDL offers two functions for each feature." .Vb 4 \& sum vs sumover \& avg vs average \& max vs maximum \& min vs minimum .Ve .Sp The \fBlong name\fR works over a dimension, while the \fBshort name\fR works over the entire ndarray. .Sp .Vb 10 \& pdl> p $A = pdl [ [1,5,4] , [4,2,1] ] \& [ \& [1 5 4] \& [4 2 1] \& ] \& pdl> p $A\->maximum \& [5 4] \& pdl> p $A\->transpose\->maximum \& [4 5 4] \& pdl> p $A\->max \& 5 \& pdl> p ones(2,2,2)\->max \& 1 \& pdl> p ones(2,2,2,2)\->max \& 1 .Ve .IP "\fBNote\fR" 5 .IX Item "Note" Notice that \s-1PDL\s0 aggregates horizontally while \s-1MATLAB\s0 aggregates vertically. In other words: .Sp .Vb 3 \& MATLAB PerlDL \& max(A) == $A\->transpose\->maximum \& max(A\*(Aq) == $A\->maximum .Ve .Sp \&\fB\s-1TIP\s0\fR: In \s-1MATLAB\s0 you think \*(L"rows and columns\*(R". In \s-1PDL,\s0 think \*(L"x and y\*(R". .SS "Higher dimensional data sets" .IX Subsection "Higher dimensional data sets" A related issue is how \s-1MATLAB\s0 and \s-1PDL\s0 understand data sets of higher dimension. \s-1MATLAB\s0 was designed for 1D vectors and 2D matrices. Higher dimensional objects (\*(L"N\-D arrays\*(R") were added on top. In contrast, \s-1PDL\s0 was designed for N\-dimensional ndarrays from the start. This leads to a few surprises in \s-1MATLAB\s0 that don't occur in \s-1PDL:\s0 .IP "\s-1MATLAB\s0 sees a vector as a 2D matrix." 5 .IX Item "MATLAB sees a vector as a 2D matrix." .Vb 5 \& MATLAB PerlDL \& \-\-\-\-\-\- \-\-\-\-\-\- \& >> vector = [1,2,3,4]; pdl> $vector = pdl [1,2,3,4] \& >> size(vector) pdl> p $vector\->dims \& ans = 1 4 4 .Ve .Sp \&\s-1MATLAB\s0 sees \f(CW\*(C`[1,2,3,4]\*(C'\fR as a 2D matrix (1x4 matrix). \s-1PDL\s0 sees it as a 1D vector: A single dimension of size 4. .IP "But \s-1MATLAB\s0 ignores the last dimension of a 4x1x1 matrix." 5 .IX Item "But MATLAB ignores the last dimension of a 4x1x1 matrix." .Vb 5 \& MATLAB PerlDL \& \-\-\-\-\-\- \-\-\-\-\-\- \& >> A = ones(4,1,1); pdl> $A = ones 4,1,1 \& >> size(A) pdl> p $A\->dims \& ans = 4 1 4 1 1 .Ve .IP "And \s-1MATLAB\s0 treats a 4x1x1 matrix differently from a 1x1x4 matrix." 5 .IX Item "And MATLAB treats a 4x1x1 matrix differently from a 1x1x4 matrix." .Vb 5 \& MATLAB PerlDL \& \-\-\-\-\-\- \-\-\-\-\-\- \& >> A = ones(1,1,4); pdl> $A = ones 1,1,4 \& >> size(A) pdl> p $A\->dims \& ans = 1 1 4 1 1 4 .Ve .IP "\s-1MATLAB\s0 has no direct syntax for N\-D arrays." 5 .IX Item "MATLAB has no direct syntax for N-D arrays." .Vb 3 \& pdl> $A = pdl [ [[1,2,3],[4,5,6]], [[2,3,4],[5,6,7]] ] \& pdl> p $A\->dims \& 3 2 2 .Ve .IP "Feature support." 5 .IX Item "Feature support." In \s-1MATLAB,\s0 several features such as sparse matrix support are not available for N\-D arrays. In \s-1PDL,\s0 just about any feature supported by 1D and 2D ndarrays, is equally supported by N\-dimensional ndarrays. There is usually no distinction. .SS "Loop Structures" .IX Subsection "Loop Structures" Perl has many loop structures, but we will only show the one that is most familiar to \s-1MATLAB\s0 users: .PP .Vb 5 \& MATLAB PerlDL \& \-\-\-\-\-\- \-\-\-\-\-\- \& for i = 1:10 for $i (1..10) { \& disp(i) print $i \& endfor } .Ve .IP "\fBNote\fR" 5 .IX Item "Note" Never use for-loops for numerical work. Perl's for-loops are faster than \s-1MATLAB\s0's, but they both pale against a \*(L"vectorized\*(R" operation. \&\s-1PDL\s0 has many tools that facilitate writing vectorized programs. These are beyond the scope of this guide. To learn more, see: PDL::Indexing, PDL::Broadcasting, and \s-1PDL::PP\s0. .Sp Likewise, never use \f(CW1..10\fR for numerical work, even outside a for-loop. \&\f(CW1..10\fR is a Perl array. Perl arrays are designed for flexibility, not speed. Use \fIndarrays\fR instead. To learn more, see the next section. .SS "ndarrays vs Perl Arrays" .IX Subsection "ndarrays vs Perl Arrays" It is important to note the difference between an \fIndarray\fR and a Perl array. Perl has a general-purpose array object that can hold any type of element: .PP .Vb 3 \& @perl_array = 1..10; \& @perl_array = ( 12, "Hello" ); \& @perl_array = ( 1, 2, 3, \e@another_perl_array, sequence(5) ); .Ve .PP Perl arrays allow you to create powerful data structures (see \&\fBData structures\fR below), \fBbut they are not designed for numerical work\fR. For that, use \fIndarrays\fR: .PP .Vb 3 \& $pdl = pdl [ 1, 2, 3, 4 ]; \& $pdl = sequence 10_000_000; \& $pdl = ones 600, 600; .Ve .PP For example: .PP .Vb 2 \& $points = pdl 1..10_000_000 # 4.7 seconds \& $points = sequence 10_000_000 # milliseconds .Ve .PP \&\fB\s-1TIP\s0\fR: You can use underscores in numbers (\f(CW\*(C`10_000_000\*(C'\fR reads better than \f(CW10000000\fR). .SS "Conditionals" .IX Subsection "Conditionals" Perl has many conditionals, but we will only show the one that is most familiar to \s-1MATLAB\s0 users: .PP .Vb 9 \& MATLAB PerlDL \& \-\-\-\-\-\- \-\-\-\-\-\- \& if value > MAX if ($value > $MAX) { \& disp("Too large") print "Too large\en"; \& elseif value < MIN } elsif ($value < $MIN) { \& disp("Too small") print "Too small\en"; \& else } else { \& disp("Perfect!") print "Perfect!\en"; \& end } .Ve .IP "\fBNote\fR" 5 .IX Item "Note" Here is a \*(L"gotcha\*(R": .Sp .Vb 2 \& MATLAB: elseif \& PerlDL: elsif .Ve .Sp If your conditional gives a syntax error, check that you wrote your \f(CW\*(C`elsif\*(C'\fR's correctly. .SS "\s-1TIMTOWDI\s0 (There Is More Than One Way To Do It)" .IX Subsection "TIMTOWDI (There Is More Than One Way To Do It)" One of the most interesting differences between \s-1PDL\s0 and other tools is the expressiveness of the Perl language. \s-1TIMTOWDI,\s0 or \*(L"There Is More Than One Way To Do It\*(R", is Perl's motto. .PP Perl was written by a linguist, and one of its defining properties is that statements can be formulated in different ways to give the language a more natural feel. For example, you are unlikely to say to a friend: .PP .Vb 1 \& "While I am not finished, I will keep working." .Ve .PP Human language is more flexible than that. Instead, you are more likely to say: .PP .Vb 1 \& "I will keep working until I am finished." .Ve .PP Owing to its linguistic roots, Perl is the only programming language with this sort of flexibility. For example, Perl has traditional while-loops and if-statements: .PP .Vb 3 \& while ( ! finished() ) { \& keep_working(); \& } \& \& if ( ! wife_angry() ) { \& kiss_wife(); \& } .Ve .PP But it also offers the alternative \fBuntil\fR and \fBunless\fR statements: .PP .Vb 3 \& until ( finished() ) { \& keep_working(); \& } \& \& unless ( wife_angry() ) { \& kiss_wife(); \& } .Ve .PP And Perl allows you to write loops and conditionals in \*(L"postfix\*(R" form: .PP .Vb 1 \& keep_working() until finished(); \& \& kiss_wife() unless wife_angry(); .Ve .PP In this way, Perl often allows you to write more natural, easy to understand code than is possible in more restrictive programming languages. .SS "Functions" .IX Subsection "Functions" \&\s-1PDL\s0's syntax for declaring functions differs significantly from \s-1MATLAB\s0's. .PP .Vb 6 \& MATLAB PerlDL \& \-\-\-\-\-\- \-\-\-\-\-\- \& function retval = foo(x,y) sub foo { \& retval = x.**2 + x.*y my ($x, $y) = @_; \& endfunction return $x**2 + $x*$y; \& } .Ve .PP Don't be intimidated by all the new syntax. Here is a quick run through a function declaration in \s-1PDL:\s0 .PP 1) "\fBsub\fR\*(L" stands for \*(R"subroutine". .PP 2) "\fBmy\fR" declares variables to be local to the function. This helps you not accidentally use undeclared variables, which is enforced if you \&\f(CW\*(C`use strict\*(C'\fR. See strict for more. .PP 3) "\fB\f(CB@_\fB\fR" is a special Perl array that holds all the function parameters. This might seem like a strange way to do functions, but it allows you to make functions that take a variable number of parameters. For example, the following function takes any number of parameters and adds them together: .PP .Vb 7 \& sub mysum { \& my ($i, $total) = (0, 0); \& for $i (@_) { \& $total += $i; \& } \& return $total; \& } .Ve .PP In more recent versions of Perl, you can \f(CW\*(C`use signatures\*(C'\fR for a different syntax for declaring function parameters. See signatures for more. .PP 4) You can assign values to several variables at once using the syntax: .PP .Vb 1 \& ($x, $y, $z) = (1, 2, 3); .Ve .PP So, in the previous examples: .PP .Vb 2 \& # This declares two local variables and initializes them to 0. \& my ($i, $total) = (0, 0); \& \& # This takes the first two elements of @_ and puts them in $x and $y. \& my ($x, $y) = @_; .Ve .PP 5) The "\fBreturn\fR" statement gives the return value of the function, if any. .SH "ADDITIONAL FEATURES" .IX Header "ADDITIONAL FEATURES" .SS "\s-1ASCII\s0 File \s-1IO\s0" .IX Subsection "ASCII File IO" To read data files containing whitespace separated columns of numbers (as would be read using the \s-1MATLAB\s0 \fIload\fR command) one uses the \s-1PDL\s0 \fIrcols\fR in PDL::IO::Misc. For a general review of the \s-1IO\s0 functionality available in \s-1PDL,\s0 see the documentation for \s-1PDL::IO\s0, e.g., \f(CW\*(C`help PDL::IO\*(C'\fR in the \fIpdl2\fR shell or \f(CW\*(C` pdldoc PDL::IO \*(C'\fR from the shell command line. .SS "Data structures" .IX Subsection "Data structures" To create complex data structures, \s-1MATLAB\s0 uses "\fIcell arrays\fR\*(L" and \&\*(R"\fIstructure arrays\fR". Perl's arrays and hashes offer similar functionality but are more powerful and flexible. This section is only a quick overview of what Perl has to offer. To learn more about this, please go to or run the command \f(CW\*(C`perldoc perldata\*(C'\fR. .IP "Arrays" 5 .IX Item "Arrays" Perl arrays are similar to \s-1MATLAB\s0's cell arrays, but more flexible. For example, in \s-1MATLAB,\s0 a cell array is still fundamentally a matrix. It is made of rows, and rows must have the same length. .Sp .Vb 6 \& MATLAB \& \-\-\-\-\-\- \& array = {1, 12, \*(Aqhello\*(Aq; rand(3, 2), ones(3), \*(Aqjunk\*(Aq} \& => OK \& array = {1, 12, \*(Aqhello\*(Aq; rand(3, 2), ones(3) } \& => ERROR .Ve .Sp A Perl array is a general purpose, sequential data structure. It can contain any data type. .Sp .Vb 8 \& PerlDL \& \-\-\-\-\-\- \& @array = ( [1, 12, \*(Aqhello\*(Aq] , [ random(3,2), ones(3,3), \*(Aqjunk\*(Aq ] ) \& => OK \& @array = ( [1, 12, \*(Aqhello\*(Aq] , [ random(3,2), ones(3,3) ] ) \& => OK \& @array = ( 5 , {\*(Aqname\*(Aq => \*(AqMike\*(Aq} , [1, 12, \*(Aqhello\*(Aq] ) \& => OK .Ve .Sp Notice that Perl array's start with the \*(L"@\*(R" prefix instead of the \*(L"$\*(R" used by ndarrays. .Sp \&\fITo learn about Perl arrays, please go to or run the command \f(CI\*(C`perldoc perldata\*(C'\fI.\fR .IP "Hashes" 5 .IX Item "Hashes" Perl hashes are similar to \s-1MATLAB\s0's structure arrays: .Sp .Vb 5 \& MATLAB \& \-\-\-\-\-\- \& >> drink = struct(\*(Aqtype\*(Aq, \*(Aqcoke\*(Aq, \*(Aqsize\*(Aq, \*(Aqlarge\*(Aq, \*(Aqmyarray\*(Aq, {1,2,3}) \& >> drink.type = \*(Aqsprite\*(Aq \& >> drink.price = 12 % Add new field to structure array. \& \& PerlDL \& \-\-\-\-\-\- \& pdl> %drink = ( type => \*(Aqcoke\*(Aq , size => \*(Aqlarge\*(Aq, myndarray => ones(3,3,3) ) \& pdl> $drink{type} = \*(Aqsprite\*(Aq \& pdl> $drink{price} = 12 # Add new field to hash. .Ve .Sp Notice that Perl hashes start with the \*(L"%\*(R" prefix instead of the \*(L"@\*(R" for arrays and \*(L"$\*(R" used by ndarrays. .Sp \&\fITo learn about Perl hashes, please go to or run the command \f(CI\*(C`perldoc perldata\*(C'\fI.\fR .SS "Performance" .IX Subsection "Performance" \&\s-1PDL\s0 has powerful performance features, some of which are not normally available in numerical computation tools. The following pages will guide you through these features: .IP "PDL::Indexing" 5 .IX Item "PDL::Indexing" \&\fBLevel\fR: Beginner .Sp This beginner tutorial covers the standard \*(L"vectorization\*(R" feature that you already know from \s-1MATLAB.\s0 Use this page to learn how to avoid for-loops to make your program more efficient. .IP "PDL::Broadcasting" 5 .IX Item "PDL::Broadcasting" \&\fBLevel\fR: Intermediate .Sp \&\s-1PDL\s0's \*(L"vectorization\*(R" feature goes beyond what most numerical software can do. In this tutorial you'll learn how to \*(L"broadcast\*(R" over higher dimensions, allowing you to vectorize your program further than is possible in \s-1MATLAB.\s0 .IP "Benchmarks" 5 .IX Item "Benchmarks" \&\fBLevel\fR: Intermediate .Sp Perl comes with an easy to use benchmarks module to help you find how long it takes to execute different parts of your code. It is a great tool to help you focus your optimization efforts. You can read about it online () or through the command \f(CW\*(C`perldoc Benchmark\*(C'\fR. .IP "\s-1PDL::PP\s0" 5 .IX Item "PDL::PP" \&\fBLevel\fR: Advanced .Sp \&\s-1PDL\s0's Pre-Processor is one of \s-1PDL\s0's most powerful features. You write a function definition in special markup and the pre-processor generates real C code which can be compiled. With \s-1PDL:PP\s0 you get the full speed of native C code without having to deal with the full complexity of the C language. .SS "Plotting" .IX Subsection "Plotting" \&\s-1PDL\s0 has full-featured plotting abilities. Unlike \s-1MATLAB, PDL\s0 relies more on third-party libraries (pgplot and PLplot) for its 2D plotting features. Its 3D plotting and graphics uses OpenGL for performance and portability. \&\s-1PDL\s0 has three main plotting modules: .IP "PDL::Graphics::PGPLOT" 5 .IX Item "PDL::Graphics::PGPLOT" \&\fBBest for\fR: Plotting 2D functions and data sets. .Sp This is an interface to the venerable \s-1PGPLOT\s0 library. \s-1PGPLOT\s0 has been widely used in the academic and scientific communities for many years. In part because of its age, \s-1PGPLOT\s0 has some limitations compared to newer packages such as PLplot (e.g. no \s-1RGB\s0 graphics). But it has many features that still make it popular in the scientific community. .IP "PDL::Graphics::PLplot" 5 .IX Item "PDL::Graphics::PLplot" \&\fBBest for\fR: Plotting 2D functions as well as 2D and 3D data sets. .Sp This is an interface to the PLplot plotting library. PLplot is a modern, open source library for making scientific plots. It supports plots of both 2D and 3D data sets. PLplot is best supported for unix/linux/macosx platforms. It has an active developers community and support for win32 platforms is improving. .IP "PDL::Graphics::TriD" 5 .IX Item "PDL::Graphics::TriD" \&\fBBest for\fR: Plotting 3D functions. .Sp The native \s-1PDL 3D\s0 graphics library using OpenGL as a backend for 3D plots and data visualization. With OpenGL, it is easy to manipulate the resulting 3D objects with the mouse in real time. .SS "Writing GUIs" .IX Subsection "Writing GUIs" Through Perl, \s-1PDL\s0 has access to all the major toolkits for creating a cross platform graphical user interface. One popular option is wxPerl (). These are the Perl bindings for wxWidgets, a powerful \s-1GUI\s0 toolkit for writing cross-platform applications. .PP wxWidgets is designed to make your application look and feel like a native application in every platform. For example, the Perl \&\s-1IDE\s0 \fBPadre\fR is written with wxPerl. .SS "Simulink" .IX Subsection "Simulink" Simulink is a graphical dynamical system modeler and simulator. It can be purchased separately as an add-on to \s-1MATLAB. PDL\s0 and Perl do not have a direct equivalent to \s-1MATLAB\s0's Simulink. If this feature is important to you, then take a look at \fBScilab\fR: .PP .PP Scilab is another numerical analysis software. Like \s-1PDL,\s0 it is free and open source. It doesn't have \s-1PDL\s0's unique features, but it is very similar to \s-1MATLAB.\s0 Scilab comes with \fBXcos\fR (previously Scicos), a graphical system modeler and simulator similar to Simulink. .SH "COMPARISON: REPEATED COPY OF MATRIX" .IX Header "COMPARISON: REPEATED COPY OF MATRIX" In \s-1MATLAB,\s0 the \f(CW\*(C`repmat\*(C'\fR function works like so: .PP .Vb 10 \& > A = reshape(0:5, 3, 2)\*(Aq # similar to PDL::sequence(3, 2) \& ans = \& 0 1 2 \& 3 4 5 \& > repmat(A, 2, 3) # double rows, triple columns \& ans = \& 0 1 2 0 1 2 0 1 2 \& 3 4 5 3 4 5 3 4 5 \& 0 1 2 0 1 2 0 1 2 \& 3 4 5 3 4 5 3 4 5 .Ve .PP This works (at least in Octave) at least up to 3 dimensions. .PP The \s-1PDL\s0 analog: .PP .Vb 10 \& sub repmat { \& my $f=shift; \& my @n=@_; #number of repetitions along dimension \& my $sl = join \*(Aq,\*(Aq, map ":,*$_", @n; # insert right\-size dummy after each real \& my $r = $f\->slice($sl); #result \& $r = $r\->clump($_, $_+1) for 0..$#n; \& $r; \& } \& > p $x = sequence(3,2) \& [ \& [0 1 2] \& [3 4 5] \& ] \& > p repmat($x, 3, 2) # triple columns, double rows \& [ \& [0 1 2 0 1 2 0 1 2] \& [3 4 5 3 4 5 3 4 5] \& [0 1 2 0 1 2 0 1 2] \& [3 4 5 3 4 5 3 4 5] \& ] .Ve .SH "COMPARISON: FLOYD-WARSHALL ALGORITHM" .IX Header "COMPARISON: FLOYD-WARSHALL ALGORITHM" In graph theory , an apparently-simple but difficult problem is the \*(L"shortest path\*(R" problem, of finding the shortest path between any two nodes. A famous solution to this, albeit expensive (it is \f(CW\*(C`O(V^3)\*(C'\fR where \f(CW\*(C`V\*(C'\fR is the number of vertices) is the Floyd-Warshall algorithm, which iterates through all the possible paths. .PP Both the \s-1MATLAB\s0 solution and the \s-1PDL\s0 solution use vectorisation, so hopefully this is a useful comparison. The \s-1MATLAB\s0 version started with the code in code by Giorgos Dim , but modified as that code produces an incorrect path matrix. .PP Sample data (reflected on both the Wikipedia page, and the Rosetta Code website) for the weighted-edges matrix is, in \s-1PDL\s0 format: .PP .Vb 6 \& my $we = pdl q[ \& [Inf Inf \-2 Inf] \& [ 4 Inf 3 Inf] \& [Inf Inf Inf 2] \& [Inf \-1 Inf Inf] \& ]; .Ve .PP and in \s-1MATLAB\s0 format: .PP .Vb 1 \& A = [0 Inf \-2 Inf; 4 0 3 Inf; Inf Inf 0 2; Inf \-1 Inf 0] .Ve .SS "\s-1PDL\s0 version" .IX Subsection "PDL version" To solve for only distances without capturing the shortest actual paths: .PP .Vb 2 \& $we .= $we\->hclip($we\->mslice(\*(AqX\*(Aq, $_) + $we\->mslice($_, \*(AqX\*(Aq)) \& for 0..($we\->dim(0)\-1); .Ve .PP This loops over each possible intermediate point (\f(CW\*(C`k\*(C'\fR in the other literature), setting it to \f(CW$_\fR (a Perl idiom). It uses \&\*(L"hclip\*(R" in PDL::Primitive for vectorised calculation of the distance between the intermediate point's predecessors and successors. Those are the two components of the addition expression, using \*(L"slices\*(R" alluded to above. The \f(CW\*(C`.=\*(C'\fR is the \s-1PDL\s0 syntax for updating an ndarray. .PP To capture the shortest-path \*(L"next vertex\*(R" matrix as well: .PP .Vb 10 \& use PDL::Lite; \& my $d = $we\->copy\->inplace; \& $d\->diagonal(0, 1) .= 0; \& my $suc = $we\->copy\->inplace; \& my $adjacent_coords = PDL::whichND($we\->isfinite); \& $suc\->indexND($adjacent_coords) .= $adjacent_coords\->slice(0)\->flat; \& $suc\->diagonal(0, 1) .= PDL::Basic::sequence($d\->dim(0)); \& for (my $k = $d\->dim(0)\-1; $k >= 0; $k\-\-) { \& my $d_copy = $d\->copy; \& $d .= $d\->hclip($d\->mslice(\*(AqX\*(Aq, $k) + $d\->mslice($k, \*(AqX\*(Aq)); \& my $coords = PDL::whichND($d < $d_copy); \& my $from_coords = $coords\->copy\->inplace; \& $from_coords\->slice(0) .= $k; \& $suc\->indexND($coords) .= $suc\->indexND($from_coords); \& } .Ve .PP The \f(CW\*(C`diagonal\*(C'\fR and \f(CW\*(C`slice\*(C'\fR expressions show how to update data via a query syntax. .SS "\s-1MATLAB\s0 version" .IX Subsection "MATLAB version" Path-lengths only: .PP .Vb 5 \& function D = FloydWarshall(D) \& for k = 1:length(D) \& D = min(D,D(:,k) + D(k,:)); \& end \& end .Ve .PP The path vertices-capturing as well: .PP .Vb 10 \& function [D,P] = FloydWarshall(D) \& P = D; \& n = length(D); \& coords = find(isfinite(P)); \& P(coords) = floor((coords\-1) / n)+1; % the col in 1\-based \& for v = 1:n; P(v, v) = v; end \& for k = 1:n \& prevD = D; \& D = min(D,D(:,k) + D(k,:)); \& coords = find(D .SH "ACKNOWLEDGEMENTS" .IX Header "ACKNOWLEDGEMENTS" I'd like to thank David Mertens, Chris Marshall and Sigrid Carrera for their immense help reviewing earlier drafts of this guide. Without their hours of work, this document would not be remotely as useful to \s-1MATLAB\s0 users as it is today.