Unexpected result linspace function

13 visualizaciones (últimos 30 días)
Nguyen Trung Kien
Nguyen Trung Kien el 30 de Nov. de 2018
Comentada: Nguyen Trung Kien el 30 de Nov. de 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:
Capture.PNG

Respuesta aceptada

Mark Sherstan
Mark Sherstan el 30 de Nov. de 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
  1 comentario
Nguyen Trung Kien
Nguyen Trung Kien el 30 de Nov. de 2018
Thank you so much for your explaination. This helped me to understand and not confuse more.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos


Versión

R2017b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by