Operations with arrays - c++

I have to code a program using C++ at university.
They asked me to type all elements of a 3x3 matrix. And all elements have to be positive. So far so good. Each row of the matrix represents the components of a R^3 vector. So there are three vectors (Three 1D arrays). I had to calculate the modulus of each vector and successfully did it.
Here comes the problem... The next step is to get which vector the largest modulus has, and return its position. All this using a function --> int largestModulus (int Modulus[3]). How can I do that? Because it is all about comparing but this time is comparing a vector, and I only know how to compare different single elements. Thanks for your help!!

In the arguments to the function,
since you're passing and receiving a 2D matrix, the parameter must be
int largestModulus (int Modulus[][3])

Related

Multiply two Eigen vectors by corresponding elements

I have two Eigen vectors (vectorOne and vectorTwo) of my defined type( see below for my type).
typedef Matrix<double, 50, 1> myVector;
I want a third vector vectorThree that will have multiplication of vectorOne and vectorTwo. But I want to multiply each element by corresponding element - i.e. vectorOne(i, 0) by vectorTwo (i, 0) so that I have something like below for all i.
vectorThree (i, 0) = vectorOne(i, 0) * vectorTwo(i, 0)
I saw this and tried vectorOne.array() * vectorTwo.array() but it did not work.
I know I can do that using a for loop and iterating over all elements. But is there a more efficient or built in Eigen function for that?
You should be able to cast matrices to arrays via .array() and multiply it here. It would return an array expression though, so maybe it is not what you want.
From Eigen documentation:
First of all, of course you can multiply an array by a scalar, this works in the same way as matrices. Where arrays are fundamentally different from matrices, is when you multiply two together. Matrices interpret multiplication as matrix product and arrays interpret multiplication as coefficient-wise product. Thus, two arrays can be multiplied if and only if they have the same dimensions.
Otherwise you can use .cwiseProduct of matrix to get matrix as result.
https://eigen.tuxfamily.org/dox/group__QuickRefPage.html#matrixonly

How to determine if an element in a multidimensional array is empty

I am working on a magic square problem that uses a dynamic matrix of size n*n. It fills the matrix with numbers 1-n^2, and the sum of each row, column, and diagonal must be the same. One of the conditions of the algorithm is to check if an element in the matrix already had a number input in it during one of the loops. I am having problems checking if one of the elements in the matrix already had a number inputed in it, so I am wondering how to check if an element is empty.
Here is my code for that portion of the algorithm:
else if(matrix[row][col] != 0)
{
row = row + 2;
col--;
}
For some reason it triggers this if statement on the 5th iteration of the encompasing loop. I have worked it out on paper using the algorithm for a magic square, and the 5th iteration of the loop brings it to an empty element in the matrix. I thought that if an element is empty it holds the value 0? I appreciate any help as I am very confused. Thank you.
Array's in C and C++ are not empty by default. You need to explicitly set the elements to 0 or create the array in such a way that they are initialized to 0.
What you are facing is Undefined Behavior. The uninitialized array has some random(read garbage) values and accessing those results in a Undefined behavior.
Array's created at global scope or with a static qualifier will be initialized to 0 or you can use initialization provided built in by the language or you can explicitly set each element to 0.
There are multiple ways of doing so, the best one depends on what behavior you want to extract from the array.

(C++) Initializing and Declaring elements within a Two Dimensional Vector

I'm having an awkward result when I run my program after creating this 2D vector. The program actually crashes when it launches. But I'm basically trying to input a set of data for a 2D vector that is meant to retain the amount of bushels of certain crops in the first column (as ints), and then to retain the yield ratio of each crop (as an int). I haven't declared the yield ratio yet, but even if the 2nd column is left empty (in terms of each element's value) it shouldn't have a problem. Here's my code:
vector<vector<int> >crops(2, vector<int>(43));
crops[0][0]=0; //Arugula
crops[1][0]=2000000; //Beans
crops[2][0]=0; //Beets
crops[3][0]=0; //Cabbages
crops[4][0]=0; //Cammomile
crops[5][0]=0; //Carrots
crops[6][0]=0; //Catmint
crops[7][0]=0; //Celery
crops[8][0]=0; //Coriander
crops[9][0]=0; //Corn
crops[10][0]=0; //Cucumbers
crops[11][0]=0; //Eggplants
crops[12][0]=2000000; //Fennel
crops[13][0]=1500000; //Flax
crops[14][0]=0; //Garlix
crops[15][0]=0; //Greenwoad
crops[16][0]=0; //Hem
crops[17][0]=0; //Leeks
crops[18][0]=0; //Lettuce
crops[19][0]=0; //Madder
crops[20][0]=0; //Mint
crops[21][0]=0; //Mustard
crops[22][0]=5000000; //Oats
crops[23][0]=0; //Onions
crops[24][0]=0; //Parsnips
crops[25][0]=0; //Parsely
crops[26][0]=2500000; //Peas
crops[27][0]=0; //Poppy
crops[28][0]=0; //Potatoes
crops[29][0]=0; //Pumpkins
crops[30][0]=0; //Radishes
crops[31][0]=0; //Rutabagas
crops[32][0]=0; //Spinach
crops[33][0]=4000000; //Spring Barley
crops[34][0]=0; //Squash
crops[35][0]=0; //Tomatoes
crops[36][0]=0; //Turnips
crops[37][0]=0; //Vetches
crops[38][0]=0; //Weld
crops[39][0]=0; //Woad
crops[40][0]=6000000; //Barley - Winter Crop
crops[41][0]=5000000; //Mixtill - Winter Crop
crops[42][0]=4000000; //Wheat - Winter Crop
Though, I have to leave for work now, but I will be able to respond to any answers once I return tonight. Thank you for those who are trying to help! :)
Swap your subscript indices.
crops[13][0] -> crops[0][13]
When you declared
vector<vector<int> >crops(2, vector<int>(43));
You created a vector which is value-initialised with 2 vectors, each of which was value-initialised with 43 ints (meaning they are initialised to 0). There are two vectors in the outer vector so you can only do crops[0] or crops[1] without reading someone else's memory.
Alternatively, of course, you could just change the declaration to:
vector<vector<int> >crops(43, vector<int>(2));

