+ 1
Zero Matrices C++
What is the best way to create a matrix with zeros on all elements? I Know that I can create a two dimensional array and use a for to put zero in each element. But, is there a more practical way, like is in Python?
10 ответов
+ 2
Alright I realized you already knew about the for loop thing...
Well there really is no better way, sorry.
+ 1
Well, if you want convenience, you could make a function that returns a heap-allocated 2d array. It would probably look like this:
float** createMatrix(int width, int height, float fill)
{
float** rows = new float*[height];
for(int i = 0;i < height;i++)
{
rows[i] = new float[width];
for(int j = 0;j < width;j++)
{
rows[i][j] = fill;
}
}
return rows;
}
+ 1
Perhaps your compiler follows latest recommendations, so the following code will print zeroes
float x[3][4] = {0.};
for (auto i = 0; i<3;i++)
{
for (auto j = 0;j<4;j++)
printf("%.1f ", x[i][j]);
printf("\n");
}
in case of non-zero initial value there are some tricks with memcpy. But significant improvement is expected only for large arrays.
0
Not as easy as python, the easiest (and fastest) way to create a matrix would be a two dimensional array like this:
float matrix[][] = {
{0.0f, 0.0f, 0.0f, 0.0f},
{0.0f, 0.0f, 0.0f, 0.0f},
{0.0f, 0.0f, 0.0f, 0.0f},
{0.0f, 0.0f, 0.0f, 0.0f}
};
That works for column-major and row-major matrices.
Its faster than a loop because you skip all the iterations.
0
Blake Quake but this isn’t very practical. What if i wanna easily modify the size? Seems to me, that a for loop is still the better option.
0
Here is a link to the code:
https://code.sololearn.com/c84MK1AU45u3
0
in the line:
rowa[i][j] = fill;
fill is some intrinsec function? or just the number that I wanna put there?
0
C++ is not so handy there, that is true.
The easiest it can probably get is if you code yourself your own matrix class based on vectors:
http://www.cplusplus.com/reference/vector/vector/
This container is able to shrink and grow during runtime, so you can alter the size.
In that class, you can put all the functions that you want to have, the way you want it, which means you have full control over what your matrix can do.
So dependant on what you want, you'll either have to do some work yourself, or try using valarray objects (they come closest to that):
http://www.cplusplus.com/reference/valarray/valarray/
0
It would be the value passed into the parameter "fill". So yes the number you want in there should be passed to the function.
0
I'm really new to this c++ thing, so the way Blake Quake said is ok, i can understand it, about the other ones, I will need to test and see how it works. But Thanks guys... I will try it.