6 views (last 30 days)

I have this section of code which is working fine but i don't like the way i have implemented those 3 separate for loops. Can anyone suggest to me that how can i merge them together to make it even more efficient and compact ? Thank you

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

Opportunities for recent engineering grads.

Apply Today
## 5 Comments

## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/270002-combining-3-for-loops-into-1-in-matlab#comment_345486

⋮## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/270002-combining-3-for-loops-into-1-in-matlab#comment_345486

## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/270002-combining-3-for-loops-into-1-in-matlab#comment_345492

⋮## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/270002-combining-3-for-loops-into-1-in-matlab#comment_345492

## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/270002-combining-3-for-loops-into-1-in-matlab#comment_345506

⋮## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/270002-combining-3-for-loops-into-1-in-matlab#comment_345506

## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/270002-combining-3-for-loops-into-1-in-matlab#comment_345707

⋮## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/270002-combining-3-for-loops-into-1-in-matlab#comment_345707

## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/270002-combining-3-for-loops-into-1-in-matlab#comment_345725

⋮## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/270002-combining-3-for-loops-into-1-in-matlab#comment_345725

Sign in to comment.