eval() is too slow to numerically evaluate a function with X(t) and Y(t).

4 ビュー (過去 30 日間)
Perico Nasdemico
Perico Nasdemico 2023 年 4 月 20 日
コメント済み: Perico Nasdemico 2023 年 4 月 22 日
Hello,
I have a symbolic vector function, Vfun, that depends of two symbolic variables, X(t) and Y(t).
I want to evaluate Vfun for a series of numerical values for X and Y. Here's what I've tried. It works, but it's quite slow.
%% SETUP
syms X(t) Y(t) % (here the "(t)" isn't very relevant, but, I'll need to be able to use diff(Vfun,t) later on)
Vfun = [2*X + Y ; cos(X)*X^2 + Y^3 ; 3 + sin(Y)]; % (actually generated by an algorithm I can't change)
N = 40000;
Xnum = rand(1,N);
Ynum = rand(1,N);
%% TRYING TO EVALUATE Vfun WITH Xnum AND Ynum
tic
Mresults = zeros(3,N);
for j = 1:N
X = Xnum(j);
Y = Ynum(j);
Mresults(:,j) = subs(Vfun);
end
toc
I suspect the problem lies in the subs() function.
I've tried to use matlabFunction(), but it doesn't work and I don't know how to remove the "(t)"
Any ideas? I doesn't need to be ultra-fast, just something more reasonable.
Thank you in advance

採用された回答

James Tursa
James Tursa 2023 年 4 月 20 日
編集済み: James Tursa 2023 年 4 月 20 日
Something like this?
syms X(t) Y(t)
Vfun = [2*X + Y ; cos(X)*X^2 + Y^3 ; 3 + sin(Y)]
Vfun(t) = 
syms x y
vfun = subs(Vfun,[X Y],[x y])
vfun(t) = 
f = str2func(['@(x,y)' vectorize(char(vfun))]) % explicit code with no t
f = function_handle with value:
@(x,y)[2.*x+y;x.^2.*cos(x)+y.^3;sin(y)+3]
g = matlabFunction(vfun(0)) % using matlabFunction( ) with arbitrary t=0
g = function_handle with value:
@(x,y)[x.*2.0+y;x.^2.*cos(x)+y.^3;sin(y)+3.0]
N = 40000;
Xnum = rand(1,N);
Ynum = rand(1,N);
fnum = f(Xnum,Ynum);
gnum = g(Xnum,Ynum);
isequal(fnum,gnum)
ans = logical
1

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSymbolic Math Toolbox についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by