maximum, minimum and average of a matrix?
std::vector<std::vector<unsigned long> > matrix(15); // 15 rows
typedef std::vector<std::vector<unsigned long> >::iterator it_type;
it_type row = matrix.begin();
for (int w=0;w<10;w++)
{
//some lines of code
unsigned long num = x.to_ulong();
cout <<"Decimal form is: " << num<< end;
// if we've hit 15 items in the current row (i.e. 15 columns), then shift to the next row
if (row->size() == 15)
++row;
// add this to the next column in the current row
row->push_back(num);
}
// resize the last row
row->resize(15); // this will ensure that there are 15 columns in the last row
for(size_t i=0; i < matrix.size(); ++i)
{
for(size_t j=0; j < matrix[i].size(); ++j)
cout << matrix[i][j] << " ";
cout << endl;
}
Now I want to find maximum, minimum and average of this matrix. What shall I do?
Re: maximum, minimum and average of a matrix?
It would be a lot easier to achieve if you were to wrap a 1D vector in a Matrix class.
See http://www.parashift.com/c++-faq-lit...html#faq-13.10
Re: maximum, minimum and average of a matrix?
Re: maximum, minimum and average of a matrix?
A simple example.
Code:
#include <vector>
#include <algorithm>
class matrix
{
public:
matrix()
: n_columns(0),
n_rows(0)
{
}
matrix(int columns, int rows)
: n_columns(columns),
n_rows(rows),
data(columns * rows)
{
}
int operator ()(int row, int column)
{
return data[column + (row * n_columns)];
}
std::vector<int>::iterator begin()
{
return data.begin();
}
std::vector<int>::iterator end()
{
return data.end();
}
private:
std::vector<int> data;
int n_columns;
int n_rows;
};
int main()
{
matrix m(10, 20);
// Fill the matrix here.
// Find the maximum value in the matrix.
int maximum = *std::max_element(m.begin(), m.end());
// Get element at 4,6
int value = m(4, 6);
}
Re: maximum, minimum and average of a matrix?
thanks. but if i implement it this way, it gives lots of errors.
Re: maximum, minimum and average of a matrix?
Re: maximum, minimum and average of a matrix?
Quote:
Originally Posted by
JohnW@Wessex
What errors?
I couldn't find any errors, however:
Quote:
Originally Posted by
JohnW@Wessex
A simple example.
Code:
class matrix
{
matrix(int columns, int rows)
: n_columns(columns),
n_rows(rows),
data(columns * rows)
{
}
...
private:
std::vector<int> data;
int n_columns;
int n_rows;
};
You might want to be careful with your order of initialization.
Re: maximum, minimum and average of a matrix?
Quote:
Originally Posted by
monarch_dodra
You might want to be careful with your order of initialization.
The constructor initialises all of the members with the constructor parameters, so everything should be fine. Now if I'd used 'n_rows' & 'n_columns' to initialise 'data', that would be different.
I avoid dependencies of member declaration; it's too open to accidental error.