Nicholas Kunes
Nicholas Kunes

Reputation: 11

Converting a NumPy slicing loop to C++

I am porting a small Python time-series algorithm to C++ and I have been stuck on these four lines for a while.

    result = np.empty((539, 181))
for i in range(539):
    result[i, :180] = orig[i:i + 180]
    result[i, 180] = orig[i + 180] - orig[i + 180 - 1]

This is the loop I am trying to port to C++. I have limited experience in Python but I understand NumPy fairly well. I have been stuck on this port for the entire day now and have finally resorted to posting my first question on StackOverflow for help.

The concept I find hard to understand is slicing (operator :). I know (I think?) that the way to go about slicing the array in C++ would be, specific to the line 3 python code, replace i through (180 - 1) in the empty array with the orig data i through (i + 180).

I assume this is a rather easy port so hopefully someone on here could show me the C++ variant of these 4 lines and provide a walkthrough explanation of how the slice operations were implemented in C++. It just is really hard for me to grasp.

Thank you all, Nicholas

Upvotes: 0

Views: 250

Answers (1)

jackw11111
jackw11111

Reputation: 1547

    int orig[1000];
    int result[539][181] = {};

    for (int i = 0; i < 539; i++){
        //adding elements individually (instead of slicing)
        for (int j = 0; j < 180; j++){
            result[i][j] = orig[i+j];
        }
        result[i][180] = orig[i+180] - orig[i+180-1];
    }

Upvotes: 1

Related Questions