MatLab linspace function written in C++

relevant Matlab code con be found in
...\toolbox\matlab\elmat\linspace.m

This function generates N points between min and max.

vector<double> linspace(double min, double max, int n)
{
 vector<double> result;
 // vector iterator
 int iterator = 0;

for (int i = 0; i <= n-2; i++)
 {
 double temp = min + i*(max-min)/(floor((double)n) - 1);
 result.insert(result.begin() + iterator, temp);
 iterator += 1;
 }

//iterator += 1;

result.insert(result.begin() + iterator, max);
 return result;
}
Advertisements

One thought on “MatLab linspace function written in C++

  1. template
    std::vector linspace(const T& lo, const T& hi, const int32_t& N)
    {
    T incr = (hi – lo) / (N-1);
    std::vector res(N);

    for(int i = 0; i < N; ++i)
    {
    res[i] = lo + i * incr;
    }

    return res;

    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s