這是我運行良好的 MATLAB 代碼。
% all of the given time are in milisecond
n = 3; % No of image
T = 100; % for the time period user wants to see the mirage
ts = .2*(100/(2*n-3)); % standing time
tv = .6*((100-((2*n-3)*ts))/(2*(n-1))); % travelling time
m1 = 0:.1:tv;
x1 = .5*(1-cos(pi*(m1/tv))); %position equation
xa = x1;
%travelling toward from left to right
for i= 1:n-1
x1 = x1 i-1;
%standing at one point
for f = 1:ts
x2(f) = x1(end);
end
if i==1
x3=[x1,x2];
else
x3 = [x3,x1,x2];
end
end
我正在嘗試將其轉換為 Python 代碼。它顯示 SyntaxError: cannot assign to function call
這是我想出的 Python 代碼
import numpy as np
import math
n = 3;
T = 100;
ts = .2*(100/(2*n-3));
tv = .6*((100-((2*n-3)*ts))/(2*(n-1)));
m1 = np.arange(0,tv,0.1);
x1 = 0.5*(1-(np.cos(np.pi*(m1/tv))));
xa = x1;
##################################
#travelling toward from left to right
for i in range(1,n-1):
x1 = x1 i-1;
for f in np.arange(1,ts, ):
x2(f) = x1(end); # The error line
if i==1:
x3 = np.array([x1,x2]);
else:
x3 = np.array([x3,x1,x2]);
我怎樣才能解決這個問題?我可以在 x2(f) = x1(end) 中進行哪些更改,因為無論我做什么,每次都會顯示不同的錯誤。
uj5u.com熱心網友回復:
首先,我建議停止使用分號。python存在的主要原因之一是使代碼更具可讀性。
然后,我建議不要使用空白引數,如果您不故意這樣做,它沒有實際用途:
for f in np.arange(1,ts):
關于你的程式,你正在做類似函式(一些特定引數)分配函式('end'變數下的引數),如果你想使用陣列操作你應該使用方括號,花括號是為函式保留的:
x2[f] = x1[end]
uj5u.com熱心網友回復:
python中的索引和切片使用[]而不是()
for i in range(1, n-1):
x1 = x1 i - 1;
x2 = []
for f in np.arange(1, ts):
x2.append(x1[-1])
if i == 1:
x3 = np.array([x1, x2])
else:
x3 = np.array([x3, x1, x2])
uj5u.com熱心網友回復:
關于
TypeError: list indices must be integers or slices, not numpy.float64
看看 Octave 中發生了什么:
最初x2是未定義的,但在我們開始f回圈時創建:
>> x2
error: 'x2' undefined near line 1 column 1
>> f=1
f = 1
>> x2(f) = x1(end)
x2 = 1
如果我嘗試用最后一個值索引它ts,我會得到同樣的錯誤:
>> f=ts
f = 6.6667
>> x2(f)
error: x2(6.66667): subscripts must be either integers 1 to (2^63)-1 or logicals
您不會在實際回圈中得到錯誤,因為1:ts迭代實際上會在該范圍內創建整數:
>> 1:ts
ans =
1 2 3 4 5 6
在numpy:
In [1]: ts = 6.6667
In [3]: np.arange(0,ts)
Out[3]: array([0., 1., 2., 3., 4., 5., 6.])
雖然arange步長為 1s,但實際值是浮動的,因此存在索引錯誤。
并且一個變數,陣列,不能通過這個賦值創建:
In [6]: x2[0]=1
Traceback (most recent call last):
Input In [6] in <cell line: 1>
x2[0]=1
NameError: name 'x2' is not defined
在 Python 中創建此類陣列/串列的正確方法:
In [14]: x2 = np.zeros(6)
...: for i in range(6):
...: x2[i] = i**2
...:
In [15]: x2
Out[15]: array([ 0., 1., 4., 9., 16., 25.])
In [16]: alist = []
...: for i in range(6):
...: alist.append(i**2)
...:
...:
In [17]: alist
Out[17]: [0, 1, 4, 9, 16, 25]
但是您的f回圈只是在所有插槽中放置相同的值
for f = 1:ts
x2(f) = x1(end);
end
為此,我們真的應該使用整個陣列方法:
In [21]: x2 = np.full(6,fill_value=2.3)
In [22]: x2
Out[22]: array([2.3, 2.3, 2.3, 2.3, 2.3, 2.3])
或者:
In [25]: x2=np.zeros(6)
...: x2[:] = 2.3
在 MATLAB 中,您可以進行大量迭代,因為它會進行jit編譯。但是numpy就像原始的 MATLAB,編譯的整個陣列方法要快得多。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/464909.html
