gpt4 book ai didi

python - 如何简化 Python 和 Matlab 中的 for 循环

转载 作者:行者123 更新时间:2023-12-01 06:04:24 24 4
gpt4 key购买 nike

我是 C 和 MATLAB 用户。当我开始学习 Python 时(一周前),我注意到我没有充分利用 MATLAB 的潜力,特别是数组运算。我经常使用 for 循环,可能是因为我学过 C 语言编程。

在之前的技巧中,我学习了使用 cumsum 和其他高效的数组运算,例如:

alpha = [1e-4,1e-3,1e-4,1e-1,1e-2,1e-3,1e-6,1e-3];
zeta = alpha / (dz*dz)
nz = 101
l=[0.3,0.1,0.2,0.1,0.1,0.1,0.2];
wz = cumsum(l*(nz-1));
nl = lenght(l);

是否可以在 Python (Numpy) 或 MATLAB 中简化以下代码?

      A = zeros(nz,nz);
i=1;
for j = 2:wz(i)-1
A(j,j-1) = zeta(1,1);
A(j,j) = -2*zeta(1,1);
A(j,j+1) = zeta(1,1); % layer 1 nodes
end

%cicle to n-layers
for i=2:nl
for j=wz(i-1):wz(i-1)
A(j,j-1) = zeta(1,i-1);
A(j,j) = -zeta(1,i-1)-zeta(1,i);
A(j,j+1) = zeta(1,i);
end

for j=wz(i-1)+1:wz(i)
A(j,j-1) = zeta(1,i);
A(j,j) = -2*zeta(1,i);
A(j,j+1) = zeta(1,i);
end

end
end

最佳答案

在有机会在我的机器上与你的机器上并行运行下面的代码后,我修改了它。仍然有几个问题(A 是否应该在最后的循环中变得更大?,dz 是什么?)。在运行之前遇到的问题是我忘记了 idx_matrix 必须是逻辑的。

dz=0.1;
alpha = [1e-4,1e-3,1e-4,1e-1,1e-2,1e-3,1e-6,1e-3];
zeta = alpha / (dz*dz);
nz = 101;
l=[0.3,0.1,0.2,0.1,0.1,0.1,0.2];
wz = cumsum(l*(nz-1));
nl = length(l);

A = zeros(nz);
i=1;

%replaces 1st loop
j_start = 2;
j_end = wz(i)-1;

idx_matrix = false(size(A));
idx_matrix(j_start:j_end,j_start:j_end) = eye(j_end-j_start+1);
A(idx_matrix) = -2*zeta(1,1);

idx_matrix(idx_matrix) = false;
idx_matrix(j_start:j_end,j_start-1:j_end-1) = eye(j_end-j_start+1);
A(idx_matrix) = zeta(1,1);

idx_matrix(idx_matrix) = false;
idx_matrix(j_start:j_end,j_start+1:j_end+1) = eye(j_end-j_start+1);
A(idx_matrix) = zeta(1,1);

%cicle to n-layers
for i=2:nl

%replaces 3rd loop
j_start = wz(i-1);
A(j_start,j_start) = -zeta(1,i-1)-zeta(1,i);
A(j_start,j_start-1) = zeta(1,i-1);
A(j_start,j_start+1) = zeta(1,i);

%replaces 4th loop
j_start = wz(i-1)+1;
j_end = min(wz(i),size(A,2)-1);
idx_matrix = false(size(A));
idx_matrix(j_start:j_end,j_start:j_end) = eye(j_end-j_start+1);
A(idx_matrix) = -2*zeta(1,i);

idx_matrix(idx_matrix) = false;
idx_matrix(j_start:j_end,j_start-1:j_end-1) = eye(j_end-j_start+1);
A(idx_matrix) = zeta(1,i);

idx_matrix(idx_matrix) = false;
idx_matrix(j_start:j_end,j_start+1:j_end+1) = eye(j_end-j_start+1);
A(idx_matrix) = zeta(1,i);

end

关于python - 如何简化 Python 和 Matlab 中的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8878413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com