How to get dimensions of a multidimensional vector in C++

all
I am using multidimensional STL vector to store my data in C++. What I have is a 3D vector
vector<vector<vector<double>>> vec;
What I want to retrieve from it is :
&vec[][1][]; // I need a pointer that points to a 2D matrix located at column 1 in vec
Anyone has any idea to do so? I would be extremly appreciate any help!
Regards
Long
It is best to consider vec just as a vector whose elements happen to be
vectors-of-vectors-of-double, rather than as a multi-dimensional structure.
You probably know, but just in case you don't I'll mention it,
that this datatype does not necessarily represent a rectangular cuboid.
vec will only have that "shape" if you ensure that all the vectors are
the same size at each level. The datatype is quite happy for the vector vec[j]
to be a different size from the one at vec[k] and likewise for vec[j][n]
to be a vector of different size from vec[j][m], so that your structure is "jagged".
So you want to get a pointer to the vector<vector<double>> that is at
index 1 in vec. You can do that by:
vector<vector<double>> * pmatrix = &vec[1];
However this pointer will be an unnecessarily awkward means of accessing that
vector<vector<double>>. You certainly won't be able to write the
like of:
double d = pmatrix[j][k];
and expect to get a double at coordinates (j,k) in the "matrix addressed
by a pmatrix". Because pmatrix is a pointer-to-a-vector-of-vector-of-double;
so what pmatrix[j] refers to is the vector-of-vector-of-double (not vector-of-double)
at index j from pmatrix, where the index goes in steps of
sizeof(vector<vector<double>>). The statement will reference who-knows-what
memory and very likely crash your program.
Instead, you must write the like of:
double d = (*pmatrix)[j][k];
where (*pmatrix) gives you the vector-of-vector-of-double addressed by pmatrix,
or equivalently but more confusingly:
double d = pmatrix[0][j][k];
Much simpler - and therefore, the natural C++ way - is to take a reference,
rather than pointer, to the vector<vector<double>> at index 1 in vec. You
do that simply by:
vector<vector<double>> & matrix = vec[1];
Now matrix is simply another name for the vector<vector<double>> at index 1 in vec,
and you can handle it matrix-wise just as you'd expect (always assuming
you have made sure it is a matrix, and not a jagged array).
Another thing to consider was raised in a comment by manu343726. Do you
want the code that receives this reference to vec[1] to be able to
use it to modify the contents of vec[1] - which would include changing its
size or the size of any of the vector<double>s within it?
If you allow modification, that's fine. If you don't then you want to get
a const reference. You can do that by:
vector<vector<double> > const & matrix = vec[1];
Possibly, you want the receiving code to be able to modify the doubles
but not the sizes of the vectors that contain them? In that case, std::vector
is the wrong container type for your application. If that's your position I
can update this answer to offer alternative containers.
Consider using matrix from some linear algebra library. There are some directions here

3d -> 1D array indexing

in C++, what is the indexing value for a W * H * D sized 3D array?
for a particular i, j, k is this the correct indexing:
i*W*H+j*W+k
What you have written is equivalent to the pointer arithmetic that this would do:
T x[D][H][W];
x[i][j][k]; // Pointer arithmetic done here
Obviously, depending on how you order D, H and W (or i, j, k), the calculation will differ.
There is no one "correct" order, but the version you've given should work. The order in which you apply the indices will determine whether you do row-major or column-major indexing. If you're porting Fortran code (for example) it can make sense to reverse the "normal" C order.
Width, height and depth are meaningless in this context. What you need to know is that multidimensional arrays are stored in row-major order.
Yes, assuming i varies from 0 ... D-1, j varies from 0 ... H-1, and k varies from 0 ... W-1.
Usually, though, the purpose of having an indexer, I thought, was to express relations within a sparse matrix so you didn't need to deal with the whole thing (and expend memory for it). If your data span the whole matrix, you might look into creating the 3d matrix as a pointer to an array of pointers, which themselves each point to an array of pointers. Using this allows you to use the x[i][j][k] notation but may be faster.
See http://www.nr.com/cpppages/chapappsel.pdf for a description.
If you need to to iterarate over all elements it is best to do in
for i
for j
for k
order. This way, it would be fastest, because index of array is incremented by one each time and values could be precached.
There is no only one correct way to do this but you probably chose best one.