473,505 Members | 13,823 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

In-place Class Functions

Hi

I have a matrix class:

template<class Type> class TMatrix
{
//...
TMatrix& T();
//...
}

The transposition function above does not execute in place, ie it
returns a new object. This allows expressions like:

TMatrix<single> A,L,D;
L = ...
D = ...
A = L.T()*D*L;

L.T() is not L and therefore it makes sense to return a new object. If
L.T() were executed in-place, the final product D*L would in fact be
D*L.T() which is incorrect.

However, there are situations where the transpose is required in an
assignment, and

L = L.T();

seems clumsy and inefficient with all the constructors and destructors
getting in on the action (unless good return by value optimizations are
being generated).

Should I do something like:

TMatrix& T(bool inplace = false);

which does not break:
A = L.T()*D*L;

but allows:
L.T(true);

and even:
A = L.T(true)*D*L.T();

as a pathological example. The difference between this expression and
the first version being that L is ends in a transposed state (first
transpose in-place, the second not).

The code may be something like:
template<class Type> TMatrix<Type>& TMatrix<Type>::T(bool inplace)
{
if(inplace)
{
// Transpose in-place.
//...
return *this;
}
/* Create temporary and transpose in-place. Admittedly, a bit lazy
since the transpose code could be re-done below, but on the other hand
one does not want two code fragments doing the same job. */
return TMatrix<Type>(this).T(true);
}

Since a temporary has to be created, maybe
L = L.T();
is not so inefficient after all?

Any comments or suggestions?

Thanks
Andrew

Jul 19 '05 #1
8 2935
Andrew Morgan escribió:
template<class Type> class TMatrix
{
//...
TMatrix& T();
//...
}

The transposition function above does not execute in place, ie it
returns a new object. This allows expressions like:

TMatrix<single> A,L,D;
L = ...
D = ...
A = L.T()*D*L;

L.T() is not L and therefore it makes sense to return a new object. If
L.T() were executed in-place, the final product D*L would in fact be
D*L.T() which is incorrect.

However, there are situations where the transpose is required in an
assignment, and

L = L.T();


Make T return a TMatrix_T object that holds a reference to the TMatrix.
Define a TMatrix::operator = (const TMatrix_T &) and an operator *
(const TMatrix_T &, const TMatrix &), and additional operators if
neccessary.

Regards.
Jul 19 '05 #2
Andrew Morgan wrote:
Hi

I have a matrix class:

template<class Type> class TMatrix
{
//...
TMatrix& T();
//...
}

The transposition function above does not execute in place, ie it
returns a new object. This allows expressions like:

TMatrix<single> A,L,D;
L = ...
D = ...
A = L.T()*D*L;

L.T() is not L and therefore it makes sense to return a new object. If
L.T() were executed in-place, the final product D*L would in fact be
D*L.T() which is incorrect.

However, there are situations where the transpose is required in an
assignment, and

L = L.T();

seems clumsy and inefficient with all the constructors and destructors
getting in on the action (unless good return by value optimizations are
being generated).

Should I do something like:

TMatrix& T(bool inplace = false);

which does not break:
A = L.T()*D*L;

but allows:
L.T(true);

and even:
A = L.T(true)*D*L.T();

as a pathological example. The difference between this expression and
the first version being that L is ends in a transposed state (first
transpose in-place, the second not).

The code may be something like:
template<class Type> TMatrix<Type>& TMatrix<Type>::T(bool inplace)
{
if(inplace)
{
// Transpose in-place.
//...
return *this;
}
/* Create temporary and transpose in-place. Admittedly, a bit lazy
since the transpose code could be re-done below, but on the other hand
one does not want two code fragments doing the same job. */
return TMatrix<Type>(this).T(true);
}

Since a temporary has to be created, maybe
L = L.T();
is not so inefficient after all?

Any comments or suggestions?


It seems to me that you are getting into a kerfuffle trying
to provide a unified syntax for doing different things.

T(TMatrix& result) const;
// assign 'result' the transposition of this matrix

TMatrix& T();
// transpose matrix this matrix
anyone reading the code won't then have to wonder what the
signifigance of 'true' is.

Jul 19 '05 #3
lilburne wrote:
It seems to me that you are getting into a kerfuffle trying to provide a
unified syntax for doing different things. True.
T(TMatrix& result) const;
// assign 'result' the transposition of this matrix

TMatrix& T();
// transpose matrix this matrix
anyone reading the code won't then have to wonder what the signifigance
of 'true' is.

I now have:

template <class Type> class TMatrix
{
//...
void T();
void PLU();
void UFSub(TMatrix &x);
void BSub(TMatrix &y);
//...
}
template<class Type> TMatrix<Type> T(const TMatrix<Type> &A)
{
// Create temporary, transpose and return.
TMatrix<Type> B(A);
B.T();
return B;
};

