Integral of a Recursive Function in MATLAB - matlab

I want to compute the following symbolic integral which is recursive :
function [y] = myfunc(i,T)
s = sym('s');
x= sym('x');
h=[....] %matrix n*n (function of x)
d=[....] %matrix n*1 (constants)
for k=1:n
if (T>0)
y= int(exp(-s*x)*h(i,k)*myfunc(k,T-x/d(i)),'x',0,T);
end
end
I expected MATLAB, while computing the integral, calls myfunc(k,T-x/d(i)) for different values of 'x' from 0 to T. However, it returns error since myfunc would be called with symbolic value 'x' and not the real value. Indeed, it cannot determine if (T>0) expression is true or false.
I would be thankful if you can suggest how this recursive integral can be computed ?. Thanks

If you want to ensure that a different real value is used in each step of a recursive function, you can define a variable to account for how deep you are.
Suppose we call it depth, and on the top level it is equal to 1. Each time you go one step deeper you increase depth by 1.
Now, if you want to get a number corresponding to the right depth, you can just call it as y(depth).

Related

Plotting the sum of series

I use this code and i don't know what it needs to work for my problem:
syms x k t
for t=0:10
num=((-1)^k)/k
t1=sin(8*3.1415*k*t)
S1=symsum((num*t1),k,1,2);
x=0.5-((1/3.1415)*S1);
end
Plot(x)
On the x axis I show time and on the y axis I show the function over four periods.
When I try to run the code I get the following error:
Undefined function 'symsum' for input arguments of type 'double'.
Maybe I can't use symsum with my argument type, but is there another function I can use? Sum also didn't work:
Error using sum Dimension argument must be a positive integer scalar within indexing range.
Since you want to plot x(t), you need to use plot(t,x) where t and x are vectors.
Instead of using for t=0:10, just let t=0:10 and calculate the corresponding x.
Also, the symbolic variable is just k.
syms k
t=0:10;
num=((-1)^k)/k;
t1=sin(8*3.1415*k*t);
S1=symsum((num*t1),k,1,2);
x=0.5-((1/3.1415)*S1);
plot(t,x)
It is noted that if you let t=0:10, then the sin(8*k*pi*t) will always be 0 since t is a vector of the integer from 0 to 10. The result of x(t) will be 5:
Output when t=0:10:
As you can see, the value of x(t) is very close to each other. Theoretically, they should all be 5. But there is some numerical approximation which leads to the small error.
You probably want non-integer t. Here is a output when t=0:0.1:10

Matlab fit with function returning vector with all the y(x_i) values

I am working on something and I haven't found any solution, maybe I didn't know how to correctly search for it...
I have two arrays of experimental data (x and y). x is a list of certain energies (512 values from 0 to 100 kev) and I want to fit them to a function which returns a vector of values of y for every x in the list (the energies are always the same, 512 certain values). This is because my function model contains several matrix and other functions.
So, I can't evaluate my function as f(x,a,b,c...) (with a,b,c the parameters to fit) and expect a single scalar, but I have to evaluate f(a,b,c...), and it returns a vector of y(x1),y(x2)...
Now, I want to fit my data to my model. But lsqcurvefit needs a function of the form f(x), I suppose that it evaluates every f(x). I could write my function so that every time it is called it evaluates the vector result, and then returns y for the given x, but it would be quite inefficient... And I'm sure there must be another way.
Any idea?
Maybe you can do an fminsearch on the sum of square errors? It is best to put all fitting parameters into one vector. Here I call it p.
f = #(x,p) (p(3)+p(1)*x.^p(2)).^(1/p(4); %example function with four free parameters
sqerr = #(x,y,p) sum((y-f(x,p)).^2); %sum of squared errors
p = [1,1,1,1]; %four starting conditions
p = fminsearch(#(p) sqerr(x,y,p),p); %fit
Then you can find your y(x_i) values by calling the function with the fitted paramters
f(x,p)

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.

Nonlinear square optimization task in matlab

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).

Calculate hypergeometric function

i need to calculate the degenerate hypergeometric function of two variables given by integral formula:
and I used Matlab for taking numerical integral:
l = 0.067;
h = 0.933;
n = 1.067;
o = 0.2942;
p = 0.633;
func_F=#(x)(x.^(l-1)).*((1-x).^(n-l-1)).*((1-x.*o).^(-h)).*exp(x.*p);
hyper= quadl(func_F,0,1,'AbsTol',1e-6); % i use 'AbsTol' to avoid warnings
disp(hyper);
The result i got is 54.9085, and i know this value is wrong! So please help me to calculate true value of the above integral with singularity at 0.
I don't see where you have the Gamma functions in your code. Did you forget them, or did the value you were expecting already compensate for the lack of them?
Also, maybe you can state why "this value is wrong." Otherwise we are just guessing.
Edit: one more thing, as per the Matlab help page on this function, it might be better to use quadgk. See the following quote (near the bottom of the page):
The quadgk function will integrate functions that are singular at
finite endpoints if the singularities are not too strong. For example,
it will integrate functions that behave at an endpoint c like log|x-c|
or |x-c|p for p >= -1/2. If the function is singular at points inside
(a,b), write the integral as a sum of integrals over subintervals with
the singular points as endpoints, compute them with quadgk, and add
the results.
Bottom line is the the singularities near the endpoints (when your x gets near 0 or 1) might cause some problems.