Does Mathematica have an equivalent to Matlab's linspace? I want to make a list with "start", "stop" and "number of points". What is the neatest way of doing this?
Asked
Active
Viewed 2.0k times
28
cormullion
- 24,243
- 4
- 64
- 133
Vibhor Singh
- 381
- 1
- 3
- 4
2 Answers
31
There was an update for Array, not done to the end. The method below does not work for earlier versions even though that Array is
New in 1 | Last modified in 4
Moreover WRI forgot to update docs for error messages: Array::plen - the first example gives no error in V9.
V9
Array[# &, n, {start, stop}]
Array[# &, 10, {-1, 1}]
{-1, -(7/9), -(5/9), -(1/3), -(1/9), 1/9, 1/3, 5/9, 7/9, 1}
V<9
ClearAll[linespace];
linespace[s_, f_, 1] := (f + s)/2
linespace[s_, f_, n_] := Range[s, f, (f - s)/(n - 1)]
Kuba
- 136,707
- 13
- 279
- 740
6
You could use table... unless I am missing something really basic. Speed, maybe? Edited to consider the special case as suggested by Kuba.
linspace[start_, stop_, n_:100] := Table[x, {x, start, stop, (stop - start)/(n - 1)}]
linspace[start_, stop_, 1] := Mean[{start,stop}]
Peltio
- 5,516
- 3
- 27
- 27
-
-
Ah, ok. My procedures are written with the implicit disclaimer "this will help you aim at your foot, it's up to you not to pull the trigger". Well, it can be overloaded to consider the special case. – Peltio Nov 29 '13 at 18:24
-
I like this disclaimer :) but notice that I'm not reminding about negative numbers, strings etc. but about little function deficiency. – Kuba Nov 29 '13 at 18:36
-
I certainly appreciate feedback. So, basically, this special case could arise within some automated task that could compute the number of points and come up with the special, and apparently useless case n=1. Before writing my post I had a look at the web documentation for linspace for MATLAB and this special case is not mentioned. Actually, I see now this http://cens.ioc.ee/local/man/matlab/techdoc/ref/linspace.html is the first page that came up but it appears it is not on Mathworks servers. So my bad for not checking it thoroughly. – Peltio Nov 29 '13 at 18:41
-
it seems there is no good answer :)
n=1seems useless but on the other hand, why not? – Kuba Nov 29 '13 at 19:02
Range[s, f, (f - s)/(n - 1)]so many times that my fingers run across the keyboard on their own – Dr. belisarius Nov 29 '13 at 20:32Subdivide[-1, 1, 10 - 1]. – J. M.'s missing motivation Aug 17 '17 at 14:35