Search code examples
c++carraysinterpolationscaling

Scale and interpolate an array


I have a simple 1D array with some numbers (which do NOT represent anything that have to do with an image), and four elements containing e.g.

1 5 9 13

Now I want to scale this array by a factor of 3 to a size of 12 elements and interpolate the contained numbers in the new array elements linearly. So after this scale-operation the new array would contain for this example the following values:

1 2 3 4 5 6 7 8 9 10 11 12 13

My question: is there any standard C/C++ function/library/code available for this performing such an operation with different array sizes and factors? This sounds for me like it could be a standard problem where one would not have to re-invent the wheel again.

Thanks!


Solution

  • In C++20, there is std::lerp to do linear interpolation.

    But you have to call it manually after resizing the array. Something like:

    std::vector<int> grow(const std::vector<int>& v, std::size_t k)
    {
        if (v.empty()) {
            return {};   
        }
    
        std::vector<int> res(v.size() * (k - 1) + 1);
    
        for (std::size_t i = 0; i + 1 < v.size(); ++i) {
            for (std::size_t j = 0; j != k; ++j) {
                res[i * k + j] = std::lerp(v[i], v[i + 1], float(j) / k);
            }
        }
        res.back() = v.back();
        return res;
    }
    

    Demo