如何手动计算MATLAB linspace函数

mTu*_*ran 2 matlab

Matlab中有一个名为linspace的函数,它会在给定范围内分割间隔。例如:

>> x = linspace(-10,5, 10)

x =

  -10.0000   -8.3333   -6.6667   -5.0000   -3.3333   -1.6667         0    1.6667    3.3333    5.0000
Run Code Online (Sandbox Code Playgroud)

如何通过手工计算找到x(4)?

Div*_*kar 5

这似乎有效-

x = linspace(-10,5, 10)

start = -10;
stop = 5;
num_elements = 10;
index = 4;

out = start + (index-1)*(stop - start)./(num_elements-1)
Run Code Online (Sandbox Code Playgroud)

输出-

x =
  -10.0000   -8.3333   -6.6667   -5.0000   -3.3333   -1.6667    0    1.6667 ...
out =
    -5
Run Code Online (Sandbox Code Playgroud)

因此,(stop - start)./(num_elements-1)将是stepsize

因此,如果您需要完整的阵列,请执行以下操作-

complete_array = start : (stop - start)./(num_elements-1) :stop 
Run Code Online (Sandbox Code Playgroud)

但是,如果将这些结果与linspace- 进行比较,请注意浮点精度问题What is the advantage of linspace over the colon “:” operator?