Hello,
I have a variable of the form t[j,i]. I would like to save these values into a 2D vector in C++…
I believe I should use the dataframe but I am a bit confuse on how to do it…
Is it possible? Anyone who knows how to do this?
Thank you!
Sam
Hello,
I have a variable of the form t[j,i]. I would like to save these values into a 2D vector in C++…
I believe I should use the dataframe but I am a bit confuse on how to do it…
Is it possible? Anyone who knows how to do this?
Thank you!
Sam
Hi Sam,
You can retrieve the values into a DataFrame with: ampl::DafaFrame df = ampl.getVariable(“t”).getValues();
After that you can use a function such as the following to convert the DataFrame into a vector of vectors.
std::vector<std::vector> dataframe_to_vector(const ampl::DataFrame &df)
{
std::vector<std::vector> data;
int nrows = df.getNumRows();
int ncols = df.getNumCols();
data.reserve(nrows);
for (auto it = df.begin(); it != df.end(); it++)
{
data.push_back(std::vector(ncols));
for (int i = 0; i < ncols; i++)
{
data.back()[i] = (*it)[i].dbl();
}
}
return data;
}
For this type of questions asking on our new forum (https://discuss.ampl.com/) is better since it works a lot better with code.
Thank you Filipe,
it doesn’t save the values as I expected though…maybe because in my variable t the number of columns depends on the number of rows through the parameter A??
var t{j in J, i in I: i<= A[ j ] } >= 0;
do I need to specify the value of A when I save the dataframe??
I apologize if I did not mention this sooner…
Thanks
Sam
Hi Sam,
The DataFrame should have three columns, one of index “i”, one for index “j”, and another for “t[i,j]”. Do you want to load this values into a matrix? You can do that as follows:
for (auto it = df.begin(); it != df.end(); it++)
{
int i = (int) (*it)[0].dbl();
int j = (int) (*it)[1].dbl();
double value = (*it)[2].dbl();
matrix[i][j] = value;
}