Copy an Eigen vector to a C array? - c++

How do I copy an Eigen vector mesh to a C array r?
double *r;
typedef Eigen::VectorXd RealVector;
Eigen::Map<RealVector>(r, 1, mesh.cols()) = mesh;
gives an assert from Eigen
DenseBase::resize() does not actually allow to resize.
The same message comes from either
Eigen::Map<RealVector>(r, mesh.cols()) = mesh;
or
Eigen::Map<RealVector>(r, mesh.cols(), 1) = mesh;
I need the values to be copied, not just mapped.

Since you did not clarify, I'm speculating three possible errors you could have made:
Either your mesh is actually a VectorXd, but then it will always have exactly one column, but potentially multiple rows, i.e., you need to write:
Eigen::VectorXd::Map(r, mesh.rows()) = mesh;
Or your mesh is a RowVectorXd (i.e., having one row and multiple columns). Then you need to write:
Eigen::RowVectorXd::Map(r, mesh.cols()) = mesh;
If mesh actually is a matrix, you need to decide how to map it to linear memory (i.e. row-major or column-major). This is also possible with Map:
Eigen::MatrixXd::Map(r, mesh.rows(), mesh.cols()) = mesh;

You don't have to copy anything actually. You can access the raw data using the .data() member function.
#include <Eigen/Core>
int main()
{
Eigen::VectorXd mesh = Eigen::VectorXd::Random(10);
double * r = mesh.data();
r[5] = 0; // writes to mesh directly
assert(mesh(5) == 0);
}
If you want to copy the data to the pointer, you have to allocate memory, perform the copy and deallocate after use.
#include <algorithm>
#include <Eigen/Core>
int main()
{
Eigen::VectorXd mesh = Eigen::VectorXd::Random(10);
double * r = new double[mesh.size()];
std::copy(mesh.data(), mesh.data() + mesh.size(), r);
assert(r[5] == mesh(5));
delete[] r;
}

Related

C++ using vector<vector> to represent matrix with continuous data buffer

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<float>> func(int M)
{
// res = matrix size MxM
vector<vector<float>> res;
float* buffer = static_cast<float*>(malloc(M * M * sizeof(float)));
res.reserve(M);
for (int i=0; i<M; i++) {
res.emplace_back(buffer + i * M, buffer + (i + 1) * M);
/// res[i] = compute_the_matrix();
}
return res;
}
I'm required to make a function that use vector<vector<float>> to represent a matrix. However, it's inefficient because the rows might be at different location in memory, while a good matrix should have all its element in a continuous block.
To do this, I malloc a continuous block of memory. Then initialize the vectors from this block.
Is this method safe and will the vectors free memory correctly when it's destructed? Another situation I can think of is if there's an exception in res[i] = compute_the_matrix();, then we have a memory leak.
Edit: I think this code perform copy-constructor instead of move-constructor, so it's not what I'm looking for. So, how can I make a vector that is continuous in memory?
The code doesn't do what you think it does.
The line
res.emplace_back(buffer + i * M, buffer + (i + 1) * M);
creates a new std::vector<float> to add to res. This std::vector<float> will allocate its own memory to hold a copy of the data in the range [buffer + i * M, buffer + (i + 1) * M), which also causes undefined behavior because you never initialized the data in this range.
So, in the end you are not using the memory you obtained with malloc at all for the vectors. That memory is simply leaked at the end of the function.
You can't specify what memory a vector<vector<float>> should use at all. There is simply no way to modify its allocation strategy. What you can do is etiher use a vector<float> instead to hold the matrix entries linearly indexed in a single vector or you can use a vector<vector<float, Alloc1>, Alloc2> where Alloc1 and Alloc2 are some custom allocator types for which you somehow specify the allocation behavior so that the storage layout is closer to what you want (although I doubt that the latter can be done nicely here or is worth the effort over just using the linear representation).

want to declare arrays by using constructor with variables