The void return types in the class is meant to convey the idea that the
operation are done in-place, while the function T (which does not alter
its argument - this would be catastrophic) returns a new transposed object.

All in-expression transpositions are handled by the function:

A = B + (C * T(D)) + E;

[BTW, is A = B + C * T(D) + E; evaluated left to right, right to left (I
suspect) or according to mathematical precedence where * would be
evaluated first?]

The reason why the in-place/copy issues has come up is because the
function PLU (Partially pivoted LU decomposition) is done in-place.

Solving a finite element-type problem:
[f] = [K][x]

where [K] is a 1000 node 3D problem (and hence 6,000x6,000 = 36,000,000
elements = 275Mb! - worst case obviously) is done in-place simply
because I may not have a spare 275M to create a copy!

Re-arranging:
[x] = [f]/[K] (or strictly, [x] = INV[K][f])

Again, [x] may be "largish" (6,000 elements = 47K) so [f] can be
decomposed in-place into [x].

Coding would look like this:
f = ...
K = ...
f /= K; // [f] is now [x] - the solution.

which wakes up:

template<class Type> TMatrix<Type>& TMatrix<Type>::operator/=(const
TMatrix &K)
{
// Division is strictly inversion and pre-multiplication.
/* Which version???
TMatrix A(K);
A.PLU();
A.UFSub(*this);
A.BSub(*this);
return *this;
*/
// Factorize K to LU by Partial LU.
K.PLU();
// Solve [y] = INV[L][f] by Unit Forward Substitution.
K.UFSub(*this);
// Solve [x] = INV[u][y] by Back Substitution.
K.BSub(*this);
return *this;
};

As you can see from the code, my dilemma is:
* do I make &K const, in which case I must make a temporary A (275M
free?), or do a leave &K non-const (ie developer please note that
operator/= is entitled to modify non-const K, and similarly, non-const
&x and &y in UFSub() and BSub() respectively)?

Thus, f /= K decomposes both f and K in-place.

If I were the only user of the code I can live with this since I know
its behaviour, but it is not necessarily good class design. But then,
good design sometimes runs foul of practical problems. Comments?

Thanks for the posts.

Regards
Andrew

Jul 19 '05 #4
Andrew Morgan wrote:
lilburne wrote:
Thus, f /= K decomposes both f and K in-place.

If I were the only user of the code I can live with this since I know
its behaviour, but it is not necessarily good class design. But then,
good design sometimes runs foul of practical problems. Comments?


I looked at our own matrix class and unsurprisingly none of
the methods return a matrix by value. Now our matrix is
mainly used for geometric transformation so they never get
beyond 4x4 in size and are usually contained within a class
that provides geometric transforms. However, the design of
the class is such that a user of it never gets any
surprises. We provide some methods so that users can do
Vector * Transform or Point * Transform, but mostly we'll
have methods which look like:

Matrix& Transpose();
Matrix& Transpose(Matrix& copy);
Matrix& Postmultiple(const Matrix&);
Matrix& Postmultiple(const Matrix&, Matrix& result) const;
Matrix& Premultiple(const Matrix);

obviously this forces users to write their code in a
functional style rather than by using operator shorthands,
the reasoning being that the class user is never left in any
doubt about whether something is going to occur in place or not.

So we sidestep the issue of temporaries by saying

"if you require a temporary then you actively create one
yourself, you don't rely on the compiler doing it for
you."

this is a style of coding which we carry through with all
our data structures.

Jul 19 '05 #5
lilburne wrote:
obviously this forces users to write their code in a functional style
rather than by using operator shorthands, the reasoning being that the
class user is never left in any doubt about whether something is going
to occur in place or not.

So we sidestep the issue of temporaries by saying

"if you require a temporary then you actively create one
yourself, you don't rely on the compiler doing it for
you."

this is a style of coding which we carry through with all our data
structures.


I agree that is a safe approach.

I am however, trying to capture the essence of object orientation which
urges user-defined types to behave like built-ins.

That is if:
double x,y,z;
x = y + z;
y /= z;

are valid for doubles, then
TMatrix<double> X,Y,Z;
X = Y + Z;
Y /= Z;

should also be (without surprises and bad side effects -- the
responsibility of the designer).

To this end, I have the following global templates:

