首页 > 解决方案 > 在初学者级别理解 Python for 循环

问题描述

我意识到以前有人问过这些问题,但我似乎无法为自己找到答案。

我对 Matlab 相当流利,但我无法理解这些 Python for 循环。我在 Matlab 中编写了这个小脚本,我想在 Python 中做同样的事情。

MATLAB

h = 2;
w = pi / 2;
t = 0:.01:4;
smP = [1 2]';
r = [h * cos(w * t') 2 * h * sin(w * t')]';
A = zeros(2,2,length(t));
rP = zeros(2,length(t));
for i = 1:length(t)
    A(:,:,i) = [cos(w * t(i)) -sin(w * t(i)); sin(w * t(i)) cos(w * t(i))];
    rP(:,i) = r(:,i) + A(:,:,i) * smP;
end
plot(rP(1,:),rP(2,:))

我无法让rP(:,i)-style 索引在 Python 中工作。我已经尝试了几件事。

尝试 1

r = np.matrix([h * np.cos(w * t), 2 * h * np.sin(w * t)])
A = np.array([[np.cos(w * t), -np.sin(w * t)], [np.sin(w * t), np.cos(w * t)]])

rP = []
for i in range(len(t)):
    instant = r[:,i] + A[:,:,i] @ smP
    rP.append(instant)

尝试 2

rP = np.zeros([2,len(t)])
for i in range(len(t)):
    rP[:][i] = r[:,i] + A[:,:,i] @ smP

这给了我一个 400 列表(我当前的大小为 t),在每个索引处包含一个 2x1 向量。这我似乎无法绘制,这只是保存数据的不好方法。我显然想要一个 2xlength(t) 矩阵,其中每一列都是离散时间步长的向量 rP(就像 Matlab 代码一样)。

我怎样才能在 Python 中完成这个简单的事情?

标签: pythonmatlabfor-loopvectorindexing

解决方案


检查以下解决方案:

import numpy as np
from matplotlib import pyplot as plt
from numpy import sin, cos, hstack, vstack

h = 2
w = np.pi / 2
t = np.arange(0, 4+0.01, 0.01) # t = 0:.01:4;
smP = np.array((1, 2)) # smP = [1 2]';
r = vstack((h * cos(w * t), 2 * h * sin(w * t))) #r = [h * cos(w * t') 2 * h * sin(w * t')]';
A = np.zeros((2, 2, len(t))) #A = zeros(2,2,length(t));
rP = np.zeros((2, len(t))) #rP = zeros(2,length(t));

for i in range(len(t)):  #for i = 1:length(t)
    A[:,:,i] = vstack((hstack((cos(w * t[i]), -sin(w * t[i]))), hstack((sin(w * t[i]), cos(w * t[i]))))) #    A(:,:,i) = [cos(w * t(i)) -sin(w * t(i)); sin(w * t(i)) cos(w * t(i))];
    rP[:,i] = r[:,i] + A[:,:,i].dot(smP.T)  #    rP(:,i) = r(:,i) + A(:,:,i) * smP;

plt.plot(rP[0,:], rP[1,:])  #plot(rP(1,:),rP(2,:))
plt.show(block=True)

请注意,我的 Python 水平不是那么好......


推荐阅读