class matrix
{
public:
matrix();
matrix(int row, int column);
~matrix();
private:
const int DEFAULT_SIZE;
int size_row, size_column;
double *entry;
};
// main function
int
main()
{
//make a matrix of default size
matrix A; /* no error */
delete A;
//make 5 matrices of default size
matrix *B = new matrix [5]; /* no error */
delete [] B;
//make a matrix of size 15x15
matrix C(15, 15); /* no error */
delete C;
//make 5 matrices of size 15x15
matrix *D = new matrix(15, 15) [5]; /* compile error !! */
return 0;
}
//Define functions
matrix::matrix() : DEFAULT_SIZE(10)
{
size_row = DEFAULT_SIZE;
size_column = DEFAULT_SIZE;
entry = new double [size_row*size_column];
}
matrix::matrix(int row, int column) : DEFAULT_SIZE(10)
{
size_row = row;
size_column = column;
entry = new double [size_row*size_column];
}
matrix::~matrix()
{
delete [] entry;
}
I'm studying about constructor.
I'd like to declare arrays by using constructor with variables.
Can you correct my code line?
Please see the line below '//make 5 matrices of size 15x15'
Also, in this case, how can I use destructor?
To make an array of 5 elements that each get constructed with (15,15), you could do the following in C++11:
matrix* D = new matrix[5]{
{15,15}, {15,15}, {15,15}, {15,15}, {15,15}
};
But it would be much simpler to just use a vector:
std::vector<matrix> D(5, {15,15}); // C++11
std::vector<matrix> D(5, matrix(15,15)); // pre-C++11
After looking at your source code here is what I have seen! In your class for your private members your row and column sizes should not be of type int, they should be unsigned int. The reason they should be unsigned int is because an int without an unsigned is a signed value by default which means it can have negative numbers. For the amount of rows and columns in a matrix that does not make sense. With an unsigned int value it ranges from [0, max_value] of an unsigned int. Another thing to take care in is what if someone entered in 0 for either the row or column size or both? Then you would still not have a valid matrix. A little logic needs to be done here; if someone enters in a 0 for either then you have to make a decision as what the default behavior should be. Do you want to use the default value of 10? Also a value of 1x1 does not make sense either! Now you could have 1x4 or 4x1 then these would not be exactly a Matrix but they would be vectors that are either row or column major in order. In my honest opinion your default matrix size from the base constructor without any arguments should be 2x2. If a user specifies 1 for either parameter then the other parameter should be greater then 1. Also there is no need for 2 constructors here, this is duplicate code and can be done with just 1 constructor. Also there is no need to call your destructor, this gets automatically called when this class object goes out of scope.
For matrices would you think that the elements should be public for easy access?
Right now as it stands your (element) array is private meaning no outside class can access them, now if this is the behavior you want then you will need functions to access them and to set them if the values need to change.
Based on your class implementation here is what I did to show you the changes I have mentioned above.
#include <vector>
#include <array>
class Matrix {
private:
const unsigned int DEFAULT_SIZE;
unsigned int size_row, size_column;
double* elements;
public:
explicit Matrix( unsigned int row = 0; unsigned int column = 0 );
~Matrix();
// Copy Constructor
Matrix( const Matrix& c );
// Operator = Needed
Matrix& operator=( const Matrix& c );
}; // Matrix
Matrix::Matrix( unsigned int row, unsigned int column ) : DEFAULT_SIZE(2) {
// Check if both are 0 Or both are 1 - use default sizes
if ( (row == 0 && column == 0) ||
(row == 1 && column == 1) ) {
row = DEFAULT_SIZE;
column = DEFAULT_SIZE;
}
// Check [Row,Column] For [0,1] && [1,0]
if ( row == 0 && column == 1 ) {
row = 1;
column = DEFAULT_SIZE;
} else if ( row == 1 && column == 0 ) {
row = DEFAULT_SIZE;
column = 1;
}
size_row = row;
size_column = column;
element = new double[size_row * size_column];
} // Matrix
Matrix::~Matrix() {
delete [] elements
} // ~Matrix
Matrix::Matrix( const Matrix& c ) : DEFAULT(2) {
this->size_row = c.size_row;
this->size_column = c.size_column;
this->element = c.element;
} // Matrix(copy)
Matrix& Matrix::operator=( const Matrix& c ) {
// Assignment Can Only Happen If Both Matrices Are Of The Same Dimensions:
// You can not set a 4x3 = 6x9 for this does not make sense
if ( (this->size_row == c.size_row) &&
(this->size_column == c.size_column) ) {
this->element = c.element;
return *this;
} // operator=
As for the code in your main function I see a few errors that need to be fixed. The first two lines:
Matrix A;
delete A;
You are declaring Matrix A; then on the next line you are calling delete on A.
This is your first error: A is an instance of Matrix. This is a local stack variable that belongs to the scope of the main function. There is no need to call delete on this! When your instance of Matrix (A) goes out of scope the Matrix::~Matrix() is called implicitly for you behind the scenes, there is no need to invoke it.
Your next two lines of code:
Matrix* B = new Matrix[5];
delete [] B;
These two are correct and there are no problems here. You instance B is a pointer to a type object Matrix and because new is used here it is created on the heap and because you have [5] B is not just a pointer to this type but is a pointer on the heap to the first address of you dynamically allocated array. Then you call delete with the [] operator on B which is correct.
Your next two lines of code:
Matrix C(15,15);
delete C;
You are declaring an instance of a Matrix object called C on the stack where you are now using your defined constructor. Again on the second line here there is no need to call delete on C.
As for your last 2 lines of code this is not as simple as trying to do want you want but isn't all that trivial. In order for you to create your dynamic array of Matrices that all have a default size of 15x15 needs a little more work. In order to do this properly you can see from the class implementation that I added a Copy Constructor and an overloaded = operator. There are three steps to achieve this.
// First Step - Create A Single Stack Instance With Size [15,15]
Matrix D = Matrix( 15, 15 ); // This Will Be Used Later To Populate Your Array
// Second Step - Create An Array of 5 Matrices On The Heap
Matrix* E = new Matrix[5]; // Right Now All Five Are Using Default Size 2x2.
// Step Three Now We Update Them Using Our operator=()
for ( unsigned int i = 0; i < 5; i++ ) {
E[i] = D;
}
// Then Delete the Array
delete [] E; // Only Need To Delete E
However This WILL NOT WORK: Due to how our operator=() is defined! So how do we achieve this? There are two ways and both work. So You Can Remove Matrix E, the for loop and the delete [] E lines. Leave the Matrix D for that will be needed!
The First is easier: If you noticed I included both vector and array from the STL for this case I will use the vector class since it is the most commonly used.
// We already have: Matrix D = Matrix( 15, 15 );
// You Want an Array of 5
std::vector<Matrix> vMatrices; // This will create a vector of stack Matrices but at first it will be "EMPTY"
for ( unsigned int i = 0; i < 5; i++ ) {
vMatrices.push_back( D );
}
// Now You Have A vector of 5 Matrices.
// If You Want Vector of Pointers
std::vector<Matrix*> vpMatrices;
for ( unsigned int i = 0; i < 5; i++ ) {
vpMatrices.push_back( &D );
}
// To clean up your vectors you can simply do
vMatrices.clear();
vpMatrices.clear();
// The Other Way Would Be To Use std::array but it is less commonly used.
// If You know you will only ever need a set amount this works good
std::array<Matrix, 5> aMatrices;
for ( unsigned int i = 0; i < 5; i++ ) {
aMatrices.at(i) = D;
}
// For Holding Pointers
std::array<Matrix*, 5> apMatrices;
for ( unsigned int i = 0; i < 5; i++ ) {
apMatrices.at(i) = &D;
}
// To Clean Up std::array To Be Honest Not really sure for I do not use them
// But using it here just as an illustration that there are plenty of predefined containers
// to use to hold multiple elements of the same data type.
As a final note about your class, you are creating your size of your matrices and have the elements array defined based on size, however being that everything is private, you have no way to populate it or to access it. Keeping it private means you would have to implement functions to do this and considering the nature of matrices either for them to "Store" data or "Function Calls" or Being a Mathematical Object of Calculations and Operations. You do not want the overhead of accessory functions for this would be a performance hit. There is nothing wrong with keeping the size of the row and columns private, for there is no need to access these outside of the class once they have been defined. But your single dimensional array that is representing your MxN matrix should be publicly defined. Also you should have operator[] defined as well.
If you want to see how a basic math library implements matrices take a look at GLM's math library that is written to work with OpenGL shader language GLSL.
This library is an Headers Only Library. No need to link or include *.dlls or *.libs. All you need to do is store it into a folder on you computer and set you system to have an environment variable that points to its main folder. Then in you IDE if you are using VS all you have to do in the additional include section of the projects properties is use the environment variable defined. This is for using it! But to just look over its contents you can just down load it to any folder and open any of the *.h files. Then you can see how they implemented Matrix classes! You will notice that they are template types and they have predefined types of matrices such as mat2x2, mat2x3, mat2x4, mat3x2, mat3x3, mat3x4, mat4x2, mat4x3, & mat4x4. This is do to the nature of writing Programs and Shaders that are focused on 2D and 3D Graphics so the min required is a 2x2 and the largest that is truly needed is a 4x4. They also have vector classes defined of different sizes, and your matrices can be constructed from different size vectors. But this should serve as a guideline. Here is their link
GLM

void pointer to vector elements

I want to have a void pointer to a vector.
void *para;
vector<double> x(2);
x[0] = 0;
x[1] = 1;
para = &x;
I can now use the vector like this.
vector<double> k = *(static_cast<vector<double>*>(para));
cout << k[0] << "\n";
Now I want to access the elements of the vectors through the pointer. How can I do that? But now I want to get the elements of the vector x, directly via the void pointer para, without using the new vector k. Something like this:
double k = ??? // here should be the element of x via para
Thank's in advance.
Now I want to access the elements of the vectors through the pointer.
This has two steps: reinterpret the pointer as a vector, then access elements.
How can I do that? But now I want to get the elements of the vector x, directly via the void pointer para, without using the new vector k.
void *para;
vector<double> x(2);
para = &x;
// step 1: reinterpret the pointer as a vector
auto *voidToVector = reinterpret_cast< vector<double>* >(para);
// step 2: access elements
double k = (*voidToVector)[0];
That said, please DON'T store data in your application as void*. Every time you do, you can assume that a developer will probably see it later and die a bit inside (and that developer may even be you).
Edit:
For the calculation in the function, I need to access the elements of the vector, vector>>> accel; Is there a better way????
Consider this:
class FourDimensionalVector
{
public:
FourDimensionalVector(std::size_t x, std::size_t y, std::size_t z, std::size_t a)
: d1{x}, d2{y}, d3{z}, d4{a}
, data{ d1 * d2 * d3 * d4 }
{
}
// ALL access to the vector elements can/should be done through this
double& operator()(std::size_t x, std::size_t y, std::size_t z, std::size_t a)
{
assert(d1 > x); // same for the other dimensions
return data[x * d1 + y * d2 + z * d3 + a];
}
// implement other interface elements here (iteration access, reading the size,
// resetting the values, etc.
private:
std::size_t d1, d2, d3, d4;
std::vector<double> data; // store flattened data
};
With this, you just pass a reference to the data as a parameter, and edit it as needed. I'm not sure the indexing logic is OK (and the code is incomplete), but the idea is the same.
Client code:
void YourFunction(FourDimensionalVector& fdv)
{
fdv[2, 3, 4, 0] = fdv[2, 3, 4, 0] + 0.38;
}
This solution is strongly typed, efficient and clean (it avoids the casting completely and the void*).
[edit by Jojia]: But what is the difference between your solution and this one
vector<vector<vector<vector<double>>>> Xaccel;
void initialize(&Xaccel); //This function initializes values for all elements of Xaccel
void myfunction(&Xaccel){
double x = Xaccel[0][0][0][0];
}
I don't see any difference to your solution. BUT: I thought passing these large objects to the function myfunction might be a problem. Is that correct?
[edit by utnapistim]:
From a semantical point of view, they are the same: both send the same data to the function and allocate the same memory (my solution also stores dimensions, but whatever).
From a maintenance/reusability/testability/modularity point of view, they are quite different: my solution abstracts away the fact that your four dimensional matrix is a vector (of vector of vector ... ).
This will allow you to write your client code using a 4d matrix interface (which you can implement to match the needs of your client code) instead of a vector, and allow you to define your operations in terms of a matrix.
For example, the vector<vector<vector<double>>> code can be used to create a sparse/asymetrical matrix (with the first line in the outer vector being three times longer than the second line and so on). The matrix class would prevent that by cutting access to the vector.
If you choose to keep the vector<vector...> solution, at least typedef it:
typedef vector<vector<vector<double>>> FourDMatrix;
FourDMatrix Xaccel;
void initialize(FourDMatrix& Xaccel);
void myfunction(FourDMatrix& Xaccel);
In this line you create a copy:
vector<double> k = *(static_cast<vector<double>*>(para));
So one of the solution would be to use reference instead:
vector<double> &k = *(static_cast<vector<double>*>(para));
k[0] = 123;
Or pointer
vector<double> *pk = static_cast<vector<double>*>(para);
(*pk)[0] = 123; // but usage is more explicit, so reference would be better
I assume you know what you are doing and you really need to pass vector through a void *. One of the reasons could be passing pointer to vector as a cookie to C API that expects void *. Note there is very low chance to have a good reason to use void * in c++ itself, you should use boost::any or boost::variant for type safety.

How to access a dynamically allocated matrix in c++?

I have created a dynamic matrix of class objects but i have made a big mess with handling the returned pointers.
My intention is to create a matrix of class Point( Int x,Int y) and later to use it in different ways in the program.
Everything is working but i can't figure out the returned pointers game between the functions.
class Point
{
private:
int x;
int y;
public:
Point(int x,int y);
void SetPoint(int x,int y);
};
In a second class I use a Point object as class member.
Init_Pallet() is used to Initialize the Matrix.
class Warehouse
{
private:
Robot r1,r2;
Point *Pallet_Matrix;
public:
Point* Init_Pallet();
};
This is the Init function
Point* Warehouse::Init_Pallet()
{
int rows =10,cols =10;
Point** Pallet_Matrix = new Point*[rows];
for (int i = 0; i < rows; i++)
Pallet_Matrix[i] = new Point[cols];
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; j++) //Pallet matrix Init, x point for robots amount in position and y for box amount
Pallet_Matrix[i][j].SetPoint(0,0);
return *Pallet_Matrix;
}
The Init function is called by WareHouse C'Tor (ignore the other vars)
Warehouse::Warehouse(Robot p_r1,Robot p_r2): r1(p_r1),r2(p_r2)
{
this->r1=p_r1;
this->r2=p_r2;
Point *p =Init_Pallet();
this->Pallet_Matrix=p;
}
My question is: How do I return the address to the beginning of the matrix from the Init function to the C'Tor who called it?
And second question: how do i access the matrix different locations in the format of Matrix[i][j] after returning the matrix adress to the C'Tor.
Thank you in advance for all the help and your time.
You should just have Init_Pallet return a Point** and then do return Pallet_Matrix;. Currently you're copying one of the Point*s that you allocated out of the function, so the copy is no longer part of a contiguous array that you can index.
Don't forget to delete[] the dynamically arrays in your destructor.
However, you should much prefer to use the standard library containers like std::array or std::vector. Then you don't need to worry about the dynamic allocation yourself and no pointers to get in a mess with.
If I were doing it, I would just have:
class Warehouse
{
public:
Warehouse() : Pallet_Matrix() { }
private:
Robot r1,r2;
std::array<std::array<Point, 10>, 10> Pallet_Matrix;
};
And that's it. No init needed. No dynamic allocation. No assigning 0 to every element (if you give Point a default constructor that zero-initialises). Done.
How do I return the address to the beginning of the matrix from the Init function to the C'Tor?
In case you would really need just an address of first element, pretty straightforward would be:
return &Pallet_Matrix[0][0];
how do i access the matrix different locations in the format of Matrix[i][j] after returning the matrix address
Init_Pallet is a member function, which could simply work with the Pallet_Matrix member directly. Otherwise, the Init_Pallet function could actually return Point**, which should however make you feel that something's wrong with this code.
Better[1] solution would be:
Define the default constructor for Point:
class Point
{
public:
Point() : x(0), y(0){}
...
Use std::vectors instead of dynamically allocated arrays:
class Warehouse
{
private:
std::vector< std::vector<Point> > Pallet_Matrix;
and instead of:
Point *p =Init_Pallet();
this->Pallet_Matrix=p;
you would simply use std::vector's constructor:
int rows = 10, cols = 10;
Pallet_Matrix = std::vector< std::vector<Point> >(rows, cols);
[1] Better = You don't want to handle the memory management on your own.
The problem is that the returned type of Init_Pallet() is wrong — its a row, not a matrix. And in the last line of Warehouse::Init_Pallet() you dereference the proper pointer to matrix obtaining the pointer to the first row of the matrix.
You need to write Point **Pallet_Matrix; in Warehouse, use Point** Warehouse::Init_Pallet() definition of Init_pallet(), and return Pallet_Matrix in the last line of Init_Pallet().
The notation Point *row means the row is "the array of points" or "the pointer to the beginning of the array of points". The notation Point **matrix means the matrix is "the array of pointers to the beginnings of the arrays of points" or "the pointer to the beginning of such an array".
First: are the dimensions really constant, or is this just an
artifact of your having simplified the code for posting? If
they are really constant, there's no need for dynamic
allocation: you can just write:
Point palletMatrix[10][10];
and be done with it. (If you have C++11, it's even better; you
can use std::array, and palletMatrix will have full object
semantics.)
If you do need dynamic indexes, the only reasonable way of
doing this is to write a simple matrix class, and use it:
class Matrix
{
int m_rows;
int m_columns;
std::vector<Point> m_data;
public:
Matrix( int rows, int columns )
: m_rows( rows )
, m_columns( columns )
, m_data( rows * columns, Point( 0, 0 ) )
{
}
Point& operator()( int i, int j )
{
return m_data[ i * m_columns + j ];
}
// ...
};
Trying to maintain a table of pointers to tables is not a good
solution: it's overly complex, it requires special handling to
ensure that each row has the same number of columns, and it
generally has poor performance (on modern machines, at least,
where locality is important and multiplication is cheap).
Note too that the actual data is in an std::vector. There are
practically no cases where a new[] is a good solution; if you
didn't have std::vector (and there was such a time), you'd
start by implementing it, or something similar. (And
std::vector does not use new[] either.)
EDIT:
One other thing: if you're putting Point in a matrix, you might
want to give it a default constructor; this often makes the code
simpler.

Creating a dynamic 2D array

I need to have a 2D array of double.
Its width is around 900. Its height as well (the same width value).
Dealing with two loops (one for the width and one for the height), I really need to get access to all the pixels of the 900X900 image that I will process.
The size of the array is too big (error when specifying the number of raw and column).
I thought about establishing that with a dynamic array to optimize the time of calculation and to free the memory everytime I deal with one pixel on the two loops.
But I really cannot find the syntax I would like to have to declare a 2D dynamic array (malloc, setting array element values and freeing the memory).
Wrap it in a class:
class Matrix2D {
typedef std::vector<double> Column;
std::vector<Column> columns;
public:
Matrix2D(unsigned int width, unsigned int height) :
columns(width, Column(height)) {
}
double& at(unsigned int i, unsigned int j) {
return columns[i][j];
}
};
Matrix2D matrix(900, 900);
matrix.at(45, 65) = 1234.5678;
I need to have a 2D array of double
Since you are using C++ you should use STL classes that will take care of ugly memory management for you. So you are actually looking for std::vector< std::vector<double> >, or for the sake of the readability of your code:
#include <vector>
typedef std::vector<double> DVector; // row represented by vector of doubles
typedef std::vector<DVector> MyVector; // 2D array as a vector of these rows
And then avoid using dynamic allocation wherever it's possible to do so. Take advantage of RAII idiom:
{
MyVectorarr; // vector object with automatic storage duration
} // <-- vector is automatically destructed when execution goes out of scope
Questions that might help you:
Multi-dimensional vector
Initialization of a vector of vectors?
vector of vector
I associate malloc with pure C, not C++ (as the prior answer points yout, you should use std::vector). However, if you really want to:
// allocate the memory in a block
double* block = (double *) malloc(sizeof(double) * xSize * ySize);
// allocate memory for the accessor array
double* accessor = (double*) malloc(sizeof(double*) * xSize);
// assign memory addresses
double* curPtr = block;
for (int i = 0; i < xSize; ++i) {
accessor[i] = curPtr;
curPtr += ySize;
}
// you can now access the array via accessor[x][y]
// now need to free malloced memory:
free(accessor);
free(block);
If you do it this way, I highly suggest tying it to the RAII pattern, otherwise you'll eventually get a memory leak. Using the STL's containers is a better approach.