The One-Line C# Linq Implementation of LineSpace Algorithm


In Matlab, there is a function linspace that generates n evenly-spaced points between two given points. For example,

x1 = 1
x2 = 9
n = 3
y = linspace(x1, x2, n)

and y becomes 3 points which are [1 5 9]. The first and last point should not change. And this can be extended to 2D, 3D and even higher dimensions. You can use C# LINQ to implement the 3D LineSpace algorithm given 3 parameters: two end points and the number of partitions (e.g. 2 partitions makes 3 points).

1
2
3
4
5
private IEnumerable<Vector3D> LineSpace(Vector3D start, Vector3D end, int partitions) =>
        Enumerable.Range(0, partitions + 1)
        .Select(idx => idx != partitions
                ? start + (end - start) / partitions * idx
                : end);
private IEnumerable<Vector3D> LineSpace(Vector3D start, Vector3D end, int partitions) =>
        Enumerable.Range(0, partitions + 1)
        .Select(idx => idx != partitions
                ? start + (end - start) / partitions * idx
                : end);

The class Vector3D can be referenced by adding the assembly PresentationCore:

1
using System.Windows.Media.Media3D;
using System.Windows.Media.Media3D;

The above code stores the LINQ so make sure you don’t run into multiple enumeration problem that degrades the code performance.

numpy-linspace-1 The One-Line C# Linq Implementation of LineSpace Algorithm c # LINQ math

numpy linspace example

The partitions should be strictly larger than 1 otherwise you could add throwing an exception. Please note that it is better to stick to double-type which provides higher floating point accuracy otherwise the inaccuracy may accumulate along the calculations (in that case, the length of each segments may not be exactly equal to the distance between two end points divided by the number of partitions).

You, of course, can unit test the implementation, and we will cover that in the next post.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
421 words
Last Post: PPAP in C++ and Javascript for Beginner
Next Post: How to Display Text in Browser using the Echo API ?

The Permanent URL is: The One-Line C# Linq Implementation of LineSpace Algorithm

Leave a Reply