Constructing Symbolic Functions in Matlab - matlab

I'm trying to build a symbolic function in Matlab, as follows:
syms theta
Rx(theta) = cos(theta) + sin(theta);
When I enter Rx(0.1), Matlab returns cos(1/10) + sin(1/10)
But what I'm trying to do is get Matlab to evaluate it numerically. I can accomplish that with double(Rx(0.1)), but when doing the same thing on much more complex functions in a loop, the conversion to double each time causes it to run very slowly. Is there a way to alter Rx itself to give numeric output?

You could create a standard (non-symbolic), anonymous function from your symbolic function. For this you use matlabFunction
syms theta
Rx(theta) = cos(theta) + sin(theta);
Rxd = matlabFunction(Rx);
Then
>> Rxd(0.1)
ans =
1.094837581924854
Note that you may lose precision, though, as the computations are done numerically from the beginning, as opposed to symbolically and converted to double only at the end.

Related

how can I obtain exact values of sin and cos in matlab for angles like pi/4?

if I write in matlab
cos(pi/4)
I get this form:
0.7071
when I'd prefer getting it actual value of (2)^(1/2)/2 to write formulas more clearly.
is there a way to do what I ask?
You can you use the Symbolic Math toolbox that comes with many installs of Matlab:
theta = sym(pi)/4;
cos(theta)
which returns
ans =
2^(1/2)/2

Pi, Matlab Symbolic math toolbox have a bug?

Hello i have one question. When I calculate a division in matlab: x/(pi.^2)
syms x
x/(pi.^2)
ans =
(281474976710656*v)/2778046668940015
the correct answer is x/9.8696, so why is matlab giving me this result?
Is it a bug?
You have to use the vpa() command "Variable-precision arithmetic". Check this code:
syms x real; % define x as a real symbolic variable (not a complex variable)
vpa( x/(pi.^2), 5) % second argument define number of significant digits
For trigonometric expressions involving pi, it is sometimes good to define sym('pi'):
syms x real;
pi_s = sym('pi');
expr = x/pi_s^2
I try to always use the 'real' tag when using the symbolic toolbox. If you do not use it you are going to see a lot of complex conjugates and other things that are not important for your problem, because x is probably real variable.
Hope this helps,
No it is not a bug:
2778046668940015/281474976710656 = 9.8696

Matlab: Error using ==> mpower

I'm trying to use fsolve in matlab to solve a system of nonlinear equations numerically. Here is a test sample of my program, k1 and R are parameters and x0 is the start point.
function y=f(k1, R, x0)
pair=fsolve(#system,x0);
y=pair(1);
function r=system(v)
int1=#(x) exp(k1*x);
int2=#(x) exp(k1*x^2)/(x^4);
r(1)=exp(v(1))*quadl(int1,0,v(1));
r(2)=exp(k1*v(2))*quadl(int2,v(1),20)*k1*R;
end
end
The strange thing is when I run this program, matlab keeps telling me that I should use .^ instead of ^ in int2=#(x) exp(k1*x^2)/(x^4). I am confused because the x in that function handle is supposed to be a scalar when it is used by quadl. Why should I have to use .^ in this case?
Also I see that a lot of the examples provided in online documentations also use .^ even though they are clearly taking power of a scalar, as in here. Can anybody help explain why?
Thanks in advance.
in the function int2 you have used matrix power (^) where you should use element-wise power (.^). Also, you have used matrix right division (/) where you should use element-wise division (./). This is needed, since quadl (and friends) will evaluate the integrand int2 for a whole array of x's at a time for reasons of efficiency.
So, use this:
function y = f(k1, R, x0)
pair = fsolve(#system,x0);
y = pair(1);
function r = system(v)
int1 = #(x) exp(k1*x);
int2 = #(x) exp(k1*x.^2)./(x.^4);
r(1) = exp( v(1)) * quadl(int1,0,v(1));
r(2) = exp(k1*v(2)) * k1*R*quadl(int2,v(1),20);
end
end
Also, have a look at quadgk or integral (if you're on newer Matlab).
By the way, I assume your real functions int1 and int2 are different functions? Because these functions are of course trivial to solve analytically...
Internally MATLAB will evaluate the function fun for necessary values of x, which is more than one and x is a vector. a and b are only used to describe the limits of integration. From the documentation
fun is a function handle. It accepts a vector x and returns a vector y, the function fun evaluated at each element of x. Limits a and b must be finite.
Hence, you must use .^ to operate on individual elements of vector x.

Multiplication of large number with small number

I'm trying to compute a rather ugly integral using MATLAB. What I'm having problem with though is a part where I multiply a very big number (>10^300) with a very small number (<10^-300). MATLAB returns 'inf' for this even though it should be in the range of 0-0.0005. This is what I have
besselFunction = #(u)besseli(qb,2*sqrt(lambda*(theta + mu)).*u);
exponentFuncion = #(u)exp(-u.*(lambda + theta + mu));
where qb = 5, lambda = 12, theta = 10, mu = 3. And what I want to find is
besselFunction(u)*exponentFunction(u)
for all real values of u. The problem is that whenever u>28 it will be evaluated as 'inf'. I've heared, and tried, to use MATLAB function 'vpa' but it doesn't seem to work well when I want to use functions...
Any tips will be appreciated at this point!
I'd use logarithms.
Let x = Bessel function of u and y = x*exp(-u) (simpler than your equation, but similar).
Since log(v*w) = log(v) + log(w), then log(y) = log(x) + log(exp(-u))
This simplifies to
log(y) = log(x) - u
This will be better behaved numerically.
The other key will be to not evaluate that Bessel function that turns into a large number and passing it to a math function to get the log. Better to write your own that returns the logarithm of the Bessel function directly. Look at a reference like Abramowitz and Stegun to try and find one.
If you are doing an integration, consider using Gauss–Laguerre quadrature instead. The basic idea is that for equations of the form exp(-x)*f(x), the integral from 0 to inf can be approximated as sum(w(X).*f(X)) where the values of X are the zeros of a Laguerre polynomial and W(X) are specific weights (see the Wikipedia article). Sort of like a very advanced Simpson's rule. Since your equation already has an exp(-x) part, it is particularly suited.
To find the roots of the polynomial, there is a function on MATLAB Central called LaguerrePoly, and from there it is pretty straightforward to compute the weights.

Get the derivative of a function_handle in MATLAB

Is it possible to get the derivative of a function_handle as a other function_handle?
Like:
fun1 = #(x) x^2;
% do that ...
disp(fun2);
#(x) x*2
I know how to find the derivative of a symbolic function but I can't convert a function_handle to a symbolic function.
I'm new to matlab and I couldn't find any way on doing that. Thanks in advance.
The short answer is "No." MATLAB has no idea what the contents of the function_handle mean in a symbolic sense. You're better off creating it using syms in first place.
A longer answer would be either to use the Symbolic Math Toolbox, as suggested by #A Danesh, or an approximation, as suggested by #Andrey.
However, if you're always working with polynomials, then you can store the coefficients as an array and use the following functions:
polyval to evaluate
conv to multiply
deconv to divide
polyder to differentiate
polyint to integrate
syms x
f = #(x) x^2 + 1;
diff(f,x)
Ans:
2*x + 1
You can get an approximation function:
delta = 0.0001;
d = #(x)( (fun1(x+delta) - fun1(x))./delta)
you can't analytically from a function handle.
but if you got the symbolic math toolbox you can derivate the symbolic function and create a function handle from the result.