//---------------------------------------------------------------------------
template<class TClass> const TClass operator+(const TClass &Left,const
TClass &Right)
{
return TClass(Left) += Right;
}
//---------------------------------------------------------------------------
template<class TClass> const TClass operator-(const TClass &Left,const
TClass &Right)
{
return TClass(Left) -= Right;
}
//---------------------------------------------------------------------------
template<class TClass> const TClass operator*(const TClass &Left,const
TClass &Right)
{
return TClass(Left) *= Right;
}
//---------------------------------------------------------------------------
template<class TClass> const TClass operator/(const TClass &Left,const
TClass &Right)
{
return TClass(Left) /= Right;
}
//---------------------------------------------------------------------------

These are always implemented as op= (per Scott Meyers). To support
matrix operations with these template, my dilemma is solved, since I
have had to redefined operator/= with a const parameter, and since the
parameter is decomposed internally, I must necessarily use a temporary:

template<class Type> TMatrix<Type>& TMatrix<Type>::operator/=(const
TMatrix &B)
{
// Division is strictly inversion and pre-multiplication.
TMatrix A(B);
A.PLU();
A.UFSub(*this);
A.BSub(*this);
return *this;
};

So, in this scenario I can match the behaviour of the built-ins (without
surprises), but I have not lost the ability to operations without
temporaries:

TMatrix f,K,x;
f = ...
K = ...
----------
x = f; // Contrived, but f not lost.
x /= K; // Uses temporary for K.
----------
OR
----------
f /= K; // Uses temporary for K, x not needed, but f modified
---------- // (no surprise)
OR
----------
K.Inverse(); // Very slow but OK.
x = K*f; // Solution, but non-intuitive if you did not spot the //
Inverse()
----------
OR
---------- // Fastest!
K.PLU(); // In-place decomposition - no surprise or temporary
K.UFSub(f);
K.BSub(f); // Solution in f
----------
OR
----------
x = f; // Contrived, but f not lost.
K.PLU(); // In-place decomposition - no surprise or temporary
K.UFSub(x);
K.BSub(x); // Solution in x.
----------

The last two could be wrapped in functions:

void Solve(TMatrix &f,const TMatrix &K);
TMatrix& Solve(const TMatrix &f,const TMatrix &K);

respectively.

Having given this a lot of thought recently, built-in behaviour can be
replicated by TMatrix operators which use temporaries. When performance
and memory storage are issues, use functions like x = Solve(f,K).

This strategy differs somewhat from yours in that when one wishes to use
the extremely convenient short-hand, one pays the price in temporaries,
but more traditional alternatives are available should the need arise.

Thanks for the input.

Regards
Andrew

Jul 19 '05 #6
Andrew Morgan wrote:


I have a matrix class:

template<class Type> class TMatrix {
//...
TMatrix& T(void);
//...
};

The transposition function above does not execute in place, ie it
returns a new object.
No it doesn't. It returns a *reference* to a TMatrix object.
You probably just screwed up. Instead, you should define:

template<class Type> class TMatrix {
//...
TMatrix T(void);
//...
};
This allows expressions like:
TMatrix<single> A,L,D;
L = ...
D = ...
A = L.T()*D*L;

L.T() is not L and therefore it makes sense to return a new object.
If L.T() were executed in-place,
the final product D*L would in fact be D*L.T() which is incorrect.

However, there are situations where the transpose is required in an
assignment, and

L = L.T();

seems clumsy and inefficient with all the constructors and destructors
getting in on the action (unless good return by value optimizations are
being generated).

Should I do something like:

TMatrix& T(bool inplace = false);

which does not break:
A = L.T()*D*L;

but allows:
L.T(true);

and even:
A = L.T(true)*D*L.T();

as a pathological example. The difference between this expression and
the first version being that L is ends in a transposed state (first
transpose in-place, the second not).

The code may be something like:
template<class Type> TMatrix<Type>& TMatrix<Type>::T(bool inplace) {
if(inplace) {
// Transpose in-place.
//...
return *this;
};
/* Create temporary and transpose in-place. Admittedly, a bit lazy
since the transpose code could be re-done below, but on the other hand
one does not want two code fragments doing the same job. */
return TMatrix<Type>(this).T(true);
}

Since a temporary has to be created, maybe
L = L.T();
is not so inefficient after all?

Any comments or suggestions?


Take a look at
The C++ Scalar, Vector, Matrix and Tensor class Library

http://www.netwood.net/~edwin/svmtl/

Remember that the transpose is applied *only* to
*Square* matrix types.

Jul 19 '05 #7
E. Robert Tisdale wrote:
Andrew Morgan wrote:


I have a matrix class:

template<class Type> class TMatrix {
//...
TMatrix& T(void);
//...
};

The transposition function above does not execute in place, ie it
returns a new object.

No it doesn't. It returns a *reference* to a TMatrix object.
You probably just screwed up. Instead, you should define:

template<class Type> class TMatrix {
//...
TMatrix T(void);
//...
};

