Using symbolic subs in for loop

3 次查看(过去 30 天)
ben
ben 2018-2-10
回答: Adarsh 2025-1-31
Hi,
I have the following equation:
syms tf zeta taum tgo
eq = (exp(-tgo/taum)+tgo/taum-1)^2;
INT = int(eq,tgo);
TauM = 5;
dt = 0.01;
Tgo = 10;
for Tgo > 0
INT = double(subs(INT,{tgo,taum},{Tgo,TauM}));
Tgo = Tgo - dt
end
My question is: using subs inside the for loop slows it down. Is there anyway to make it faster? (The problem is Tgo is dynamic).
P.s. In this example I could write the integral not a syms however in many problems I would like to insert the function and run the code and not to do all the work before.
Thank you.

回答(1 个)

Adarsh
Adarsh 2025-1-31
Hi @ben,
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);
Original code execution time: 2.2715 seconds
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);
optimized code execution time using for loop: 0.2773 seconds
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.

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by