Matlab: Error using ==> mpower - matlab

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.

Related

Numerical gradient of a Matlab function evaluated at a certain point

I have a Matlab function G(x,y,z). At each given (x,y,z), G(x,y,z) is a scalar. x=(x1,x2,...,xK) is a Kx1 vector.
Let us fix y,z at some given values. I would like your help to understand how to compute the derivative of G with respect to xk evaluated at a certain x.
For example, suppose K=3
function f= G(x1,x2,x3,y,z)
f=3*x1*sin(z)*cos(y)+3*x2*sin(z)*cos(y)+3*x3*sin(z)*cos(y);
end
How do I compute the derivative of G(x1,x2,x3,4,3) wrto x2 and then evaluate it at x=(1,2,6)?
You're looking for the partial derivative of dG/dx2
So the first thing would be getting rid of your fixed variables
G2 = #(x2) G(1,x2,6,4,3);
The numerical derivatives are finite differences, you need to choose an step h for your finite difference, and an appropriate method
The simplest one is
(G2(x2+h)-G2(x2))/h
You can make h as small as your numeric precision allows you to. At the limit h -> 0 the finite difference is the partial derivative

MATLAB finding roots, and # operator

x=1;
f=#(x) x^3 - (5/x^2)-4*sin(x)-2;
fzero(f,x)
ans =
1.9227
I am supposed to find the root of the equation, x^3 - (5/x^2)-4*sin(x)-2, and the above code is the solution for it.
I don't understand the general mechanism of this code.
(1) What does # operator do?
I know its something like function handle, but I don't understand what function handle is.
(2) How does it work when it includes x in the parenthesis?
(3) How can there be a function fzero(), when I haven't made a script for fzero()?
(4) why are there two variables inside fzero()?
I don't understand that the variable 'f' does there
(5) Why did it declare x=1 in the beginning?
Please consider that I am pretty much new to MATLAB, and don't know much.
f = #(x) ... is the way to declare an anonymous function in MATLAB, actually not very different than creating a function normally in MATLAB such as function output = f(input) .... It is just the pratical way especially when you are working with mathematical functions.
#(x) defines that x is the variable of which is the same as f(x) in mathematics. fzero() is MATLAB's existing function to calculate the x value for f(x) = 0 which means calculating roots of defined funtion. Giving your x a real value at the beginning does mean the starting point to find the root. It will find the roots greater than 1 in your case. It will be very clear for you when you read existing documentation of MATLAB.
Edit:
If you give an interval such as x = [0 1] instead of x = 1, fzero(f,x) would try to calculate roots of f function in given interval, if there is no roots exist in that interval it woud return a NaN value.

How to integrate p(x)*f(x) where p(x) is a polynomial and f(x) is a function? MATLAB

I want to integrate p(x)*f(x) where p(x) is a polynomial and f(x) is a function. I am working in MATLAB.
I have the coefficients of the polynomial in a vector.
p=[2,3,4,5];
funct=#(x) xˆ2;
I know how to integrate the function by itself, as well as how to integrate the polynomial by itself. However, I just can't find any info on how to take the integral of the product.
Here is what I tried:
p2=poly2sym(p)
integral(funct*p2,-1,1)
but p2 is not a function handle.
Help is appreciated!
Yes, p2 is not a function handle – it's a symbolic expression, but integral performs numerical integration and requires a function handle that returns floating point values. Even if p2 was a function handle, multiply function handles (e.g., funct*p2) is not valid. Additionally, funct needs to be vectorized.
Instead of poly2sym, you can evaluate your integral numerically with polyval like this:
p = [2,3,4,5];
funct = #(x)x.^2; % use element-wise power to vectorize
p2 = #(x)polyval(p,x);
integral(#(x)funct(x).*p2(x),-1,1) % evaluate two handles into one
which returns 4.533333333333333. Or you could compute this particular integral symbolically using int:
p = [2,3,4,5];
syms x;
funct = x^2;
p2 = poly2sym(p,x);
int(funct*p2,x,-1,1)
which returns the exact rational value of 68/15 (use vpa or double to convert to decimal or floating point, respectively).

How to solve an equation with piecewise defined function in Matlab?

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.

Is my equation too complex for matlab to integrate?

I have a code that needs to evaluate the arc length equation below:
syms x
a = 10; b = 10; c = 10; d = 10;
fun = 4*a*x^3+3*b*x^2+2*c*x+d
int((1+(fun)^2)^.5)
but all that returns is below:
ans = int(((40*x^3 + 30*x^2 + 20*x + 10)^2 + 1)^(1/2), x)
Why wont matlab evaluate this integral? I added a line under to check if it would evaulate int(x) and it returned the desired result.
Problems involving square roots of functions may be tricky to intgrate. I am not sure whether the integral exists or not, but it if you look up the integral of a second order polynomial you will see that this one is already quite a mess. What you would have, would you expand the function inside the square root, would be a ninth order polynomial. If this integral actually would exist it may be too complex to calculate.
Anyway, if you think about it, would anyone really become any wiser by finding the analytical solution of this? If that is not the case a numerical solution should be sufficient.
EDIT
As thewaywewalk said in the comment, a general rule to calculate these kinds of integrals would be valuable, but to know the primitive function to the particular integral would probably be overkill (if a solution could be found).
Instead define the function as an anonymous function
fun = #(x) sqrt((4*a*x.^3+3*b*x.^2+2*c*x+d).^2+1);
and use integral to evaluate the function between some range, eg
integral(fun,0,100);
for evaluating the function in the closed interval [0,100].