我正在考虑从Matlab切换到Python(NumPy)。因此,作为一项学习任务,我尝试在Python上重写一个简单的随机模型。 python脚本返回正确的答案,但工作太慢! Python需要3分钟而不是Matlab需要3秒钟。我做错了什么?
Matlab的:
clear all; clc;
tic
T = 0.05;
Tmax = 3600;
t = T:T:Tmax;
N = length(t);
G = [0 0;
0 T];
F = [1 T;
0 1];
Dksi = 13*1;
Deta = 10*1;
Band = 0.1:0.1:3;
RMS_Omega = nan(1, length(Band));
for i = 1:length(Band)
K = nan(2, 1);
K(1) = 8/3 * Band(i) * T;
K(2) = 32/9 * Band(i)^2 * T;
ksi = sqrt(Dksi) * randn(1, N);
eta = sqrt(Deta) * randn(1, N);
Xest = [0; 0];
Xextr = F*Xest;
Xist = [0; 0];
ErrOmega = nan(1, N); Omega = nan(1, N);
for k = 1:N
Xist = F*Xist + G*[0; ksi(k)];
omega_meas = Xist(1) + eta(k);
Xest = Xextr + K*(omega_meas - Xextr(1));
Xextr = F*Xest;
ErrOmega(k) = Xest(1) - Xist(1);
Omega(k) = Xist(1);
end
RMS_Omega(i) = sqrt(mean(ErrOmega.^2));
end
figure(1)
hold on
plot(Band, RMS_Omega);
hold off
xlabel('Bandwidth, Hz'); ylabel('RMS \omega, Hz');
toc
的Python:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import math
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import time as time
tbeg = time.time()
T = 0.005
Tmax = 3600.0
t = np.linspace(T, Tmax, int(Tmax/T))
N = len(t)
G = np.array([[0, 0],
[0, T]])
F = np.array([[1, T],
[0, 1]])
Dksi = 13.0
Deta = 10.0
Band = np.linspace(0.1, 3.0, 30)
Band_for_plot = 2
RMS_Omega = np.array([None for i in range(0, len(Band))])
for i, BW in enumerate(Band):
K = np.array([[8/3 * BW * T],
[32/9 * BW*BW *T]])
ksi = math.sqrt(Dksi) * np.random.randn(N)
eta = math.sqrt(Deta) * np.random.randn(N)
Xest = np.array([[0],
[0]])
Xextr = F.dot(Xest)
Xist = np.array([[0],
[0]])
ErrOmega = np.array([None for j in range(0, N)])
Omega = np.array([None for j in range(0, N)])
for k in range(0, N):
Xist = F.dot(Xist) + G.dot(np.array([[0],
[ksi[k]]]))
omega_meas = Xist[0] + eta[k]
Xest = Xextr + K * (omega_meas - Xextr[0])
Xextr = F.dot(Xest)
ErrOmega[k] = Xest[0] - Xist[0]
Omega[k] = Xist[0]
RMS_Omega[i] = math.sqrt(np.mean(ErrOmega**2))
elapsed = time.time() - tbeg
print(elapsed, u'sec')
答案 0 :(得分:0)
在处理过类似的问题后,我学会了避免进行代码翻译。尽管它可以节省写作时间,但它不会在运行中(减少写入的使用/时间)。
Python中的{{1}}循环通常比Matlab慢,但提供了大量的工具和库,可以帮助构建一个好的代码,所以要使用它们。问题中的评论已经是一个很好的帮助!