转换为 Python 时,冒号在 Matlab 中意味着什么?

What does colons mean in Matlab when converting to Python?

我正在尝试将 Matlab 代码转换为 Python,而且几乎所有内容都非常容易更改。但是当一个地方出现很多冒号时,我陷入了这一部分。这是原始的 Matlab 代码:

for iii=1:nP-1  
    nnn=100;
    xxx=[X(iii):(X(iii+1)-X(iii))/nnn:X(iii+1)];
    fff=0;
    for j=1:2
        [U,V]=Hermite(X(iii:iii+1),j,xxx);
        fff=fff+U*Y(iii+j-1)+V*DY(iii+j-1);
    end
    figure(1), hold on, grid on, axis equal
    plot(xxx,fff,'r-','LineWidth',2.5);
    plot(X(iii:iii+1),Y(iii:iii+1),'ko','LineWidth',2,'MarkerSize',8)
end 

我在 Python 中归结为:

for iii in range(0,nP - 2):
    nnn = 100

    xxx = [X[iii]:(X[iii + 1] - X[iii]) / nnn:X[iii + 1]]
    fff = 0
    for j in range(0,1):
        [U, V] = Hermite(X[iii:iii + 1], j, xxx)
        fff = fff + U * Y(iii + j - 1) + V * DY[iii + j - 1]

    plt.figure(1)
    plt.grid("on")
    plt.axis("equal")
    plt.plot(xxx, fff, color='red',marker='o',linestyle='')
    plt.plot(X[iii:iii + 1], Y[iii:iii + 1], color='blue',marker='o',linestyle='')
    plt.show()

我卡住的部分在这里:

xxx = [X[iii]:(X[iii + 1] - X[iii]) / nnn:X[iii + 1]]

我相信对于精通两种语言的人来说应该很容易。 提前谢谢你。

语法 a : b : c 使用 b 的步骤创建从 a 到 c(如果可能,包括在内)的序列。在这种情况下,将其进一步包裹在方括号中没有任何效果,因为序列已经是矩阵(即 a:b:c 确实等同于 [a:b:c] )。因此

[ X(iii)  :  (X(iii+1) - X(iii)) / nnn  :  X(iii+1) ];

是一个序列:

  • 来自 X[iii](无论计算结果是什么),
  • X[iii + 1]
  • 使用 (X[iii + 1] - X[iii]) / nnn
  • 的步骤

如果处理整数,python 中的等效项是 range( start, end, steps),对于浮点数,等效项是 numpy.arange,但有一个警告。 Matlab 将端点视为 'inclusive',而 python 将其视为 'exclusive'。这意味着你必须稍微调整你的端点以获得相同的范围(通常你可以通过将值 'endpoint+step' 传递给 range 来做到这一点,使它成为你的新 'excluded' 端点python)

为了向您展示我的意思,请考虑以下示例:

在octave(/matlab)控制台中:

octave:1> a = 1; b = 2; c = 11;
octave:2> a:b:c
    1    3    5    7    9   11

在python3解释器中:

>>> a = 1; b = 2; c = 11;
>>> list( range( a, c+b, b ) )
[1, 3, 5, 7, 9, 11]