Unexpected result linspace function
13 views (last 30 days)
Show older comments
Nguyen Trung Kien
on 30 Nov 2018
Commented: Nguyen Trung Kien
on 30 Nov 2018
Today I am working with
linspace
function. I used it as
x = linspace(x1,x2,(x2-x1)/deltax+1)
When I passed the value of x1, x2, deltax as:
x1=0.2;
x2=0.5;
deltax=0.1;
I got the result
x = 0.2 0.35 0.5
I try again with
x = linspace(0.2, 0.5, 4)
the result was as expected:
x = 0.2 0.3 0.4 0.5
I do not know it is a bug or other side effect of linspace function. Please help me to understand this. Because if I try:
x1=0.2;
x2=0.6;
deltax=0.1;
The result was good
x = 0.2 0.3 0.4 0.5 0.6
Thank you in advance for your consideration. The following image is the console command I tried:

0 Comments
Accepted Answer
Mark Sherstan
on 30 Nov 2018
It is due to round off error. Linspace documentation states the following regarding the fuction: If n is not an integer, linspace rounds down and returns floor(n) points. The number is really close to 4 but not 4 so linspace is rounding the number down to 3 or "flooring" it. The other case is exactly 5 and you dont have that issue. Try the following in MATLAB and you will see:
x1=0.2;
x2=0.5;
deltax=0.1;
x = (x2-x1)/deltax+1
x == 4
>> False
x1=0.2;
x2=0.6;
deltax=0.1;
x = (x2-x1)/deltax+1
x == 5
>> True
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!