NKN
NKN

Reputation: 6424

More efficient symbolic function evaluation

In order to perform function evaluation using normal variables one can do as follows:

f = @(x)x.^2+3*x-5;
x0 = -10:0.01:10;
p = f(x0);

But when using symbolic variables, the efficiency decreases drastically. For instance:

f = @(x)x.^2+3*x-5;
x0 = -10:0.001:10;

% using real values
tic;p = f(x0);toc

% using symbolic math
syms x;tic;P = double(subs(f,x,x0));toc


Elapsed time is 0.000686 seconds.
Elapsed time is 10.867689 seconds.

Is there a way to increase the speed while using symbols?

Upvotes: 0

Views: 193

Answers (1)

Daniel
Daniel

Reputation: 36710

The conversion from float to double kills the performance in this case. Never start with floating point math (x0 = -10:0.01:10;) and continue with symbolic math.

x0=sym(-10):sym(.001):sym(10);
P=double(f(x0));

Upvotes: 1

Related Questions