I've posted a simple Matrix class on my website as a small-footprint
package for doing basic calculations on matrices up to about 10x10 in
size (no theoretical limit, but performance on inverse is exponential).
Includes:
- trace
- transpose
- conjugate
- determinant
- inverse
- eigenvectors/values (for symmetric matrices)
- addition and multiplication (with constant or other matrix)
Matrices are easily built from formatted strings, as in:
m = Matrix( """1 2 3 4
5 11 20 3
2 7 11 1
0 5 3 1""")
Pretty much a no-strings-attached license, just don't hassle me about
little things like warranty, support, merchantability , accuracy, etc.
See it at http://www.geocities.com/ptmcg/pytho...html#matrix_py
-- Paul 14 6215
Do you calcalate the matrix inversion, when you don't need to?
"Paul McGuire" <pt***@austin.r r.comwrote:
>I've posted a simple Matrix class on my website as a small-footprint package for doing basic calculations on matrices up to about 10x10 in size (no theoretical limit, but performance on inverse is exponential).
Includes: - trace - transpose - conjugate - determinant - inverse - eigenvectors/values (for symmetric matrices) - addition and multiplication (with constant or other matrix)
Matrices are easily built from formatted strings, as in:
m = Matrix( """1 2 3 4
5 11 20 3
2 7 11 1
0 5 3 1""")
Pretty much a no-strings-attached license, just don't hassle me about little things like warranty, support, merchantability , accuracy, etc. See it at http://www.geocities.com/ptmcg/pytho...html#matrix_py
-- Paul
--
Regards,
Casey
On Jan 23, 4:05 pm, Casey Hawthorne <caseyhHAMMER_T ...@istar.ca>
wrote:
Do you calcalate the matrix inversion, when you don't need to?
No, the inversion is only calculated on the first call to inverse(),
and memoized so that subsequent calls return the cached value
immediately. Since the Matrix class is mutable, the cache is
invalidated if any of the matrix elements are updated. So after
changing a matrix element, the inversion would be recalculated at the
next call to inverse().
Hope that clears things up. You can also do your own experiments,
including adding verbose logging to the memoizing decorators - an
example is included in the source code. Also the footprint is quite
small, just one Python source file, about 600-700 lines of code, and
all Python, so 100% portable.
-- Paul
Paul McGuire wrote:
I've posted a simple Matrix class on my website as a small-footprint
package for doing basic calculations on matrices up to about 10x10 in
size (no theoretical limit, but performance on inverse is exponential).
Why is that? A simple and robust LU decomposition should be no more than O(n**3).
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
On Jan 23, 6:59 pm, Robert Kern <robert.k...@gm ail.comwrote:
Paul McGuire wrote:
I've posted a simple Matrix class on my website as a small-footprint
package for doing basic calculations on matrices up to about 10x10 in
size (no theoretical limit, but performance on inverse is exponential).
Why is that? A simple and robust LU decomposition should be no more than O(n**3).
--
Robert Kern
Well "3" is an exponent isn't it? :)
In truth, in my laziness, I didn't *actually* test the performance.
But after measuring inversion times for nxn matrices for n=2 to 12, I
get these results (run on Python 2.4.2, on a 2GHz CPU):
n seconds ln(seconds)
2 0.0004112254490 45 -7.79636895604
3 0.0010224763203 1 -6.88552782893
4 0.0043754164286 2 -5.43175358002
5 0.0146999129778 -4.21991370509
6 0.0507813143849 -2.98022681913
7 0.143077961026 -1.94436561528
8 0.39962257773 -0.917234732978
9 1.14412558021 0.134640659841
10 3.01953516439 1.10510290046
11 8.76039971561 2.17024153354
12 21.8032182861 3.0820575867
Plotting n vs. ln(seconds) gives a fairly straight line of slope about
1.09, and exp(1.09) = 2.97, so your big-O estimate seems to line up
nicely with the experimental data - I couldn't have fudged it any
better.
-- Paul
At Tuesday 23/1/2007 22:33, Paul McGuire wrote:
>On Jan 23, 6:59 pm, Robert Kern <robert.k...@gm ail.comwrote:
Paul McGuire wrote:
I've posted a simple Matrix class on my website as a small-footprint
package for doing basic calculations on matrices up to about 10x10 in
size (no theoretical limit, but performance on inverse is exponential).
Why is that? A simple and robust LU decomposition should be no
more than O(n**3).
Well "3" is an exponent isn't it? :)
But constant!
x**2 is a "power" (or quadratic, or polynomial) function. 2**x is an
"exponentia l" function. They're quite different.
>In truth, in my laziness, I didn't *actually* test the performance. But after measuring inversion times for nxn matrices for n=2 to 12, I get these results (run on Python 2.4.2, on a 2GHz CPU):
n seconds ln(seconds) 2 0.0004112254490 45 -7.79636895604 3 0.0010224763203 1 -6.88552782893 4 0.0043754164286 2 -5.43175358002 5 0.0146999129778 -4.21991370509 6 0.0507813143849 -2.98022681913 7 0.143077961026 -1.94436561528 8 0.39962257773 -0.917234732978 9 1.14412558021 0.134640659841 10 3.01953516439 1.10510290046 11 8.76039971561 2.17024153354 12 21.8032182861 3.0820575867
Plotting n vs. ln(seconds) gives a fairly straight line of slope about 1.09, and exp(1.09) = 2.97, so your big-O estimate seems to line up nicely with the experimental data - I couldn't have fudged it any better.
Nope, such semilog plot shows that time grows exponentially, like
t=3*exp(n), and that's really bad! :(
The points should be aligned on a log-log plot to be a power function.
As Robert Kern stated before, this problem should be not worse than
O(n**3) - how have you implemented it?
--
Gabriel Genellina
Softlab SRL
_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! http://www.yahoo.com.ar/respuestas
The points should be aligned on a log-log plot to be a power function.
As Robert Kern stated before, this problem should be not worse than
O(n**3) - how have you implemented it?
Sure enough, the complete equation is t = 5e-05exp(1.1n), or t = 5e-05
X 3**n.
As for the implementation, it's pretty much brute force. Here is the
code itself - the cacheValue decorator memoizes the calculated inverse
for the given Matrix.
@cacheValue
def det(self):
"Function to return the determinant of the matrix."
if self.isSquare() :
if self.numRows() 2:
multiplier = 1
firstRow = self[1]
tmp = self._rows[1:]
rangelentmp = range(len(tmp))
col = 0
detsum = 0
for val in firstRow:
if val:
#~ tmp2 = Matrix([
RowVector(t[0:col]+t[col+1:]) for t in tmp ])
tmp2 = self.getCachedM atrix([
RowVector(t[0:col]+t[col+1:]) for t in tmp ])
detsum += ( multiplier * val * tmp2.det() )
multiplier = -multiplier
col += 1
return detsum
if self.numRows() == 2:
return self[1][1]*self[2][2]-self[1][2]*self[2][1]
if self.numRows() == 1:
return self[1][1]
if self.numRows() == 0:
return 0
else:
raise MatrixException ("can only compute det for square
matrices")
def cofactor(self,i ,j):
i-=1
j-=1
#~ tmp = Matrix([ RowVector(r[:i]+r[i+1:]) for r in
(self._rows[:j]+self._rows[j+1:]) ])
tmp = self.getCachedM atrix([ RowVector(r[:i]+r[i+1:]) for r in
(self._rows[:j]+self._rows[j+1:]) ])
if (i+j)%2:
return -tmp.det()
else:
return tmp.det()
#~ return (-1) ** (i+j) * tmp.det()
@cacheValue
def inverse(self):
if self.isSquare() :
if self.det() != 0:
ret = Matrix( [ RowVector( [ self.cofactor(i ,j) for j
in self.colrange() ] )
for i in self.rowrange() ] )
ret *= (1.0/self.det())
return ret
else:
raise MatrixException ("cannot compute inverse for
singular matrices")
else:
raise MatrixException ("can only compute inverse for square
matrices")
At Wednesday 24/1/2007 02:40, Paul McGuire wrote:
The points should be aligned on a log-log plot to be a power function.
As Robert Kern stated before, this problem should be not worse than
O(n**3) - how have you implemented it?
Sure enough, the complete equation is t = 5e-05exp(1.1n), or t = 5e-05 X 3**n.
So either reimplement it better, or place a notice in BIG letters to
your users about the terrible time and memory penalties of using inverse()
--
Gabriel Genellina
Softlab SRL
_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! http://www.yahoo.com.ar/respuestas
On Jan 24, 11:21 am, Gabriel Genellina <gagsl...@yahoo .com.arwrote:
At Wednesday 24/1/2007 02:40, Paul McGuire wrote:
The points should be aligned on a log-log plot to be a power function.
As Robert Kern stated before, this problem should be not worse than
O(n**3) - how have you implemented it?
Sure enough, the complete equation is t = 5e-05exp(1.1n), or t = 5e-05
X 3**n.
So either reimplement it better, or place a notice in BIG letters to
your users about the terrible time and memory penalties of using inverse()
Well, really, the "terrible time and memory penalties" aren't all that
terrible for matrices up to, oh, 10x10 or so, but you wouldn't want to
use this on anything much larger than that. Hey, guess what?! That's
exactly what I said in my original post!
And the purpose/motivation for "reimplemen ting it better" would be
what, exactly? So I can charge double for it? As it was, I felt a
little guilty for posting a solution to such a likely homework
assignment, but now there's room for a student to implement a kickass
inverter routine in place of the crappy-but-useful-for-small-matrices
brute force one I've written.
Cubs win!
-- Paul
Paul McGuire wrote:
And the purpose/motivation for "reimplemen ting it better" would be
what, exactly? So I can charge double for it?
So you can have accurate results, and you get a good linear solver out of the
process. The method you use is bad in terms of accuracy as well as efficiency.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Ben Ingram |
last post by:
Hi all,
I am writing a template matrix class in which the template parameters are
the number of rows and number of columns. There are a number of reasons
why this is an appropriate tradeoff for my particular application. One of the
advantages is that the _compiler_ can force inner matrix dimensions used in
multiplication to agree. A _complie-time_ error will be triggered if you
write A * B and the number of coluns in A does not equal the...
|
by: Erik Borgstr?m |
last post by:
Hi,
I simply want to use simple matrices of ints or doubles in C++ and I
want all the good:
1) be able to use double-index, e.g. m
2) not have to use pointers at all
3) do it fast
I know I could do 1&3 with ordinary int, but then if I want to
|
by: Ben |
last post by:
Hi all,
I'm not yet good at thinking the right way in c++ so although I could
solve this problem, I'm not sure if they way I'm thinking of is the best
way to do it. I need a data type or class or something that can hold
either an int, or a float, knows which one it is holding, and will allow
me to do comparisons with instances of it without the code which asks
for the comparison having to know which one it is. So maybe I could do
it...
|
by: Charulatha Kalluri |
last post by:
Hi,
I'm implementing a Matrix class, as part of a project. This is the interface
I've designed:
class Matrix( )
|
by: SUPER_SOCKO |
last post by:
Suppose I have a matrix M x N dimension.
Normally, to print all of the elements in the matrix. I write the
following codes:
Suppose M = 5, N = 4:
for(int j=0; j<5; ++j) {
for(int k=0; k<4; ++k) {
cout << matrix << " ";
}
| |
by: christopher diggins |
last post by:
Here is some code I wrote for Matrix multiplication for arbitrary
dimensionality known at compile-time. I am curious how practical it is. For
instance, is it common to know the dimensionality of matricies at
compile-time? Any help would be appreciated. Hopefully this code comes in
useful for someone, let me know if you find it useful, or if you have
suggestions on how to improve it.
// Public Domain by Christopher Diggins, 2005
...
|
by: |
last post by:
I am trying to compile a simple c# class in Web Matrix called howdy.cs:
// Program start class
public class HowdyPartner
{
// Main begins program execution
public static void Main()
{
// Write to console
|
by: DarrenWeber |
last post by:
Below is a module (matrix.py) with a class to implement some basic
matrix operations on a 2D list. Some things puzzle me about the best
way to do this (please don't refer to scipy, numpy and numeric because
this is a personal programming exercise for me in creating an
operational class in pure python for some *basic* matrix operations).
1. Please take a look at the __init__ function and comment on the
initialization of the list data...
|
by: rijaalu |
last post by:
I am designing a matrix class that performs addition, multicpication, substraction and division. When ever i complie the code it shows an error.
include <iostream>
using namespace std;
class matrix{
public:
matrix();
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
| |
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
| |