我有这段代码工作正常,但我不喜欢我实现这3个单独for循环的方式。任何人都可以向我建议我如何将它们合并在一起,使其更加高效和紧凑?谢谢
clear variables;
close all;
clc;
ilambda=5;
mu=2;
n=2;
jmax=n+1;
P= sym('P',[jmax,jmax]);
for j1 = 1:jmax
for j2 = 2:jmax-1
[c1,c2,c3,c4,c5]=coefficients(ilambda,mu,j1,j2);
if j1<jmax
E(j1, j2) = c1*P(j1, j2) - c2 * P(j1+1, j2) - c3 * P(j1, j2+1) - c4 * P(j1, j2-1);
else
E(j1, j2) = c1 * P(j1, j2) - c3 * P(j1, j2+1) - c4 * P(j1, j2-1);
end
end
end
j2=1;
for j1=1:jmax;
[c1,c2,c3,c4,c5]=coefficients(ilambda,mu,j1,j2);
if (j1<jmax)
E(j1, j2) = c1*P(j1, j2) - c2 * P(j1+1, j2) - c3 * P(j1, j2+1);
else
E(j1, j2) = c1*P(j1, j2) - c3 * P(j1, j2+1);
end
end
j2=jmax;
for j1=1:jmax;
[c1,c2,c3,c4,c5]=coefficients(ilambda,mu,j1,j2);
if (j1==1)
E(j1, j2) = c1*P(j1, j2) - c2 * P(j1+1, j2) - c4 * P(j1, j2-1);
elseif (j1==jmax)
c1=((j1-1)*mu)+((j2-1)*mu);
E(j1, j2) = c1 * P(j1, j2) - c4 * P(j1, j2-1) - c5 * P(j1-1, j2);
else
E(j1, j2) = c1*P(j1, j2) - c2 * P(j1+1, j2)- c4 * P(j1, j2-1)- c5 * P(j1-1, j2);
end
end
答案 0 :(得分:0)
由于j1
始终从1
转到jmax
,因此不应该那么难。
你现在基本上做的是处理矩阵的内部部分,然后是第一列,然后是最后一列,包括所有行(即按列构建矩阵)。
您可以按行(使用索引j1
)构建矩阵,然后根据j2
单独构建列,如下所示:
for j1 = 1:jmax
% set j2 at 1 and work on the first column
j2=1;
[c1,c2,c3,c4,c5]=coefficients(ilambda,mu,j1,j2);
if (j1<jmax)
E(j1, j2) = c1*P(j1, j2) - c2 * P(j1+1, j2) - c3 * P(j1, j2+1);
else
E(j1, j2) = c1*P(j1, j2) - c3 * P(j1, j2+1);
end
% set j2 as variable in for loop
for j2 = 2:jmax-1
[c1,c2,c3,c4,c5]=coefficients(ilambda,mu,j1,j2);
if j1<jmax
E(j1, j2) = c1*P(j1, j2) - c2 * P(j1+1, j2) - c3 * P(j1, j2+1) - c4 * P(j1, j2-1);
else
E(j1, j2) = c1 * P(j1, j2) - c3 * P(j1, j2+1) - c4 * P(j1, j2-1);
end
end
% finally set j2 as jmax and work on the last column
j2=jmax;
if (j1==1)
E(j1, j2) = c1*P(j1, j2) - c2 * P(j1+1, j2) - c4 * P(j1, j2-1);
elseif (j1==jmax)
c1=((j1-1)*mu)+((j2-1)*mu);
E(j1, j2) = c1 * P(j1, j2) - c4 * P(j1, j2-1) - c5 * P(j1-1, j2);
else
E(j1, j2) = c1*P(j1, j2) - c2 * P(j1+1, j2)- c4 * P(j1, j2-1)- c5 * P(j1-1, j2);
end
% basically now you have completed the j1-th row
% the following loop will work in the very same way, that is:
% working on the j1-st row and then working separately on the 1st
% column, then on the inner columns and then on the last column.
end
另一种(在我看来非常优雅)方法是使用switch/case
。在这种情况下,伪代码将类似于
for j1=1:jmax
for j2=1:jmax
switch j2
case 1
% enter here what to do if j2==1
case jmax
% enter here what to do if j2==jmax
otherwise
% enter here what to do if j2 is between 2 and jmax-1
end
end
end
注意:我尝试使用系数c1 ... c5的任意值,我希望这些(这些)解决方案与您的coefficients()
函数一起工作。