Skip to content

Instantly share code, notes, and snippets.

@jmbr
Created April 13, 2012 09:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jmbr/2375233 to your computer and use it in GitHub Desktop.
Save jmbr/2375233 to your computer and use it in GitHub Desktop.
MATLAB's linspace in C++
template <typename T = double>
vector<T> linspace(T a, T b, size_t N) {
T h = (b - a) / static_cast<T>(N-1);
vector<T> xs(N);
typename vector<T>::iterator x;
T val;
for (x = xs.begin(), val = a; x != xs.end(); ++x, val += h)
*x = val;
return xs;
}
@vellamike
Copy link

I think it would be better to leave out the default argument, I get the following error:

make -k
g++ vector_plot.cpp gnuplot.cpp -o vector -lboost_iostreams -lboost_system -lboost_filesystem
gnuplot.cpp:21:43: error: default template arguments may not be used in function templates without -std=c++0x or -std=gnu++0x
make: *** [all] Error 1

Compilation exited abnormally with code 2 at Sat Jun 29 15:11:35

@garrison
Copy link

garrison commented Aug 8, 2013

Repeated addition of floating point numbers can be numerically unstable. It might instead be better to use a method similar to numpy.linspace, available at https://github.com/numpy/numpy/blob/master/numpy/core/function_base.py

@ozymandium
Copy link

A simple addition would be to set xs.back()=b, if the issue pointed out by @garrison is not a problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment