Home > OS >  Create a 2D array using vector (C ) from a set of available points
Create a 2D array using vector (C ) from a set of available points

Time:12-26

I have a set of points generated using the function linspace (similar to the one in MATLAB):

vector<double> x_coord = linspace(-5,5,11); // Output = -5 -4 -3 -2 -1 0 1 2 3 4 5 
vector<double> y_coord = linspace(-5,5,11); // Output = -5 -4 -3 -2 -1 0 1 2 3 4 5 

vector<vector<double>> coord( x_coord.size() , vector<double> (3));

 for(int i=0; i<x_coord.size();i  ){
    for(int j=0; j<x_coord.size();j  ){
        coord[i] = {x_coord[i],y_coord[j],0};
  }
 }

I want to create a 2D array "coord" using this set of points such that i have a square shaped grid. I tried doing it using the nested for loops as above but didn't get the result i wanted. Essentially coord array should be like:

-5,-5,0
-5,-4,0
-5,-3,0
-5,-2,0
-5,-1,0
-5,0,0
-5,1,0
-5,2,0
-5,3,0
-5,4,0
-5,5,0
-4,-5,0
-4,-4,0
.
.
-4,4,0
-3,-5,0
-3,-5,0
.
.
-3,5,0
.
.
.
.
5,5,0

How do i construct the array coord?

CodePudding user response:

Just keep it simple, use push_back and a range-for loop:

vector<vector<double>> coord;
coord.reserve(x_coord.size() * y_coord.size());
for(auto x : x_coord){
  for(auto y : y_coord){
    coord.push_back({x,y,0});
  }
}
  • Related