2 views (last 30 days)

I want to rewrite this code but without if and else statements. I just want to enhance convergence rate

for i=1:N-1

for j=1:M-1

A(i+(M-1-j)*(N-1),i+(M-1-j)*(N-1))=-2/dx^2-2/dy^2;

B(i+(M-1-j)*(N-1))=B(i+(M-1-j)*(N-1))-(cos(x(i)+y(j))+cos(x(i)-y(j)));

if i==1

B(i+(M-1-j)*(N-1))=B(i+(M-1-j)*(N-1))-cos(y(j))/dx^2;

else

A(i+(M-1-j)*(N-1),i-1+(M-1-j)*(N-1))=1/dx^2;

end

end

end

Vimal Rathod
on 5 May 2020

Hi,

If your main goal is to remove the if else statements from the code, you can write the following code first and then write the main for loop with i starting from 2 instead on one and remove the if statement and keep the statement in the else condition.

i = 1;

for j=1:M-1

A(i+(M-1-j)*(N-1),i+(M-1-j)*(N-1))=-2/dx^2-2/dy^2;

B(i+(M-1-j)*(N-1))=B(i+(M-1-j)*(N-1))-cos(y(j))/dx^2;

end

for i=2:N-1

for j=1:M-1

A(i+(M-1-j)*(N-1),i+(M-1-j)*(N-1))=-2/dx^2-2/dy^2;

B(i+(M-1-j)*(N-1))=B(i+(M-1-j)*(N-1))-(cos(x(i)+y(j))+cos(x(i)-y(j)));

A(i+(M-1-j)*(N-1),i-1+(M-1-j)*(N-1))=1/dx^2;

end

end

if you want to further optimize you can vectorize the first loop.

Hope this helps!

Rik
on 7 May 2020

I wouldn't personally care how my code would solve the equations. The more time you put in, the more you can optimize your code. At some point you get to a stage where you need to put in an unreasonable amount of time. Then I would stop.

Are you really sure you simply want to avoid an if/else block? That doesn't make sense to me.

What toolboxes relating to diff equations do you have available?

Opportunities for recent engineering grads.

Apply Today
## 3 Comments

## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/522300-how-do-i-avoid-using-if-and-else-statements-in-this-code#comment_839296

⋮## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/522300-how-do-i-avoid-using-if-and-else-statements-in-this-code#comment_839296

## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/522300-how-do-i-avoid-using-if-and-else-statements-in-this-code#comment_839301

⋮## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/522300-how-do-i-avoid-using-if-and-else-statements-in-this-code#comment_839301

## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/522300-how-do-i-avoid-using-if-and-else-statements-in-this-code#comment_839320

⋮## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/522300-how-do-i-avoid-using-if-and-else-statements-in-this-code#comment_839320

Sign in to comment.