I have a density function f_N which is defined as follows (K_nu(z) is the modified Bessel function):
I want to compute the following integral for each value of N:
The following is the implementation of the above in matlab.
for N=1:100
syms z
f =#(z) (1/(gamma(N)*sqrt(pi))*(z/2).^(N-0.5).*besselk(0.5-N,z));
g = #(z) f(z).*log(f(z));
val=integral(g,0,Inf);
But when I run the above code, it's always returning NaN for varoious values of N with the following warning:
Warning: Infinite or Not-a-Number value encountered
Can someone suggest a simple way to do this or avoid this issue?
I don't think you are doing what you think you are doing. Your declaration of z as a symbol will get overridden by the function handle definition. That means the integral is not a symbolic one, but a numeric one. So what you simply need to do is to drop the function handle notation "#(z)" and do the integral symbolically...
My guess, without thoroughly analysing this, is that one of the points in you integration domain [0,inf] yields a value f (x)=inf, which would destroy a numeric integration technique, but perhaps not a symbolic one.
Related
I am just getting started with MATLAB and I have written a function to produce the binomial expansion of (x-a)^n when given x, a and n. As far as I can tell my code should work, but I do not seem to be using the function variables correctly.
function expand(a,n,x)
f = 0;
for k = 0:1:n
f = f + nchoosek(n,k).*x.^(n-k).*(-a).^k;
end
end
I need to be able to call the function and have it output f as the expanded polynomial in x, for example calling expand(1,3,x) should return x^3-3*x^2+3*x-1, but instead, calling it gives this error:
Unrecognized function or variable 'x'. It seems like it wants me to call the function with x being another number but I in fact need it to be able to be any letter to be used as the variable in the polynomial.
I know in Maple I would specify the variable type in the function to be x::name so I'm assuming there's something similar in MATLAB that I don't yet know.
Thanks for any help.
There are two ways to go about this:
Create x as a symbolic variable. For example, syms x; expand(a,n,x). This gives you the power of using the symbolic toolbox features like simplify(), but comes with a bit of a performance penalty. You should avoid using the symbolic toolbox in intensive calculations.
Return an anonymous function, f=#(X)sum(arrayfun(#(k)nchoosek....,1:n). This has better performance and does not require double(subs(...)) when you want an actual numeric value, but may be too difficult to implement for a beginner.
let us suppose that we have following task:Find the optimal value of weights
so that minimize following equation
where var-means variance of given x1 variable, also we have constraint that sum of these weights should be equal to 1
i have initialized anonymous function and weights for initial points
w=[0.5; 0.5];
>> f=#(x1,x2) (w(1)*w(1)*var(x1)+w(2)*w(2)*var(x2))
f =
#(x1,x2)(w(1)*w(1)*var(x1)+w(2)*w(2)*var(x2))
i think i should use function fmincon,
i have created A matrix
A=[1;1];
and b column
b=[1];
then i tried following fun
weighs=fmincon(f(x1,x2),w,A,b)
but it gives me error
Error using optimfcnchk (line 287)
FUN must be a function, a valid string expression, or an inline function
object.
could you help me please what is wrong? thanks in advance
You need to specify the function in fmincon as a function handle or anonymous function; f(x1,x2) evaluates to a scalar double, not a function handle. fmincon will want to evaluate this function with current values of w to check for the quality of the solution, so it needs a way to feed w as an input.
Thus, you need to
Change the function definition to f(w,x1,x2), i.e.
f=#(w,x1,x2) (w(1)*w(1)*var(x1)+w(2)*w(2)*var(x2))
Write the fmincon call as fmincon(#(u)f(u,x1,x2),...)
However, I would suggest to substitute 1-w(2) for w(1) (or vice versa) in your problem to reformulate it as an unconstrained optimization of one variable (unless w is a real weight, and has to remain between 0 and 1, in which case you still need a constraint).
Lets say, I have a function 'x' and a function '2sin(x)'
How do I output the intersects, i.e. the roots in MATLAB? I can easily plot the two functions and find them that way but surely there must exist an absolute way of doing this.
If you have two analytical (by which I mean symbolic) functions, you can define their difference and use fzero to find a zero, i.e. the root:
f = #(x) x; %defines a function f(x)
g = #(x) 2*sin(x); %defines a function g(x)
%solve f==g
xroot = fzero(#(x)f(x)-g(x),0.5); %starts search from x==0.5
For tricky functions you might have to set a good starting point, and it will only find one solution even if there are multiple ones.
The constructs seen above #(x) something-with-x are called anonymous functions, and they can be extended to multivariate cases as well, like #(x,y) 3*x.*y+c assuming that c is a variable that has been assigned a value earlier.
When writing the comments, I thought that
syms x; solve(x==2*sin(x))
would return the expected result. At least in Matlab 2013b solve fails to find a analytic solution for this problem, falling back to a numeric solver only returning one solution, 0.
An alternative is
s = feval(symengine,'numeric::solve',2*sin(x)==x,x,'AllRealRoots')
which is taken from this answer to a similar question. Besides using AllRealRoots you could use a numeric solver, manually setting starting points which roughly match the values you have read from the graph. This wa you get precise results:
[fzero(#(x)f(x)-g(x),-2),fzero(#(x)f(x)-g(x),0),fzero(#(x)f(x)-g(x),2)]
For a higher precision you could switch from fzero to vpasolve, but fzero is probably sufficient and faster.
I have been working on solving some equation in a more complicated context. However, I want to illustrate my question through the following simple example.
Consider the following two functions:
function y=f1(x)
y=1-x;
end
function y=f2(x)
if x<0
y=0;
else
y=x;
end
end
I want to solve the following equation: f1(x)=f2(x). The code I used is:
syms x;
x=solve(f1(x)-f2(x));
And I got the following error:
??? Error using ==> sym.sym>notimplemented at 2621
Function 'lt' is not implemented for MuPAD symbolic objects.
Error in ==> sym.sym>sym.lt at 812
notimplemented('lt');
Error in ==> f2 at 3
if x<0
I know the error is because x is a symbolic variable and therefore I could not compare x with 0 in the piecewise function f2(x).
Is there a way to fix this and solve the equation?
First, make sure symbolic math is even the appropriate solution method for your problem. In many cases it isn't. Look at fzero and fsolve amongst many others. A symbolic method is only needed if, for example, you want a formula or if you need to ensure precision.
In such an old version of Matlab, you may want to break up your piecewise function into separate continuous functions and solve them separately:
syms x;
s1 = solve(1-x^2,x) % For x >= 0
s2 = solve(1-x,x) % For x < 0
Then you can either manually examine or numerically compare the outputs to determine if any or all of the solutions are valid for the chosen regime – something like this:
s = [s1(double(s1) >= 0);s2(double(s2) < 0)]
You can also take advantage of the heaviside function, which is available in much older versions.
syms x;
f1 = 1-x;
f2 = x*heaviside(x);
s = solve(f1-f2,x)
Yes, the Heaviside function is 0.5 at zero – this gives it the appropriate mathematical properties. You can shift it to compare values other than zero. This is a standard technique.
In Matlab R2012a+, you can take advantage of assumptions in addition to the normal relational operators. To add to #AlexB's comment, you should convert the output of any logical comparison to symbolic before using isAlways:
isAlways(sym(x<0))
In your case, x is obviously not "always" on one side or the other of zero, but you may still find this useful in other cases.
If you want to get deep into Matlab's symbolic math, you can create piecewise functions using MuPAD, which are accessible from Matlab – e.g., see my example here.
Using the code,
syms x(t)
y=x^2
diff(y,t)
diff(y,x)
I get the following error:
2*D(x)(t)*x(t)
Error using sym/diff (line 26)
All arguments, except for the first one, must not be symbolic functions.
Is there a way to tackle this? Thanks for your time.
I dont know much about the Symbolic Math Toolbox, but taking a derivative wrt to a function does not seem to be supported (at least in a direct fashion) for diff.
You can substitute a variable, compute a derivative, and substitute the function back. Like so:
syms z
subs(diff(subs(y,x,z),z),z,x)
ans(t) = 2*x(t)