Home > Blockchain >  create a matrix with condition in C
create a matrix with condition in C

Time:02-15

I want to create a matrix B from a matrix A, in C .

First column of A is distance D1, second column is distance D2. Matrix B copies the same columns (and rows) of A, except when in A it happens that D2-D1=delta exceeds a threshold. In this case, the row of A is break in two rows in B.

I wrote an algorithm, but the problem is that it gives segmentation fault. Someone can help, why it happens?

std::vector<float> newD1(10), newD2(10);
float box=5.;
int j=0;
for(auto i=0;i<D1.size();i  ){
    float delta=D2[i]-D1[i];
      if (delta>box){ //break row i in two rows: j and j 1
        //first half of row i goes in row j
        newD1[j]=D1[i];
        newD2[j]=(D1[i] D2[i])/2.;
        //second half of row i goes in j 1
        D1[j 1]=(D1[i] D2[i])/2.;
        D2[j 1]=D2[i];
        j=j 2; //we skip two row because we break up the original row in 2 rows
      }
      else{
       newD1[j]=(D1[i]);
       newD2[j]=D2[i];
       j=j 1; //we skip one row because the original row is unchanged
      }
    }

Here I give you an example of matrix A and B; I also specify delta beside each line of the matrix.

Matrix A:

    #D1 D2        delta
    |0   5  |     5
A=  |5   15 |     10   }--> exceed the threshold, delta>5. Must break in 2 rows in `B`
    |15  17 |     2
   

B is created breaking the second line in two lines, because delta>5 :

      #D1 D2     delta
    |0   5  |     5
B=  |5   10 |     5 }--> created from row #2 of `A`. `D2` is midpoint between`D1` and `D2` in row #2 in `A`
    |10  15 |     5 }--> created from row #2 of `A`. `D1` is midpoint between`D1` and `D2` in row #2 in `A`
    |15  17 |     2
   

CodePudding user response:

1.You can use push_back to avoid the size definition

2.You updated D1 and D2 instead of newD1 and newD2

  #include <vector>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        std::vector<float> D1 = { 0,5,15 };
        std::vector<float> D2 = { 5,15,17 };
        std::vector<float> newD1, newD2;
    
        float box = 5.;
        for (auto i = 0; i < D1.size(); i  ) {
            float delta = D2[i] - D1[i];
            if (delta > box) { //break row i in two rows: j and j 1
              //first half of row i goes in row j
                newD1.push_back(D1[i]);
                newD2.push_back((D1[i]   D2[i]) / 2.);
                //second half of row i goes in j 1
                newD1.push_back ((D1[i]   D2[i]) / 2.);
                newD2.push_back (D2[i]);
            }
            else {
                newD1.push_back(D1[i]);
                newD2.push_back(D2[i]);
            }
        }
    }
  • Related