Part of the discussion was simply to debate this point. I have
concluded that member functions that modify their own data should return
void to prevent them being coerced into expressions.

template<class Type> class TMatrix {
//...
void T(); // Transpose.
void PLU(); // Partial Pivot LU Decomposition.
///...
};

and a simple function returning the transpose:

TMatrix T(const TMatrix&);

which can safely be used in expressions:

A = T(B) * D * B;

Take a look at
The C++ Scalar, Vector, Matrix and Tensor class Library

http://www.netwood.net/~edwin/svmtl/
Still chewing...
Remember that the transpose is applied *only* to
*Square* matrix types.

Huh? I make very heavy use of xT*x (dot product) as the work horse of
many of the matrix inner loops using optimized assembler. A significant
application of the class processes huge non-square matrices.

Jul 19 '05 #8
Andrew Morgan wrote:
Part of the discussion was simply to debate this point.
I have concluded that member functions that modify their own data
should return void to prevent them being coerced into expressions.

template<class Type> class TMatrix {
//...
void T(); // Transpose.
void PLU(); // Partial Pivot LU Decomposition.
///...
};
This is a *very* bad idea.
In place operations *should* return a reference to the modified object
so that it *can* be used in an expression.

For example:

TMatrix<Type>& TMatrix<Type>::operator=(
const TMatrix<Type> rhs) {
/* . . . */
return *this; }

and a simple function returning the transpose:

TMatrix T(const TMatrix&);

which can safely be used in expressions:

A = T(B) * D * B;
No.

Use operator* for element-by-element multiplication.
Use operator/ for element-by-element division.

Take a look at
The C++ Scalar, Vector, Matrix and Tensor class Library

http://www.netwood.net/~edwin/svmtl/

Still chewing...
Remember that the transpose is applied *only* to
*Square* matrix types.


Huh? I make very heavy use of xT*x (dot product) as the work horse
of many of the matrix inner loops using optimized assembler.
A significant application of the class
processes huge non-square matrices.


No!

The matrix-matrix dot product

C = A.dot(B); // C <-- AB^T

is a very special function.

You are obviously a Fortran programmer.
In C++, a matrix is a collection of *row* vectors --
*not* column vectors.

Anyway, this is the wrong place to discuss this.

Try the Object Oriented Numerics Web Page:

http://www.oonumerics.org/oon/

and subscribe to the mailing list.

Meanwhile, study
The C++ Scalar, Vector, Matrix and Tensor class library
standard proposal at

http://www.netwood.net/~edwin/svmtl/

Jul 19 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
6745
by: Curious Expatriate | last post by:
Hi- I'm completely stumped. I'm trying to write some code that will parse a file and rewrite it with all URLs replaced by something else. For example: if the file looks like this: <b>click...
1
6234
by: JS Bangs | last post by:
I started using PHP's object-oriented stuff a little while ago, which has mostly been a joy. However, I've noticed that they don't seem to echo as I would like. Eg: $this->field = 255;...
5
16135
by: lawrence | last post by:
I've waited 6 weeks for an answer to my other question and still no luck, so let me rephrase the question. I know I can do this: <form method="post" action="$self"> <input type="text"...
0
4902
by: Ben Eisenberg | last post by:
I'm trying to run a php script setuid. I've tried POSIX_setuid but you have to be root to run this. The files are located on a public access unix system and have me as the owner and nobody as the...
2
8548
by: Felix | last post by:
Hi, I've a problem: I want to have the result of my Mysql Query in a Table in my php file. Now I've this: <?
1
8695
by: James | last post by:
What is the best way to update a record in a MYSQL DB using a FORM and PHP ? Where ID = $ID ! Any examples or URLS ? Thanks
1
2935
by: Patrick Schlaepfer | last post by:
Why this code is not working on Solaris 2.8 host. Always getting: PHP Fatal error: swfaction() : getURL('http://www.php.net' ^ Line 1: Reason: 'syntax error' in /.../htdocs/ming2.php on...
1
3401
by: phpkid | last post by:
Howdy I've been given conflicting answers about search engines picking up urls like: http://mysite.com/index.php?var1=1&var2=2&var3=3 Do search engines pick up these urls? I've been considering...
1
2550
by: lawrence | last post by:
What is the PHP equivalent of messaging, as in Java?
3
4899
by: Quinten Carlson | last post by:
Is there a way to conditionally define a function in php? I'm trying to run a php page 10 times using the include statement, but I get an error because my function is already defined. The docs...
0
7213
marktang
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,...
0
7098
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...
0
7366
jinu1996
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...
0
7471
tracyyun
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...
0
5610
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5026
isladogs
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...
0
4698
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...
0
3187
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...
0
1526
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.