Symbolic Substitution and conversion to double is too time consuming

12 次查看(过去 30 天)
Hi,
I am doing a symbolic substitution and then converting the resultant into double.
for i=1:size(X_scaled,1) % for each row in X_scaled
Psi_new=Psi;
for j=1:size(Psi_new,1) % for each row in Psi
Psi_new{j}=subs(Psi_new{j},x,X_scaled(i,:)); % for each variable
Num_Psi(i,j)=double(Psi_new{j});
end
end
X_scaled: 5000 by 7 matrix with numerical values; each column cell contains a value of one out of 7 variables.
Psi: 36 by 1 cell matrix; each cell having a symbolic expression of 7 symbols (an expression made of 7 variables).
x: 1 by 7 cell array containing the names of the 7 symbols (variables)
So, the final output in Num_Psi would be 5000 *36 values.
I need to substitute the 7 values from X_scaled into each cell of Psi. However, apparently the substitution process is quite slow. This code take hours.
Is there any way to speed up the substition process?
Many thanks for looking into the problem.
Aksh

回答(1 个)

Ayush
Ayush 2023-9-8
Hi Aksh,
I understand that you want to optimise your code that is performing symbolic substitution interactively.
Some possible workarounds for optimisation are:
1. Pre-allocate memory: Pre-allocating memory for the “Psi_new” and “Num_Psi” matrix before the loop to improve performance. Since dynamic allocation leads to more memory usage.
2. Vectorisation: To avoid using nested loops, you can vectorise the substitution process. You can use the “arrayfun” function to apply the function to each element of the “Psi” array. To covert the elements of “Psi” (symbolic expression matrix) into a set of functions you can use the “matlabFunction. You can refer to the below documentation to know more about the “arrayfun” and “matlabFunction” function:
3. Parallel Computation: If you have access to the Parallel Computing Toolbox, you can use the “parfor” loop to enable parallel computation to utilise multiple cores or processors. You can refer to the below documentation to know more about the “parfor” function:
Hope it helps,
Regards,
Ayush Misra

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by