Is there a java version of matlab's colon operator or linspace? For instance, I'd like to make a for loop for evenly spaced numbers, but I don't want to bother with creating an array of those numbers manually.
For example to get all integers from 1 to 30, in matlab I would type:
1:30
or
linspace(1,30)
Analogue to linspace, but inputs are: start value, spacing, and # points.
It is similar to the colon operator :, but gives direct control over the number of points. it is the same, the main difference and advantage of linspace is that it generates a vector of integers with the desired length (or default 100) and scales it afterwards to the desired range.
linspace is an in-built function in Python's NumPy library. It is used to create an evenly spaced sequence in a specified interval.
y = linspace( x1,x2 , n ) generates n points. The spacing between the points is (x2-x1)/(n-1) . linspace is similar to the colon operator, “ : ”, but gives direct control over the number of points and always includes the endpoints.
For the two variable call, @x4u is correct. The three variable call will be quite a bit harder to emulate.
For instance, i think that linspace(1,30,60) should produce values 1, 1.5, 2, 2.5, 3, 3.5..., or maybe that's the values for linspace(1,30,59)--either way, same problem.
With this format you'll have to do the calculations yourself--Personally I'd create a new object to do the whole thing for me and forget the for loop.
counter=new Linspace(1,30,60);
while(counter.hasNext()) {
process(counter.getNextFloat())
}
or simply
while(float f : new Linspace(1,30,60)) {
process(f);
}
if you have your Linspace object implement Iterable.
Then the inside of the counter object should be pretty obvious to implement and it will easily communicate to you what it is doing without obfuscating your code with a bunch of numeric calculations to figure out ratios.
An implementation might be something like this: (NOTE: Untested and I'm pretty sure this would be vulnerable to edge cases and floating point errors! It also probably won't handle end < start for backwards counting, it's just a suggestion to get you going.)
public class Linspace {
private float current;
private final float end;
private final float step;
public Linspace(float start, float end, float totalCount) {
this.current=start;
this.end=end;
this.step=(end - start) / totalCount;
}
public boolean hasNext() {
return current < (end + step/2); //MAY stop floating point error
}
public float getNextFloat() {
current+=step;
return current;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With