473,324 Members | 2,456 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

operator[] in matrix class

Hi,

I'd like to implement a simple matrix class. I'd like to overload
operator [] so that it returns as a vector (either the stl vector or
some other Vector class of my own). The reason I want to do this is
because it enables me to apply some functions of a vector to a row of
of matrix, e.g., I have a function to compute the sum of vector:

double my_sum(vector<double> x)
{
int i, n=x.size();
double result = 0;
for(i=0; i<n; ++i) result += x[i];
return result;
}

I'd like to compute the sum of the second row of a matrix:

Matrix<double> a(3,5);
double sum2 = my_sum(a[1]);

A simple one would have three private members, the number of rows,
columns and a double pointer. If operator[] returns a pointer to row
i, then I can't call my_sum(a[1]). If I force operator[] to return a
vector<T> it won't compile. Please help.

Thanks a lot.

Below is a snippet of the template class:
=======================================
template <class T>
class Matrix {
private:
int r;
int c;
T **dp;
public:
inline T* operator[](const int i);
inline const T* operator[](const int i) const;
};

template <class T>
inline T* Matrix<T>::operator[](const int i)
{
return dp[i];
}

template <class T>
inline const T* Matrix<T>::operator[](const int i) const
{
return dp[i];
}

May 15 '06 #1
7 2704

ch***********@gmail.com wrote:
Hi,

I'd like to implement a simple matrix class. I'd like to overload
operator []
Bad idea unless you absolutely have to for compatibility reasons. Even
then it is ill-advised and there are ways around implementing in terms
of [].

If I force operator[] to return a vector<T> it won't compile. Please help.


I can only assume, since you haven't provided the source that is
actually the problem, that you are trying to return a T* as a
vector<T>. That won't work; they are completely different and
unrelated types. You have to build and initialize your vector and
return it. Add that to the fact that your sum operator accepts its
parameter by value and you have a very inefficient implementation.

Look for an alternative.

May 15 '06 #2
Noah Roberts wrote:

ch***********@gmail.com wrote:
Hi,

I'd like to implement a simple matrix class. I'd like to overload
operator []


Bad idea unless you absolutely have to for compatibility reasons. Even
then it is ill-advised and there are ways around implementing in terms
of [].


By and in itself, overloading operator[] for a matrix class so that it
returns a proxy for a row vector is not a bad idea. It is just a little
more complicated to implement. However, the interface has a lot to offer.
For instance, the matrix class I am using allows me to express an
elementary row operation as follows:

matrix A;
...
A[i] += c * A[j];

I consider this way more expressive than, e.g.,

row_add( A, i, j, c );

where I always forget the correct order of arguments. Also,

swap( A[i], A[j] );

is very suggestive notation.

Of course, the point is not overloading the operator, a row() method,
accompanied by a col() method, will also do the trick. The important aspect
of this interface is that it allows one to operate on row and column
vectors of a given matrix not just on its coefficients.
To the OP: in order to make something like this work, you may consider
designing the matrix and vector class simultaneously. They are tightly
coupled classes since proxy objects representing a row / column have to
interact nicely with vector objects. This is non-trivial. You are probably
better off not rolling your own code. What about using one of the many
available matrix classes out there?
Best

Kai-Uwe Bux

May 15 '06 #3
ch***********@gmail.com wrote:
Hi,

I'd like to implement a simple matrix class. I'd like to overload
operator []


http://www.parashift.com/c++-faq-lit...html#faq-13.10

The two FAQs following that one are also recommended.

--
Alan Johnson
May 15 '06 #4
>I'd like to implement a simple matrix class. I'd like to overload
operator [] so that it returns as a vector (either the stl vector or
some other Vector class of my own). The reason I want to do this is
because it enables me to apply some functions of a vector to a row of
of matrix, e.g., I have a function to compute the sum of vector:
Then keep the data as vector<T> to begin with, then you can return
"const vector<T>&", to avoid constructing a new object for the return
value.

It would be more efficient to store the rows and columns in a
continuous array and compute the offset to a specified row when
required.
double my_sum(vector<double> x)


Outch. You are creating a *new* vector each time this function is
called, this will be a turtle. I take it performance is not a design
criteria, nor is memory efficiency? In that case just do:

vector< vector<T> > d; // member data in your Matrix class

If you care about abovementioned qualities, you write:

T* dp;

And then pass Matrix .. example:

double my_sum(const Matrix& m, int row)
{
const double* p = m[row];
for ( ... )
...

Or whatever. Doesn't look so nice? Then you might consider what you
will be using this FOR and re-think the API. I was merely suggesting
based on the available input.. I wouldn't necessarily write anything
like that. :)

May 15 '06 #5

<ch***********@gmail.com> wrote in message
news:11*********************@i40g2000cwc.googlegro ups.com...
Hi,

I'd like to implement a simple matrix class. I'd like to overload
operator [] so that it returns as a vector (either the stl vector or
some other Vector class of my own). The reason I want to do this is
because it enables me to apply some functions of a vector to a row of
of matrix, e.g., I have a function to compute the sum of vector:

[SNIP]

As already pointed out there is an exhaustive section about matrices and
operator overloading in the FAQ. However, I'd recommend to consider
something like the UBLAS lib (which is part of boost now), or Blitz++. There
you'll find the functionality that you're looking for and the code is
already well debugged and optimized.

Cheers
Chris
May 15 '06 #6
On Sun, 14 May 2006 19:01:46 -0700, check.checkta wrote:
Hi,

