Even better:You could go even more fancy and use a wrapper function GradOmega which builds such a function inside and makes it persistent, to get the same interface you had with your initial approach. The first time you call the function GradOmega the symbolic expression is evaluated, but on each consecutive call you will only have to evaluate the generated function handle, which means it should be nearly as fast as if you hard-coded it.function result = GradOmega(numX, numY, numZ, numMu)persistent numericalGradOmega;if isempty(numericalGradOmega) numericalGradOmega = GradOmegaFactory();endresult = numericalGradOmega(numX, numY, numZ, numMu);end像使用原始版本一样使用Use this like you would use your original versionresult = GradOmega(numX, numY, numZ, numMu);只需将两个函数复制并粘贴到单个GradOmega.m文件中. (GradOmega应该是文件中的第一个函数.)Just copy and paste both functions into a single GradOmega.m file. (GradOmega should be the first function in the file.)另一个提示:您甚至可以使用向量来评估此功能.不用事后再调用GradOmega(1,2,3,4)和GradOmega(5,6,7,8),您可以使用行向量通过调用GradOmega([1,5], [2,6], [3,7], [4,8])节省时间开销.Another tip: You can even evaluate this function using vectors. Instead of calling GradOmega(1,2,3,4) and GradOmega(5,6,7,8) afterwards, you can save the time overhead via the call GradOmega([1,5], [2,6], [3,7], [4,8]) using row vectors.另一个提示:要进一步清理代码,您还可以将第一行放入单独的symOmega.m文件中.Yet another tip: To clean up your code even more, you could also put the first lines into a separate symOmega.m file.function omega = symOmega()x = sym('x');y = sym('y');z = sym('z');mu = sym('mu');omega = 0.5*(x^2+y^2+z^2) + (1-mu)/((x+mu)^2+y^2+z^2)^0.5 + mu/((x+mu-1)^2+y^2+z^2)^0.5;这样,您不必在使用它的每个文件中都拥有此符号表达式的副本.如果您还想评估Omega本身,这可能会很有用,因为您可以使用此答案中列出的相同工厂方法.您将得到以下文件:symOmega.m,Omega.m和GradOmega.m,其中只有文件symOmega.m具有实际的数学公式,而其他两个文件都使用symOmega.m.This way you don't have to have a copy of this symbolic expression in every file you use it. This can be beneficial if you also want to evaluate Omega itself, as you then can make use of the same Factory-approach listed in this answer. You would end up with the following files: symOmega.m, Omega.m and GradOmega.m, where only the file symOmega.m has the actual mathematical formula and the other two files make use of symOmega.m. 这篇关于确保MATLAB不重新计算符号表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-21 12:15