I recognize that you are evaluating a symbolic expression with substituting multiple values for symbols in a for loop.
To increase efficiency in applying these operations, the “matlabFunction” can be used which converts symbolic expressions to a MATLAB function handle then this function handle can be used to apply vectorized operations and compute the required outputs or alternatively you can even use for-loop for evaluation based on individual preference.
This increases the efficiency and speed of the operations applied compared to the operations applied on the symbolic expressions.
Also, it’s a good practice to use simplify a function before converting it into MATLAB function handle to make it more efficient.
Here is a working code example showing the improvement in speed and efficiency using the “matlabFunction” function for the required task:
Original Example:
syms tf zeta taum tgo
eq = (exp(-tgo/taum) + tgo/taum - 1)^2;
INT = int(eq, tgo);
TauM = 5;
dt = 0.01;
Tgo = 10;
% Measure time for the original code
tic;
while Tgo > 0
INT_val = double(subs(INT, {tgo, taum}, {Tgo, TauM}));
Tgo = Tgo - dt;
end
originalTime = toc;
fprintf('Original code execution time: %.4f seconds\n', originalTime);
Optimized Example:
syms tf zeta taum tgo
eq = (exp(-tgo/taum) + tgo/taum - 1)^2;
INT = int(eq, tgo);
TauM = 5;
dt = 0.01;
Tgo_values = 10:-dt:0;
tic;
% Pre-substitute taum to simplify the expression
INT_simplified = simplify(subs(INT, taum, TauM));
% Convert to a function handle for fast evaluation
INT_func = matlabFunction(INT_simplified, 'Vars', tgo);
% Initialize an array to store results
INT_vals = zeros(size(Tgo_values));
for i = 1:length(Tgo_values)
INT_vals(i) = INT_func(Tgo_values(i));
end
optimizedTime = toc;
fprintf('optimized code execution time using for loop: %.4f seconds\n', optimizedTime);
For more information the documentation for the “matlabFunction” can be referred by using the link below:
I hope this helps in improving the code efficiency.