I'd like to implement a simple matrix class. I'd like to overload
operator [] so that it returns as a vector (either the stl vector or
some other Vector class of my own). The reason I want to do this is
because it enables me to apply some functions of a vector to a row of
of matrix, e.g., I have a function to compute the sum of vector:

double my_sum(vector<double> x)
{
int i, n=x.size();
double result = 0;
for(i=0; i<n; ++i) result += x[i];
return result;
}

Do this:

template <class Iterator_type>
double my_sum(Iterator_type begin, Iterator_type end)
{
double result=0;
for(Iterator_type x=begin; x!=end; x++) result += *x;
return result;
}

Now, if you have an stl::vector<double> X (or even a list<double>)
and you want to compute its sum, then you do

double s=my_sum(X.begin(), X.end());

If, on the other hand, you have a double * X of size n, then you do

double s=my_sum(X, X+n);

With your implementation of Matrix, you should then say

double s=my_sum(a[1],a[1]+a.columns());

where Matrix::rows(), Matrix::columns() trivially return r and c
respectively.

I'd like to compute the sum of the second row of a matrix:

Matrix<double> a(3,5);
double sum2 = my_sum(a[1]);

A simple one would have three private members, the number of rows,
columns and a double pointer. If operator[] returns a pointer to row
i, then I can't call my_sum(a[1]). If I force operator[] to return a
vector<T> it won't compile. Please help.

Thanks a lot.

Below is a snippet of the template class:
=======================================
template <class T>
class Matrix {
private:
int r;
int c;
T **dp;
public:
inline T* operator[](const int i);
inline const T* operator[](const int i) const;
};

template <class T>
inline T* Matrix<T>::operator[](const int i)
{
return dp[i];
}

template <class T>
inline const T* Matrix<T>::operator[](const int i) const
{
return dp[i];
}


May 16 '06 #7

Amadeus W. M. wrote:
On Sun, 14 May 2006 19:01:46 -0700, check.checkta wrote:
Hi,

I'd like to implement a simple matrix class. I'd like to overload
operator [] so that it returns as a vector (either the stl vector or
some other Vector class of my own). The reason I want to do this is
because it enables me to apply some functions of a vector to a row of
of matrix, e.g., I have a function to compute the sum of vector:

double my_sum(vector<double> x)
{
int i, n=x.size();
double result = 0;
for(i=0; i<n; ++i) result += x[i];
return result;
}

Do this:

template <class Iterator_type>
double my_sum(Iterator_type begin, Iterator_type end)
{
double result=0;
for(Iterator_type x=begin; x!=end; x++) result += *x;
return result;
}

I do like this way.

Now, if you have an stl::vector<double> X (or even a list<double>)
and you want to compute its sum, then you do

double s=my_sum(X.begin(), X.end());

If, on the other hand, you have a double * X of size n, then you do

double s=my_sum(X, X+n);

With your implementation of Matrix, you should then say

double s=my_sum(a[1],a[1]+a.columns());

where Matrix::rows(), Matrix::columns() trivially return r and c
respectively.

I'd like to compute the sum of the second row of a matrix:

Matrix<double> a(3,5);
double sum2 = my_sum(a[1]);

A simple one would have three private members, the number of rows,
columns and a double pointer. If operator[] returns a pointer to row
i, then I can't call my_sum(a[1]). If I force operator[] to return a
vector<T> it won't compile. Please help.

Thanks a lot.

Below is a snippet of the template class:
=======================================
template <class T>
class Matrix {
private:
int r;
int c;
T **dp;
public:
inline T* operator[](const int i);
inline const T* operator[](const int i) const;
};

template <class T>
inline T* Matrix<T>::operator[](const int i)
{
return dp[i];
}

template <class T>
inline const T* Matrix<T>::operator[](const int i) const
{
return dp[i];
}


May 17 '06 #8

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

Similar topics

4
by: Zenon | last post by:
Folks, I have been trying for a week but I cannot debug the following error: Error E2285 ex5.cpp 141: Could not find a match for 'matrix<complex<double>>::operator =(complex<double>)' in...
5
by: Jason | last post by:
Hello. I am trying to learn how operator overloading works so I wrote a simple class to help me practice. I understand the basic opertoar overload like + - / *, but when I try to overload more...
3
by: Drew McCormack | last post by:
Does operator() get inherited? I would have thought so, but I can't get the following to work: I have a base class that takes its derived class as a template template parameter (the ...
3
by: Sensei | last post by:
Hi. I have a problem with a C++ code I can't resolve, or better, I can't see what the problem should be! Here's an excerpt of the incriminated code: === bspalgo.cpp // THAT'S THE BAD...
51
by: Jojo | last post by:
Is there any way to get to the left-hand side of an operator? Consider the following (this is not meant to be perfect code, just an example of the problem): class Matrix { public: int data;...
5
by: tuko | last post by:
The following snipet gives a linker error. I don't get it... template<class T> class tran { public: public: private: }; template<class T> class matrix {
2
by: Steffen | last post by:
Hi, is there a simple way to use operators overloaded in some class for objects of a derived class? In my example I have a class Matrix that represents 2x2 matrices, and I overloaded...
6
by: Michael DeWulf | last post by:
I am trying to make a 2D matrix class. The data in the matrix will be of type int and so the underlying data structure will be a 2D array (int ** matrix). To make the data easy to modify, I would...
6
by: 2beagles | last post by:
So, I have not written c++ in quite a while and am trying to dig back in to it. I am running in to a weird situation and I am hoping someone might be able to explain it. I have a class...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.