I did calculation and got the following numbers
0.739128438976901 0.739128438976900
I want MATLAB to consider that they are equal, but MATLAB recognized that the first one was greater than the second. How can I make MATLAB consider them as they are equal ?
Thanks
x = 42
y = 42.00001
if abs(x-y) < tolerance
% do something
end
The setting for tolerance is up to you.
I don't know a whole lot about Matlab (I'm more of a Mathematica guy myself), but it seems there is a roundn(x,n) function which rounds an element x to the nearest multiple of 10^n. Perhaps this could be used here.
Related
I would like to solve the following optimization problem with Matlab: minimize f(t) when t >= 0.
There's fseminf function but i didn't understand well how to apply it to my case. Also it seems a bit overkill to use such a powerful tool for such a seemingly easy problem. I'll be grateful for any tips on how to apply fseminf here and any suggestions how else it can be solved.
Matlab is a numerical software so one 'simple' way to solve this problem is to calculate the value of f(t) for values of t>0 and then find the minimum of that. Depending on the function the number of ts that you want to evaluate might be smaller or larger.
One possible solution could be:
t = 0:0.001:10; % create values from 0 to 10 in steps of 0.001
f = t.^3+5; % evaluate the function for each value of 't'
[minF, locT] = min(f);
minF % this is the smallest value of the function
t(locT) % the minimum value occurred at this 't'
You should define t to be in the region where you expect the minimum to, if you define it wrong this would only find the local minimum. If the spacing between separate 't's is too large the minimum might also fall between them, that is why I choose a relatively small step of '0.001'.
I'm trying to code a MATLAB program and I have arrived at a point where I need to do the following. I have this equation:
I must find the value of the constant "Xcp" (greater than zero), that is the value that makes the integral equal to zero.
In order to do so, I have coded a loop in which the the value of Xcp advances with small increments on each iteration and the integral is performed and checked if it's zero, if it reaches zero the loop finishes and the Xcp is stored with this value.
However, I think this is not an efficient way to do this task. The running time increases a lot, because this loop is long and has the to perform the integral and the integration limits substitution every time.
Is there a smarter way to do this in Matlab to obtain a better code efficiency?
P.S.: I have used conv() to multiply both polynomials. Since cl(x) and (x-Xcp) are both polynomials.
EDIT: Piece of code.
p = [1 -Xcp]; % polynomial (x-Xcp)
Xcp=0.001;
i=1;
found=false;
while(i<=x_te && found~=true) % Xcp is upper bounded by x_te
int_cl_p = polyint(conv(cl,p));
Cm_cp=(-1/c^2)*diff(polyval(int_cl_p,[x_le,x_te]));
if(Cm_cp==0)
found=true;
else
Xcp=Xcp+0.001;
end
end
This is the code I used to run this section. Another problem is that I have to do it for different cases (different cl functions), for this reason the code is even more slow.
As far as I understood, you need to solve the equation for X_CP.
I suggest using symbolic solver for this. This is not the most efficient way for large polynomials, but for polynomials of degree 20 it takes less than 1 second. I do not claim that this solution is fastest, but this provides generic solution to the problem. If your polynomial does not change every iteration, then you can use this generic solution many times and not spend time for calculating integral.
So, generic symbolic solution in terms of xLE and xTE is obtained using this:
syms xLE xTE c x xCP
a = 1:20;
%//arbitrary polynomial of degree 20
cl = sum(x.^a.*randi([-100,100],1,20));
tic
eqn = -1/c^2 * int(cl * (x-xCP), x, xLE, xTE) == 0;
xCP = solve(eqn,xCP);
pretty(xCP)
toc
Elapsed time is 0.550371 seconds.
You can further use matlabFunction for finding the numerical solutions:
xCP_numerical = matlabFunction(xCP);
%// we then just plug xLE = 10 and xTE = 20 values into function
answer = xCP_numerical(10,20)
answer =
19.8038
The slight modification of the code can allow you to use this for generic coefficients.
Hope that helps
If you multiply by -1/c^2, then you can rearrange as
and integrate however you fancy. Since c_l is a polynomial order N, if it's defined in MATLAB using the usual notation for polyval, where coefficients are stored in a vector a such that
then integration is straightforward:
MATLAB code might look something like this
int_cl_p = polyint(cl);
int_cl_x_p = polyint([cl 0]);
X_CP = diff(polyval(int_cl_x_p,[x_le,x_te]))/diff(polyval(int_cl_p,[x_le,x_te]));
Firstly, I'm sure a simple answer exists for this, maybe I'm just not wording it right in searching for an answer online.
I'm trying to solve an equation that looks like this:
a*x*cot(a*x) == b
Where a and b are constants. Using
solve(a*x*cot(a*x) == b, x)
I'm getting a result I know is wrong (with the values I'm using for the constants, I'm getting like -227, and it should be something around +160.) I plotted it up in Mathematica as two separate functions, and they do cross each other right around there, but since the cot part is periodic, they do so many times.
I want to constrain Matlab's search for the solution to a specific interval, such as 0 to 200; how do I do that?
I'm pretty new to Matlab (rather more experienced in Mathematica).
You can specify the bounds on x using fzero with only two requirements
The function must be in a "residual" form (i.e., r(x) = 0)
The residual values at the two bounds must have opposite sign (this guarantees that a root exists within the interval for continuous functions).
So we re-write the function in residual form:
r = #(x) a*x*cot(a*x) - b;
define the interval
% These are just random numbers; the actual bounds should come
% from the graph the ensures r has different signs a xL and xR
xL = 150;
xR = 170;
and solve
x = fzero(r,[xL,xR]);
I see you were trying to use the Symbolic Toolbox for a solution, but since the equation is a non-linear combination of a polynomial and a trigonometric function, there is more than likely no closed form solution. So I differed to a non-linear, numeric root-finder.
I tried some values and it seems solve returns a numeric solution. This is the documented behaviour if no analytic solution is found.
In this case, you may directly call the numeric solver with a matching start value
vpasolve(a*x*cot(a*x) == b, x,160)
It's not exactly what you asked for, but using your reading from the plot as a start value should do it.
Has anyone tried plotting a sine function for large values in MATLAB?
For e.g.:
x = 0:1000:100000;
plot(x,sin(2*pi*x))
I was just wondering why the amplitude is changing for this periodic function? As per what I expect, for any value of x, the function has a period of 2*pi. Why is it not?
Does anyone know? Is there a way to get it right? Also, is this a bug and is it already known?
That's actually not the amplitude changing. That is due to the numerical imprecisions of floating point arithmetic. Bear in mind that you are specifying an integer sequence from 0 to 100000 in steps of 1000. If you recall from trigonometry, sin(n*x*pi) = 0 when x and n are integers, and so theoretically you should be obtaining an output of all zeroes. In your case, n = 2, and x is a number from 0 to 100000 that is a multiple of 1000.
However, this is what I get when I use the above code in your post:
Take a look at the scale of that graph. It's 10^{-11}. Do you know how small that is? As further evidence, here's what the max and min values are of that sequence:
>> min(sin(2*pi*x))
ans =
-7.8397e-11
>> max(sin(2*pi*x))
ans =
2.9190e-11
The values are so small that they might as well be zero. What you are visualizing in the graph is due to numerical imprecision. As I mentioned before, sin(n*x*pi) = 0 when n and x is are integers, under the assumption that we have all of the decimal places of pi available. However, because we only have 64-bits total to represent pi numerically, you will certainly not get the result to be exactly zero. In addition, be advised that the sin function is very likely to be using numerical approximation algorithms (Taylor / MacLaurin series for example), and so that could also contribute to the fact that the result may not be exactly 0.
There are, of course, workarounds, such as using the symbolic mathematics toolbox (see #yoh.lej's answer). In this case, you will get zero, but I won't focus on that here. Your post is questioning the accuracy of the sin function in MATLAB, that works on numeric type inputs. Theoretically with your input into sin, as it is an integer sequence, every value of x should make sin(n*x*pi) = 0.
BTW, this article is good reading. This is what every programmer needs to know about floating point arithmetic and functions: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html. A more simple overview can be found here: http://floating-point-gui.de/
Because what is the exact value of pi?
This apparent error is due to the limit of floating point accuracy. If you really need/want to get around that you can do symbolic computation with matlab, see the difference between:
>> sin(2*pi*10)
ans =
-2.4493e-15
and
>> sin(sym(2*pi*10))
ans =
0
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