Porting code from Matlab to C ++

I have this small piece of code that I am transitioning from Matlab to C ++.

However, there is a huge change in values ​​and runtime errors when I try to display values ​​from my resulting array.

XR2 and YR2 are arrays with 7202 elements. After the code, they change to 3201 elements.

Matlab Code:

XR = so(1,:);
YR = so(2,:);
XR2 = XR;
YR2 = YR;
i = 1;
j = 1;

while(i<=numel(YR2))
    if(i>1)
        if(XR2(i)>0 && XR2(i-1)<0)
            j = i;
        end
    end
    if(YR2(i)<0.0)
        YR2(i) = [];
        XR2(i) = [];
        i = i - 1;
    end
    i = i +1;
end

C ++ Code:

#include <iostream>
#include <fstream>
void main()
{

vector<double> XR2(7202);
vector<double> YR2(7202);
ifstream myReadFile1, myReadFile2;
int h=0;
myReadFile1.open("XR.txt");
myReadFile2.open("YR.txt");
while (!myReadFile1.eof())
{
    myReadFile1 >> XR2[h];
    ++h;
}
myReadFile1.close();
h=0;
while (!myReadFile2.eof())
{
    myReadFile2 >> YR2[h];
    ++h;
}
myReadFile2.close();

int i = 0;
int j = 0;

while (i < XR2.size())
{
    if (i > 0)
    {
        if ((XR2[i]>0) && (XR2[i-1]<0))
        {
            j = i;
        }
    }
    if (YR2[i]<0.0)
    {
        YR2.erase(YR2.begin() + i);
        XR2.erase(XR2.begin() + i);
        --i; 
    }
    ++i;
}
}

When I try to map values ​​from YR2 to C ++, I get errors at runtime, and the values ​​displayed before the error also differ from the expected results.

Link to input (XR and YR) and expected output (XR2 and YR2). The data is in text files.

https://www.dropbox.com/sh/uy4cxi67rm9dspr/AAApawshcLxa1h0LfBC_rnLla?dl=0

+3
1

, , OP " ", .

, , OP, , , :

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <iomanip>

int main()
{

    std::vector<double> XR2,
                        YR2;

    std::ifstream ifile_xr("XR.txt"),
                  ifile_yr("YR.txt");
    if ( !ifile_xr || !ifile_yr ) {
        std::cout << "Error: unable to open input files.\n";
        return EXIT_FAILURE;
    }

    double x, y;
    while ( ifile_xr >> x  &&  ifile_yr >> y )
    {
        if ( y >= 0.0 )
        {
            XR2.push_back(x);
            YR2.push_back(y);
        }
    }

    std::ofstream ofile_xr("XR2.txt"),
                  ofile_yr("YR2.txt");
    if ( !ofile_xr || !ofile_yr ) {
        std::cout << "Error: unable to open output files.\n";
        return EXIT_FAILURE;
    }

    for ( size_t i = 0; i < XR2.size(); ++i ) {
        ofile_xr << std::setprecision(15) << XR2[i] << '\n';
        ofile_yr << std::setprecision(15) << YR2[i] << '\n';
    }

    return EXIT_SUCCESS;
}
0

Source: https://habr.com/ru/post/1649426/


All Articles