Perl: the Markov chain saw PerlMonks

### comment on

 Need Help??
Xilman,

Because you invoked "least squares fitting", I assume what you want is a planar least-squares fitting in 3d, analogous to the linear least-squares in 2d, and that z is supposed be be linearly dependent on the others: ax+by+c = z

You can see the algebra in this math.stackexchange answer, but basically you are solving A*X=B, where A is a matrix of the x and y data, X are the column-vector of the coefficients a,b,c from the above equation, and B is the column-vector of the z values for each x,y input.

I haven't looked up the exact PDL syntax, but: An exact solution for 3 sets of (x,y,z) data would have PDL akin to \$coeff_X = \$matrix_A->inverse * \$column_B;. But since you presumably have many points, not just three, since you invoked best-fit, you have to use the "left pseudo inverse", which would have a PDL implementation akin to \$coeff_X = (\$matrix_A->transpose * \$matrix_A)->inverse * (\$matrix_A->transpose) * \$column_B;

update: I was close.

```#!/usr/bin/perl
use strict;
use warnings;
use PDL;
use PDL::Matrix;

# example: 2x + 3y + 4 = z, plug in known exact values; make sure my c
+oefficients end up 2,3,4

my \$matrix_A = mpdl [
[1,1,1],
[3,7,1],
[5,1,1],
[1,5,1],
];

print "A => ", \$matrix_A;
print "B => ", my \$column_B = vpdl [9,31,17,21];
print "X => ", my \$coeff_X = ((\$matrix_A->transpose x \$matrix_A)->inv
+x \$matrix_A->transpose) x \$column_B;

prints:

```A =>
[
[1 1 1]
[3 7 1]
[5 1 1]
[1 5 1]
]
B =>
[
[ 9]
[31]
[17]
[21]
]
X =>
[
[         2]
[         3]
[         4]
]

In reply to Re: Surface fitting with PDL by pryrt
in thread Surface fitting with PDL by Xilman

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

• Are you posting in the right place? Check out Where do I post X? to know for sure.
• Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
• Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
• Want more info? How to link or How to display code and escape characters are good places to start.

Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2024-04-24 02:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?

No recent polls found