Reputation: 2127
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.
Upvotes: 1
Views: 1088
Reputation: 38042
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...
Upvotes: 2
Reputation: 11810
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
.
Upvotes: 2