2
\$\begingroup\$

Are there any improvements I can make to my code for forward Euler's method on Matlab?

k = 0.05;
CA0 = 3;
t0 = 0;
tF = 100;
ts = 0.1;
t = t0:ts:tF;
N = length(t);
CA = zeros(1, N);
CB = zeros(1, N);
CA(1) = CA0;
CB(1) = 0;
for i = 2:N
    r = k * CA(i-1);
    CA(i) = CA(i-1) - r * ts;
    CB(i) = CB(i-1) + r * ts;
end
plot(t, CA, 'b', t, CB, 'r');
xlabel('time(s)');
ylabel('concentration (mol/L)');
legend('C_A (Euler)', 'C_B (EUler)');
title('Forward Euler for a batch reactor');
grid on;
\$\endgroup\$
3
  • 2
    \$\begingroup\$ What is your differential equation? Does the code produce the right answer? Code review is easier if we know what the code is supposed to do. This might be correctly implemented or not, depending on what equation you’re solving. \$\endgroup\$ Commented Nov 21 at 6:11
  • \$\begingroup\$ This seems to be calculation for a first order reaction $A \rightarrow B$. I think the code is fine, if anything I'd recommend either change the line CB(1) = 0 to CB(1) = CB0 in case you need to change the initial concentration for B, or remove the line if you don't need to. \$\endgroup\$ Commented Nov 21 at 6:52
  • 1
    \$\begingroup\$ @ioveri: Since you are new to Code Review, you should post your comment as an answer (instead of a comment). You are reviewing the code, after all :) \$\endgroup\$ Commented Nov 21 at 14:00

1 Answer 1

2
\$\begingroup\$

Documentation

You should add header comments to describe the purpose of the code:

  • Mention the forward Euler method and provide a URL
  • Describe the equation or algorithm
  • Describe what you mean by "batch reactor"

Naming

The variable names are vague. You should use longer names than k, t0 , etc. You can also add comments for each variable.

Typo

EUler should be Euler in:

legend('C_A (Euler)', 'C_B (EUler)');
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.