Using symbolic subs in for loop
4 ビュー (過去 30 日間)
古いコメントを表示
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.
0 件のコメント
回答 (1 件)
Adarsh
2025 年 1 月 31 日
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.
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!