Mohammad Javad Naderi
Mohammad Javad Naderi

Reputation: 506

Changing Numbers in Matlab Symbolic Expression

In Matlab, I have a symbolic variable f and I want to substitute all numbers less than 10^-5 with 0.

For example

f=sym('0.89445*x^3 + 1e-8*x^2 + 4*x + 1.8e-13');

should turn into:

0.89445*x^3 + 4*x

How can it be done?

Upvotes: 1

Views: 314

Answers (2)

Rasman
Rasman

Reputation: 5359

You need to use the sym2poly to get the polynomial coefficients and the revert back to sym form with poly2sym

dummy = sym2poly(f);
new_f = poly2sym(((abs(dummy)>1e-5)) .* dummy,'x');

Upvotes: 1

m_power
m_power

Reputation: 3204

you could declare the constants before calling the sym function :

clear
clc
a = 0.89555;
b = 1e-8;
c = 4;
d = 1.8e-13;
if a < 1e-5
    a = 0;
end
if b < 1e-5
    b = 0;
end
if c < 1e-5
    c = 0;
end
if d < 1e-5
    d = 0;
end
symVar = strcat(num2str(a), '*', 'x^3', '+', num2str(b), '*', 'x^2', '+', num2str(c), '*', 'x', '+', num2str(d));
f = sym(symVar);

There is probably a better way than using 4 if to check and declare the constants equal to zero.

I just found a way: replace the 4 if by an anonymous function :

clear
clc
a = 0.89555;
b = 1e-8;
c = 4;
d = 1.8e-13;
h = @(x) x>=1e-5; 0;
symVar = strcat(num2str(a*h(a)), '*', 'x^3', '+', num2str(b*h(b)), '*', 'x^2', '+', num2str(c*h(c)), '*', 'x', '+', num2str(d*h(d)));
f = sym(symVar);

Let me know if this work for you.

Upvotes: 1

Related Questions