MATLAB(1)
โจ NAME โจ
okay bestie, welcome to MATLAB(1) from the User Contributed Perl Documentation corner of the universe ๐ซถ. The actual page name is PDL::MATLAB โ A guide for MATLAB users.
๐ INTRODUCTION ๐
If you're a MATLAB user, this page is literally for you. It explains the key differences between MATLAB and PDL so you can get going as quickly as possible. No cap.
This document is not a tutorial. For that, go to PDL::QuickStart. This document complements the Quick Start guide, as it highlights the key differences between MATLAB and PDL. โจ
๐ป Perl ๐ป
The key differences between MATLAB and PDL are broadcasting and Perl.
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. It's giving "touch the original, not a copy" energy ๐ .
Perl is a general purpose programming language with thousands of modules freely available on the web. PDL is an extension of Perl. This gives PDL programs access to more features than most numerical tools can dream of. At the same time, most syntax differences between MATLAB and PDL are a result of its Perl foundation.
You do not have to learn much Perl to be effective with PDL. But if you wish to learn Perl, there is excellent documentation available on-line (<http://perldoc.perl.org>) or through the command perldoc perl. There is also a beginner's portal (<http://perl-begin.org>).
Perl's module repository is called CPAN (<http://www.cpan.org>) and it has a vast array of modules. Run perldoc cpan for more information.
๐ง TERMINOLOGY: NDARRAY ๐ง
MATLAB typically refers to vectors, matrices, and arrays. Perl already has arrays, and the terms "vector" and "matrix" typically refer to one- and two-dimensional collections of data. Having no good term to describe their object, PDL developers coined the term "ndarray" to give a name to their data type.
An ndarray 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. Iconic behavior, honestly ๐ฅ.
For more information, see "ndarrays vs Perl Arrays" later in this document.
๐ฅ๏ธ COMMAND WINDOW AND IDE ๐ฅ๏ธ
Unlike MATLAB, PDL does not come with a dedicated IDE. It does however come with an interactive shell and you can use a Perl IDE to develop PDL programs.
๐ PDL interactive shell ๐
To start the interactive shell, open a terminal and run perldl or pdl2. As in MATLAB, the interactive shell is the best way to learn the language. To exit the shell, type exit, just like MATLAB.
โ๏ธ Writing PDL programs โ๏ธ
One popular IDE for Perl is called Padre (<http://padre.perlide.org>). It is cross platform and easy to use.
Whenever you write a stand-alone PDL program (i.e. outside the perldl or pdl2 shell) you must start the program with use PDL;. This command imports the PDL module into Perl. Here is a sample PDL program:
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;
Save this file as myprogram.pl and run it with:
perl myprogram.pl
๐ New: Flexible syntax ๐
In current versions of PDL (version 2.4.7 or later) there is a flexible matrix syntax that can look extremely similar to MATLAB:
- Use spaces to separate elements:
$y = pdl q[ 2 3 4 ];
- Use a ';' to delimit rows:
$A = pdl q[ 1,2,3 ; 4,5,6 ];
Basically, as long as you put a q in front of the opening bracket, PDL should "do what you mean". So you can write in a syntax that is more comfortable for you. Periodt ๐
.
๐ฆ MODULES FOR MATLAB USERS ๐ฆ
There are two modules that MATLAB users will want to use:
๐ PDL::NiceSlice ๐
Gives PDL a syntax for slices (sub-matrices) that is shorter and more familiar to MATLAB users.
% 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.
๐ PDL::AutoLoader ๐
Provides a MATLAB-style autoloader for PDL. If an unknown function foo() is called, PDL looks for a file called foo.pdl. If it finds one, it reads it.
๐ BASIC FEATURES ๐
This section explains how PDL's syntax differs from MATLAB. Most MATLAB users will want to start here.
๐จ General "gotchas" ๐จ
๐ข Indices ๐ข
In PDL, indices start at '0' (like C and Java), not 1 (like MATLAB or FORTRAN). For example, if $y 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.
๐ Displaying an object ๐
MATLAB normally displays object contents automatically. In the PDL shells you display objects explicitly with the print command or the shortcut p:
MATLAB:
>> a = 12
a = 12
>> b = 23; % Suppress output.
>>
PDL Shell (perldl or pdl2):
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>
In pdl2 there is the do_print command that will toggle the "quiet" mode, which defaults to on. In "print" mode, expressions you enter on the command line will have their values printed.
๐งฑ Creating ndarrays ๐งฑ
๐ Variables in PDL ๐
Variables always start with the '$' sign.
MATLAB: value = 42
PerlDL: $value = 42
๐งช Basic syntax ๐งช
Use the pdl constructor to create a new ndarray.
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] ]
๐งฎ Simple matrices ๐งฎ
- Matrix of ones: MATLAB
ones(5)โ PDLones 5,5 - Matrix of zeros: MATLAB
zeros(5)โ PDLzeros 5,5 - Random matrix: MATLAB
rand(5)โ PDLrandom 5,5 - Linear vector: MATLAB
1:5โ PDLsequence 5
Notice that in PDL the parenthesis in a function call are often optional. It is important to keep an eye out for possible ambiguities. For example:
pdl> p zeros 2, 2 + 2
Should this be interpreted as "zeros(2,2) + 2" or as "zeros 2, (2+2)"? Both are valid statements:
pdl> p zeros(2,2) + 2
[
[2 2]
[2 2]
]
pdl> p zeros 2, (2+2)
[
[0 0]
[0 0]
[0 0]
[0 0]
]
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.
๐ Linearly spaced sequences ๐
MATLAB: >> linspace(2,10,5)
ans = 2 4 6 8 10
PerlDL: pdl> p zeroes(5)->xlinvals(2,10)
[2 4 6 8 10]
Explanation: Start with a 1-dimensional ndarray of 5 elements and give it equally spaced values from 2 to 10.
MATLAB has a single function call for this. On the other hand, PDL's method is more flexible:
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]
]
]
โ๏ธ Slicing and indices โ๏ธ
Extracting a subset from a collection of data is known as slicing. PDL and MATLAB have a similar syntax for slicing, but there are two important differences:
- PDL indices start at 0, as in C and Java. MATLAB starts indices at 1.
- In MATLAB you think "rows and columns". In PDL, think "x and y".
MATLAB:
>> A
A =
1 2 3
4 5 6
7 8 9
PerlDL:
pdl> p $A
[
[1 2 3]
[4 5 6]
[7 8 9]
]
(row = 2, col = 1) and (x = 0, y = 1)
MATLAB:
>> A(2,1)
ans =
4
PerlDL:
pdl> p $A(0,1)
[
[4]
]
(row = 2 to 3, col = 1 to 2) and (x = 0 to 1, y = 1 to 2)
MATLAB:
>> A(2:3,1:2)
ans =
4 5
7 8
PerlDL:
pdl> p $A(0:1,1:2)
[
[4 5]
[7 8]
]
โ ๏ธ Warning โ When you write a stand-alone PDL program, if you want the "nice slice" syntax, you have to include the PDL::NiceSlice module. See the previous section "MODULES FOR MATLAB USERS" for more information.
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);
โ๏ธ Matrix Operations โ๏ธ
โ๏ธ Matrix multiplication โ๏ธ
MATLAB: A * B
PerlDL: $A x $B
๐ Element-wise multiplication ๐
MATLAB: A .* B
PerlDL: $A * $B
๐ Transpose ๐
MATLAB: A'
PerlDL: $A->transpose
๐ Functions that aggregate data ๐
Some functions (like sum, max and min) aggregate data for an N-dimensional data set. This is a place where MATLAB and PDL take a different approach:
Okay so in MATLAB, these functions all work along one dimension. ๐
>> A = [ 1,5,4 ; 4,2,1 ]
A = 1 5 4
4 2 1
>> max(A)
ans = 4 5 4
>> max(A')
ans = 5 4
If you want the maximum for the entire data set, you can use the special A(:) notation which basically turns the entire data set into a single 1-dimensional vector. โจ
>> max(A(:))
ans = 5
>> A = ones(2,2,2,2)
>> max(A(:))
ans = 1
PDL offers two functions for each feature. ๐ซถ
sum vs sumover
avg vs average
max vs maximum
min vs minimum
The long name works over a dimension, while the short name works over the entire ndarray. No cap.
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
Note: Notice that PDL aggregates horizontally while MATLAB aggregates vertically. In other words:
MATLAB PerlDL
max(A) == $A->transpose->maximum
max(A') == $A->maximum
TIP: In MATLAB you think"rows and columns". In PDL, think"x and y". ๐ฆ
๐ Higher dimensional data sets ๐
A related issue is how MATLAB and PDL understand data sets of higher dimension. MATLAB was designed for 1D vectors and 2D matrices. Higher dimensional objects ("N-D arrays") were added on top. In contrast, PDL was designed for N-dimensional ndarrays from the start. This leads to a few surprises in MATLAB that don't occur in PDL: ๐
MATLAB sees a vector as a 2D matrix.
MATLAB PerlDL
------ ------
>> vector = [1,2,3,4]; pdl> $vector = pdl [1,2,3,4]
>> size(vector) pdl> p $vector->dims
ans = 1 4 4
MATLAB sees "[1,2,3,4]" as a 2D matrix (1x4 matrix). PDL sees it as a 1D vector: A single dimension of size 4. ๐ธ
But MATLAB ignores the last dimension of a 4x1x1 matrix.
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
And MATLAB treats a 4x1x1 matrix differently from a 1x1x4 matrix.
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
MATLAB has no direct syntax for N-D arrays.
pdl> $A = pdl [ [[1,2,3],[4,5,6]], [[2,3,4],[5,6,7]] ]
pdl> p $A->dims
3 2 2
Feature support. In MATLAB, several features such as sparse matrix support are not available for N-D arrays. In PDL, just about any feature supported by 1D and 2D ndarrays, is equally supported by N-dimensional ndarrays. There is usually no distinction. ๐
๐ Loop Structures ๐
Perl has many loop structures, but we will only show the one that is most familiar to MATLAB users:
MATLAB PerlDL
------ ------
for i = 1:10 for $i (1..10) {
disp(i) print $i
endfor }
Note: Never use for-loops for numerical work. Perl's for-loops are faster than MATLAB's, but they both pale against a"vectorized"operation. PDL has many tools that facilitate writing vectorized programs. These are beyond the scope of this guide. To learn more, see:PDL::Indexing,PDL::Broadcasting, andPDL::PP.
Likewise, never use 1..10 for numerical work, even outside a for-loop. 1..10 is a Perl array. Perl arrays are designed for flexibility, not speed. Use ndarrays instead. To learn more, see the next section. ๐ง
๐งบ ndarrays vs Perl Arrays ๐งบ
It is important to note the difference between an ndarray and a Perl array. Perl has a general-purpose array object that can hold any type of element:
@perl_array = 1..10;
@perl_array = ( 12, "Hello" );
@perl_array = ( 1, 2, 3, \@another_perl_array, sequence(5) );
Perl arrays allow you to create powerful data structures (see Data structures below), but they are not designed for numerical work. For that, use ndarrays:
$pdl = pdl [ 1, 2, 3, 4 ];
$pdl = sequence 10_000_000;
$pdl = ones 600, 600;
For example:
$points = pdl 1..10_000_000 # 4.7 seconds
$points = sequence 10_000_000 # milliseconds
TIP: You can use underscores in numbers ("10_000_000"reads better than10000000). ๐
๐ผ Conditionals ๐ผ
Perl has many conditionals, but we will only show the one that is most familiar to MATLAB users:
MATLAB PerlDL
------ ------
if value > MAX if ($value > $MAX) {
disp("Too large") print "Too large\n";
elseif value < MIN } elsif ($value < $MIN) {
disp("Too small") print "Too small\n";
else } else {
disp("Perfect!") print "Perfect!\n";
end }
Note: Here is a "gotcha":
MATLAB: elseif
PerlDL: elsif
If your conditional gives a syntax error, check that you wrote your "elsif"s correctly. ๐
๐ซ TIMTOWDI (There Is More Than One Way To Do It) ๐ซ
One of the most interesting differences between PDL and other tools is the expressiveness of the Perl language. TIMTOWDI, or "There Is More Than One Way To Do It", is Perl's motto. โจ
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:
"While I am not finished, I will keep working."
Human language is more flexible than that. Instead, you are more likely to say:
"I will keep working until I am finished."
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:
while ( ! finished() ) {
keep_working();
}
if ( ! wife_angry() ) {
kiss_wife();
}
But it also offers the alternative until and unless statements:
until ( finished() ) {
keep_working();
}
unless ( wife_angry() ) {
kiss_wife();
}
And Perl allows you to write loops and conditionals in "postfix" form:
keep_working() until finished();
kiss_wife() unless wife_angry();
In this way, Perl often allows you to write more natural, easy to understand code than is possible in more restrictive programming languages. ๐ฆ
๐ Functions ๐
PDL's syntax for declaring functions differs significantly from MATLAB's.
MATLAB PerlDL
------ ------
function retval = foo(x,y) sub foo {
retval = x.**2 + x.*y my ($x, $y) = @_;
endfunction return $x**2 + $x*$y;
}
Don't be intimidated by all the new syntax. Here is a quick run through a function declaration in PDL: ๐
"sub"stands for"subroutine"."my"declares variables to be local to the function. This helps you not accidentally use undeclared variables, which is enforced if you"use strict". Seestrictfor more."@_"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:
sub mysum {
my ($i, $total) = (0, 0);
for $i (@_) {
$total += $i;
}
return $total;
}
In more recent versions of Perl, you can "use signatures" for a different syntax for declaring function parameters. See signatures for more.
- You can assign values to several variables at once using the syntax:
($x, $y, $z) = (1, 2, 3);
So, in the previous examples:
# 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) = @_;
- The
"return"statement gives the return value of the function, if any. ๐
โจ ADDITIONAL FEATURES โจ
๐ ASCII File IO
okay so bestie, you know how MATLAB's load command just slurps up a file of numbers separated by whitespace? yeah, same energy here ๐
โ except you use rcols from PDL::IO::Misc. that's the vibe.
and if you wanna see literally everything PDL can do with files, go read the docs for PDL::IO โ like, run help PDL::IO in the pdl2 shell, or pdldoc PDL::IO straight from your shell. iykyk โจ
๐งฑ Data structures
MATLAB flexes "cell arrays" and "structure arrays" when it wants to build complex data structures. Perl's arrays and hashes do the same job but honestly they're more powerful and more flexible โ no cap. this is just a lil taste though, a quick overview ๐. if you wanna go deep, hit <http://perldoc.perl.org/perldata.html> or just run perldoc perldata.
๐ Arrays
Perl arrays are giving MATLAB cell arrays but with โจmore rangeโจ. like, in MATLAB, a cell array is still fundamentally a matrix โ rows and rows, and every row has to be the same length. the math is mathing, but it's a little rigid ๐:
MATLAB
------
array = {1, 12, 'hello'; rand(3, 2), ones(3), 'junk'}
=> OK
array = {1, 12, 'hello'; rand(3, 2), ones(3) }
=> ERROR
meanwhile a Perl array is a general purpose, sequential data structure. it can literally hold any data type, no questions asked:
PerlDL
------
@array = ( [1, 12, 'hello'] , [ random(3,2), ones(3,3), 'junk' ] )
=> OK
@array = ( [1, 12, 'hello'] , [ random(3,2), ones(3,3) ] )
=> OK
@array = ( 5 , {'name' => 'Mike'} , [1, 12, 'hello'] )
=> OK
notice that! Perl arrays start with the @ prefix instead of the $ that ndarrays use. iconic behavior ๐
wanna learn more about Perl arrays? <http://perldoc.perl.org/perldata.html> or perldoc perldata. easy.
๐ฆ Hashes
Perl hashes are basically MATLAB's structure arrays but make it fashion:
MATLAB
------
>> drink = struct('type', 'coke', 'size', 'large', 'myarray', {1,2,3})
>> drink.type = 'sprite'
>> drink.price = 12 % Add new field to structure array.
PerlDL
------
pdl> %drink = ( type => 'coke' , size => 'large', myndarray => ones(3,3,3) )
pdl> $drink{type} = 'sprite'
pdl> $drink{price} = 12 # Add new field to hash.
again, look at that prefix ๐ โ Perl hashes start with % instead of the @ for arrays and the $ for ndarrays. three different sigils, three different vibes, we love to see it.
wanna learn? you already know the drill: <http://perldoc.perl.org/perldata.html> or perldoc perldata ๐ซถ
โก Performance
okay this is the part where PDL starts bragging and honestly? deserved ๐ฅ. PDL has powerful performance features, and some of them are straight up not available in your usual numerical computation tools. these pages will walk you through them:
๐ PDL::Indexing
Level: Beginner ๐ฑ
this beginner tutorial covers the standard "vectorization" feature โ the one you already know from MATLAB, bestie. read this to learn how to dodge for-loops so your program doesn't move like it's stuck in molasses โจ
๐ PDL::Broadcasting
Level: Intermediate ๐ง
PDL's "vectorization" goes beyond what most numerical software can even do. this tutorial teaches you how to "broadcast" over higher dimensions, which means you can vectorize your program further than MATLAB will let you. main character energy, fr fr ๐
โฑ๏ธ Benchmarks
Level: Intermediate ๐ง
Perl ships with an easy to use benchmarks module that helps you figure out how long different parts of your code take to run. it's a great lil tool for focusing your optimization efforts where they actually matter. read about it online at <http://perldoc.perl.org/Benchmark.html>, or through the command perldoc Benchmark ๐
๐ง PDL::PP
Level: Advanced ๐
PDL's Pre-Processor is genuinely one of PDL's most powerful features, and I'm not being dramatic. you write a function definition in special markup, and the pre-processor generates real C code that can be compiled. with PDL:PP you get the full speed of native C code without dealing with the full complexity of the C language. ate and left no crumbs. ๐
๐ Plotting
PDL has full-featured plotting abilities ๐ธ. unlike MATLAB, PDL leans more on third-party libraries โ pgplot and PLplot โ for its 2D plotting features. its 3D plotting and graphics uses OpenGL for performance and portability. three main plotting modules, let's meet them:
๐ผ๏ธ PDL::Graphics::PGPLOT
Best for: Plotting 2D functions and data sets โจ
this is an interface to the venerable PGPLOT library. PGPLOT has been widely used in academic and scientific communities for many years โ it's basically a legend at this point. partly because of its age, PGPLOT has some limitations compared to newer packages like PLplot (e.g. no RGB graphics ๐ญ). but it's got a ton of features that still keep it popular in the scientific community. respect the elders ๐ซถ
๐ PDL::Graphics::PLplot
Best for: Plotting 2D functions as well as 2D and 3D data sets ๐ฅ
this is an interface to the PLplot plotting library. PLplot is a modern, open source library for making scientific plots, and it supports plots of both 2D and 3D data sets. it's best supported on unix/linux/macosx platforms, it has an active developer community, and support for win32 platforms is improving โญ
๐ง PDL::Graphics::TriD
Best for: Plotting 3D functions ๐
the native PDL 3D graphics library, using OpenGL as a backend for 3D plots and data visualization. with OpenGL it's easy to manipulate the resulting 3D objects with the mouse in real time โ like literally grab them and spin them around, it's so satisfying ๐
๐ฅ๏ธ Writing GUIs
through Perl, PDL has access to all the major toolkits for creating a cross-platform graphical user interface ๐. one popular option is wxPerl (<http://wxperl.sourceforge.net>) โ these are the Perl bindings for wxWidgets, a powerful GUI toolkit for writing cross-platform applications.
wxWidgets is designed to make your app look and feel like a native application on every platform ๐. for example, the Perl IDE Padre is written with wxPerl. so like, yeah, it works.
๐งฎ Simulink
Simulink is a graphical dynamical system modeler and simulator. it can be purchased separately as an add-on to MATLAB ๐ธ. PDL and Perl do not have a direct equivalent to MATLAB's Simulink. if this feature is important to you, take a look at Scilab:
Scilab is another numerical analysis software. like PDL, it's free and open source ๐ฆ. it doesn't have PDL's unique features, but it's very similar to MATLAB. Scilab comes with Xcos (previously Scicos), a graphical system modeler and simulator similar to Simulink โจ
๐ COMPARISON: REPEATED COPY OF MATRIX
okay so in MATLAB, the repmat function works like this:
> A = reshape(0:5, 3, 2)' # 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
this works (at least in Octave) at least up to 3 dimensions ๐
the PDL analog, bestie ๐:
sub repmat {
my $f=shift;
my @n=@_; #number of repetitions along dimension
my $sl = join ',', 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]
]
๐ธ COMPARISON: FLOYD-WARSHALL ALGORITHM ๐ธ
Okay so in graph theory thereโs this apparently-simple but actually difficult problem called the โshortest pathโ problem โ finding the shortest path between any two nodes. A famous solution is the Floyd-Warshall algorithm, and bestie, it is expensive: itโs O(V^3) where V is the number of vertices. It iterates through all the possible paths. ๐
Both the MATLAB solution and the PDL solution use vectorisation, so hopefully this is a useful comparison. The MATLAB version started with the code by Giorgos Dim at https://uk.mathworks.com/matlabcentral/fileexchange/67503-floyd-warshall-vectorized, but was modified because that code produces an incorrect path matrix. ๐ญ
Sample data (reflected on both the Wikipedia page, and the Rosetta Code website) for the weighted-edges matrix is, in PDL format:
my $we = pdl q[
[Inf Inf -2 Inf]
[ 4 Inf 3 Inf]
[Inf Inf Inf 2]
[Inf -1 Inf Inf]
];
and in MATLAB format:
A = [0 Inf -2 Inf; 4 0 3 Inf; Inf Inf 0 2; Inf -1 Inf 0]
๐ฆ PDL version ๐ฆ
To solve for only distances without capturing the shortest actual paths:
$we .= $we->hclip($we->mslice('X', $_) + $we->mslice($_, 'X'))
for 0..($we->dim(0)-1);
This loops over each possible intermediate point (k in the other literature), setting it to $_ (a Perl idiom). It uses hclip 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 โslicesโ alluded to above. The .= is the PDL syntax for updating an ndarray. โจ
To capture the shortest-path โnext vertexโ matrix as well:
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('X', $k) + $d->mslice($k, 'X'));
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);
}
The diagonal and slice expressions show how to update data via a query syntax. ๐ซถ
๐ MATLAB version ๐
Path-lengths only:
function D = FloydWarshall(D)
for k = 1:length(D)
D = min(D,D(:,k) + D(k,:));
end
end
The path vertices-capturing as well:
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<prevD);
from_coords = n * (k-1) + mod(coords-1, n) + 1; % change col to k in 1-based
P(coords) = P(from_coords);
end
end
By comparison, the lack of โbroadcastingโ means that to update the diagonal requires a for-loop, which in the sphere of vectorised calculations is a bad thing. The calculations of coordinates are complicated by the 1-based counting. ๐
๐ COPYRIGHT ๐
Copyright 2010 Daniel Carrera (dcarrera@gmail.com). You can distribute and/or modify this document under the same terms as the current Perl license.
See: <http://dev.perl.org/licenses/>
๐ 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 MATLAB users as it is today. ๐ฅน๐
Catch you later, bestie โ this page is from source/version perl v5.32.1, dated 2022-04-11, and itโs the MATLAB(1) page. Mwah! ๐โจ
๐ฆ where this page comes from
- epel 9: perl-PDL 2.78.0-1.el9 ยท GPL+ or Artistic
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms