calculating bessel function of zero order on matlab - matlab

J(x)= 1/π integral cos(xsintheta). limits are from 0 to π.
Plot J(2pid/λ) as a function of d/λ in MATLAB for d/λ ranging between
0 and 2. At what distance of separation (in wavelengths) is the
correlation between the antennas 0.7, 0 ?
I do not understand how to integrate it in matlab, when i define syms theta and use
J_=integral(J,0,pi); there appears an error. secondly, when i integrate it manually, the answer appears 0. Kindly help me with it.

Unless you really need to calculate this manually, you should use Matlab's built-in besselj function to calculate the zeroth order Bessel function of the first kind:
dlam = 0:0.01:2;
x = 2*pi*dlam;
y = besselj(0,x)
figure;
plot(x,y)
This will be faster and more accurate the performing quadrature.
If you wish to determine the to a high degree of accuracy the points at which y is 0.7 or 0, as opposed to reading them from a plot, you can use symbolic math in conjunction with solve and sym/besselj. Assuming that this is what that part of the question is about (I know nothing about antennas), you can use something like:
syms x;
double(solve(besselj(0,x) == 0.7,x))

The integral command does not work on syms, it works on functions. For symbolic integration, the command is int.
I don’t have MATLAB at hand right now to check for typos etc., but something like this should work:
x = 0.1;
integral(#(theta) cos(x.*sin(theta)), 0, pi)/pi
Or even
bessel = #(x) integral(#(theta) cos(x.*sin(theta)), 0, pi)/pi;
bessel(0.1)

Related

How to Fit a decay exponential function in Matlab

I have to fit the dots, results of measurements, by an exponential function on Matlab. My profesor asked me to use only
fminsearch
polyval
polyfit
One of them or both. I have to find the parameters a and b (the value) which are fitting it.
There is the lines I wrote :
x=[1:10:70]
y=[0:10:70]
x=[12.5,11.8,10.8,10.9,6.5,6.2,6.1,5.423,4.625]
y=[0,0.61,1.3,1.4,14.9,18.5,20.1,29.7,58.2]
xlabel('Conductivité')
ylabel('Inductance')
The function has the form a*e^(-b*x) +c
Well polyfit and polyval are only usefull for working with polynomials. So you would have to write a minimization problem of the form min(f(x)).
functionToMinimize = #(pars, x, y)(norm(pars(1).*exp(-pars(2).*x) - y));
targetFunctionForFminseardch = #(pars)(functionToMinimize(pars, x, y));
minPars = fminsearch(targetFunctionForFminseardch, [0, 1])
Read up on anonymous functions and the use of vector norms if you have questions how to construct such a minimization problem.
Your code also has some flaws. Why are you defining x and y twice when you only want to use the actual measured data?

How to have square wave in Matlab symbolic equation

My project require me to use Matlab to create a symbolic equation with square wave inside.
I tried to write it like this but to no avail:
syms t;
a=square(t);
Input arguments must be 'double'.
What can i do to solve this problem? Thanks in advance for the helps offered.
here are a couple of general options using floor and sign functions:
f=#(A,T,x0,x) A*sign(sin((2*pi*(x-x0))/T));
f=#(A,T,x0,x) A*(-1).^(floor(2*(x-x0)/T));
So for example using the floor function:
syms x
sqr=2*floor(x)-floor(2*x)+1;
ezplot(sqr, [-2, 2])
Here is something to get you started. Recall that we can express a square wave as a Fourier Series expansion. I won't bother you with the details, but you can represent any periodic function as a summation of cosines and sines (à la #RTL). Without going into the derivation, this is the closed-form equation for a square wave of frequency f, with a peak-to-peak amplitude of 2 (i.e. it goes from -1 to 1). Recall that the frequency is the amount of cycles per seconds. Therefore, f = 1 means that we repeat our square wave every second.
Basically, what you have to do is code up the first line of the equation... but how in the world would you do that? Welcome to the world of the Symbolic Math Toolbox. What we will need to do before hand is declare what our frequency is. Let's assume f = 1 for now. With the Symbolic Math Toolbox, you can define what are considered as mathematics variables within MATLAB. After, MATLAB has a whole suite of tools that you can use to evaluate functions that rely on these variables. A good example would be if you want to use this to define a closed-form solution of a function f(x). You can then use diff to differentiate and see what the derivative is. Try it yourself:
syms x;
f = x^4;
df = diff(f);
syms denotes that you are declaring anything coming after the statement to be a mathematical variable. In this case, x is just that. df should now give you 4x^3. Cool eh? In any case, let's get back to our problem at hand. We see that there are in fact two variables in the periodic square function that need to be defined: t and k. Once we do this, we need to create our function that is inside the summation first. We can do this by:
syms t k;
f = 1; %//Define frequency here
funcSum = (sin(2*pi*(2*k - 1)*f*t) / (2*k - 1));
That settles that problem... now how do we encapsulate this into an infinite sum!? The sum command in MATLAB assumes that we have a finite array to sum over. If you want to symbolically sum over a function, we must use the symsum function. We usually call it like this:
funcOut = symsum(func, v, start, finish);
func is the function we wish to sum over. v is the summation variable that we wish to use to index in the sum. In our case, that's k. start is the beginning of the sum, which is 1 in our case, and finish is where we wish to finish up our summation. In our case, that's infinity, and so MATLAB has a special keyword called Inf to denote that. Therefore:
xsquare = (4/pi) * symsum(funcSum, k, 1, Inf);
xquare now contains your representation of a square wave defined in terms of the Symbolic Math Toolbox. Now, if you want to plot your square wave and see if we have this right. We can do the following. Let's go between -3 <= t <= 3. As such, you would do something like this:
tVector = -3 : 0.01 : 3; %// Choose a step size of 0.01
yout = subs(xsquare, t, tVector);
You will notice though that there will be some values that are NaN. The reason why is because right at a multiple of the period (T = 1, 2, 3, ...), the behaviour is undefined as the derivative right at these points is undefined. As such, we can fill this in using either 1 or -1. Let's just choose 1 for now. Also, because the Fourier Series is generally a complex-valued function, and the square-wave is purely real, the output of this function will actually give you a complex-valued vector. As such, simply chop off the complex parts to get the real parts only:
yout = real(double(yout)); %// To cast back to double.
yout(isnan(yout)) = 1;
plot(tVector, yout);
You'll get something like:
You could also do this the ezplot way by doing: ezplot(xsquare). However, you'll see that at the points where the wave repeats itself, we get NaN values and so there is a disconnect between the high peak and low peak.
Note:
Natan's solution is much more elegant. I was still writing this post by the time he put something up. Either way, I wanted to give a more signal processing perspective to how to do this. Go Fourier!
A Fourier series for the square wave of unit amplitude is:
alpha + 2/Pi*sum(sin( n * Pi*alpha)/n*cos(n*theta),n=1..infinity)
Here is a handy trick:
cos(n*theta) = Re( exp( I * n * theta))
and
1/n*exp(I*n*theta) = I*anti-derivative(exp(I*n*theta),theta)
Put it all together: pull the anti-derivative ( or integral ) operator out of the sum, and you get a geometric series. Then integrate and finally take the real part.
Result:
squarewave=
alpha+ 1/Pi*Re(I*ln((1-exp(I*(theta+Pi*alpha)))/(1-exp(I*(theta-Pi*alpha)))))
I tried it in MAPLE and it works great! (probably not very practical though)

Matlab Finding the Zeros of a Symbolic Function

I have a symbolic function, whose zeros I am particular interested in knowing. I have searched through google, trying to find something related to my query, but was unsuccessful.
Could someone please help me?
EDIT:
T(x,t) = 72/((2*n+1)^2*pi^3)*(1 - (2*n+1)^2*pi^2*t/45 + (2*n+1)^4*pi^4*t^2/(2*45^2) - (2*n+1)^6*pi^6*t^3/(6*45^3))*(2*n+1)*pi*x/3;
for i=1:1:1000
T_new = 72/((2*i+1)^2*pi^3)*(1 - (2*i+1)^2*pi^2*t/45 + (2*i+1)^4*pi^4*t^2/(2*45^2) - (2*i+1)^6*pi^6*t^3/(6*45^3))*(2*i+1)*pi*x/3;
T = T + T_new;
end
T = T - 72/((2*n+1)^2*pi^3)*(1 - (2*n+1)^2*pi^2*t/45 + (2*n+1)^4*pi^4*t^2/(2*45^2) - (2*n+1)^6*pi^6*t^3/(6*45^3))*(2*n+1)*pi*x/3;
T = T(1.5,t);
T_EQ = 0.00001
S = solve(T - T_EQ == 0,t);
The problem that I get is that S is an a vector which contains imaginary numbers. I expected a real number, because I am trying to calculate a time.
Here is a little background as to what I am trying to do:
http://hans.math.upenn.edu/~deturck/m241/solving_the_heat_eqn.pdf
In the given link is the heat equation solved for a particular one-dimensional case. The temperature distribution, that satisfies the prescribed boundary and initial conditions, is given on page 50, I believe.
What I would like to do is find the time at which the one-dimensional object equilibrates with the environment, which is held at a constant temperature of T=0. As far as I know, the easiest way to do this would be to use the Taylor expansion of the exponential function, using only the first few terms, because I expect the equilibrium time to be relatively short; and then use the small angle approximation for the sine function, because the rod has a relatively small length. Doing just this, I made a for loop to generate terms just as the summation function would--as you can see, I used 1000 terms.
Does what I am doing seem wrong to anyone? If there is a better method, could someone please recommend it?
You shouldn't be surprised to see imaginary roots provided that at least one root is real and positive, corresponding to your time. The question is if the time makes any sense due to the approximations that you're making. Have you plotted the the actual function to get a rough approximation for where the zero is?
I can't really comment on the particular problem you're trying to solve. You need to make sure that you're using enough Taylor expansion terms an that they are accurate for the domain. Have you tried this leaving in the exp and/or sin? Is there any reason that you can't just use zero? And have you checked that your summation has converged after 1,000 terms? Or does it converge much sooner or not at all?
The main question is why are you using symbolic math at all to solve this? This seems like a numeric problem unless you're experiencing overflow/underflow issues in your summation. You can find the zero using fzero in this case:
N = 32; % Number of terms in summation
x = 1.5;
T_EQ = 1e-5;
n = (2*(0:N)+1)*pi;
T = #(t)sum((72./n.^3).*exp(-n.^2*t/45).*sin(n*x/3))-T_EQ;
S = fzero(T,[0 1e3]) % Bounds around a root guarantees solution if function monotonic
which returns
S =
56.333877640358708
If you're going to use solve, I'd do something like the following to avoid for loops:
syms t
N = 32;
x = 1.5;
T_EQ = 1e-5;
n = (2*sym(0:N)+1)*sym(pi);
T(t) = sum((72./n.^3).*exp(-n.^2*t/45).*sin(n*x/3));
S = double(solve(T-T_EQ==0,t))
or, using symsum:
syms n t
N = 32;
x = 1.5;
T_EQ = 1e-5;
T(t) = symsum((72/(pi*(2*n+1))^3)*exp(-(pi*(2*n+1))^2*t/45)*sin(pi*(2*n+1)*x/3),n,0,N);
S = double(solve(T-T_EQ==0,t))
Lastly, your symbolic solutions are not even exact as some your pi variables are being converted to rational approximations. pi is floating point. Things like pi*t are generally safe if t is symbolic, because pi will be recognized as such. However, pi^2 is calculated in floating-point before being converted to symbolic due to order of operations. In general your should use sym('pi') or sym(pi) in symbolic expressions.
Assuming you have a polynomial or trigonometric function of x or y, and what you mean by "zeros" is the values where the function crosses the axis, i.e., either x or y is zero, you can call the value of the function when a variable is 0. An example:
syms x y
f=-cos(x)*exp(-(x^2)/40);
ezsurf(f,[-10,10])
F=matlabFunction(f,'vars',{[x]});
F([0])
The ezsurf just visualizes the plot. If you want a function of both x and y, you do something like the following:
syms x y
f=-cos(x)*cos(y)*exp(-(x^2+y^2)/40);
ezsurf(f,[-10,10])
F=matlabFunction(f,'vars',{[x,y]});
for y=0
solve(f)
end
This will give you the value of the function for which integer multiples of x correspond to zero points for y (values of the function that are on the y=0 plane).

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.

Double integral in MATLAB

I'm trying to find the power in an aperture from a Gaussian beam, where the aperture is offset from the beam center. The solution is the following equation (reference) (sorry, no LaTeX here):
Wz is a constant, along with a and r. I'm not sure how I can do something like this with MATLAB. Does anyone have a suggestion? I know there's a dblquad() function, but it assumes that the limits of integration are fixed, and not dependent on each other.
Using a bit of mathematical footwork, you could reduce the double integral to a single one (albeit containing the error function) which should be easier to calculate numerically in MATLAB:
(With reservation for errors; check the calculations yourself if possible.)
It turns out that more recent versions of MATLAB now have a quad2d() function, which does a 2d integral over a surface. Example 2 on the reference page details an example of doing this type of integration.
My code ended up looking something like this:
powerIntegral = #(x,y) 2/(pi*W^2)*exp(-2*((x - offsetDist).^2 + y.^2)/(W^2));
ymin = #(x) -sqrt(radius.^2 - x.^2);
ymax = #(x) sqrt(radius.^2 - x.^2);
powerRatioGaussian = quad2d(powerIntegral,-radius,radius,ymin,ymax);
Pretty nifty. Thanks for the help.
I am not sure, but I think that the symbolic toolbox can help you here. It is suited for this kind of problems. You can define your variables as symbolic vars using the syms command, and compute the integral symbolically. Then, you can assign the variables values and find the actual value.
Disclaimer : I have never actually used it myself.
Generally speaking, for numeric integration, you can transform an integral with dependent boundary conditions to one with independent boundaries by multiplying by a function that is 1 if you are inside the original boundary and 0 if you are outside. Then take your limits to be a square that contains your original conditions. In other words here you would multiply by
g(x,y) = ((x^2 + y^2) < a^2)
and your limits would be -a
You have to be a little careful about the continuity assumptions in your integration method, but you should be OK unless something is very weird. You can always check by changing your cell size and making sure the computed integral value doesn't change.
In this particular case, you could also make the transformation from cartesian to polar coordinates;
x = rcos(t)
y = rsin(t)
dxdy = rdrdt
Then your limits of integration would be r from 0 to a and t from 0 to 2*pi