簡體   English   中英

將代碼從Matlab移植到C ++

[英]Porting code from Matlab to C++

我有一小段代碼,我正在從Matlab轉向C ++。

但是,當我嘗試顯示生成的數組中的值時,值和運行時錯誤會發生巨大變化。

XR2和YR2是具有7202個元素的陣列。 它們在代碼后更改為3201個元素。

Matlab代碼:

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 ++代碼:

#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;
}
}

當我嘗試在C ++中顯示來自YR2的值時,我得到運行時錯誤,錯誤之前顯示的值也與預期結果不同。

鏈接到輸入數據(XR和YR)和預期的輸出數據(XR2和YR2)。 數據在文本文件中。

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

閱讀發布的代碼,在我看來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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM