I am trying to make a function for MATLAB and I just don't see how to set it up right. I set up the function and then I do it manually with a calculator and I seem to get a different answer. I am sure it is the way I set it up. If someone can point out the problem I would greatly appreciate it.
I am trying to make the following function:
x*e^(cos(x))
what I wrote in MATLAB:
function y = fun2(a)
y = a*exp(cos(a))
end
Your code is just fine. The most likely explanation is that your calculator is in deg mode and so treats the argument to cos as an angle measured in degrees. Computer code like MATLAB code always use radians rather than degrees. Switch your calculator to rad mode and the two evaluations will agree.
Related
I am very new to mat lab and I am trying to get to grips with integrating under a curve.
I wanted to see this difference between using the 'trapz(y)' and 'trapz(x,y)' to find the area under a curve of a Gaussian function what I can not seem to understand is why I am getting two different area values and I am trying to figure which one is more accurate.
dataset = xlsread('Lab 3 Results 11.10.18 (1).xlsx','Sheet3','C6:D515');
x=dataset(:,1);
a1=38.38;
b1=1179;
c1=36.85;
d1=6.3
y=a1*exp(-((x-b1)/c1).^2)-d1;
int1=trapz(x,y)
int2=trapz(y)
So when I run this code I get int1=1738.3 and int2=5.78.4 but when I integrated this function by hand using the trapezium rule my ans came out to be nearer int1 rather that int2 is there anyone that could shed some light on this if possible? I just cant imagen visulay how matlab is using the trapz rule two different ways,
Neither implementation is more accurate, but trapz(y) assumes unit spacing of each data point (e.g., spacing between data points is uniformly x = 1). See trapz documentation.
Since you know the x-coordinates, use trapz(x,y).
Im using fminunc to minimize a function with 450 variables, here are the lines
opts = optimset('Display','Iter','MaxIter', 10000000,'MaxFunEvals', 100000000,'TolX', 1e-12,'TolFun', 1e-12);
[x,fval,exitflag] = fminunc(#function,x0,opts);
Note that I dont provide the gradient, so fminunc uses quasi-newton algorithm.
After some iterations it endes with this final message
fminunc stopped because it cannot decrease the objective function
along the current search direction.
But if I restart the code with the new point obtained, it continued decreasing, so Im not in the minimum.
It seems to me that the algorithm its just looking for the minimum simply along one direccion and when it finds it, it stops instead start searching among the other direccions.
Any clue how to modify the problem so that doesnt happen and find the minimum? or other programm I should use in order to do it faster?
Edit: the function is convex
This type of problem can occur if your have numerical noise in your objective function. Then gradient/hessian become noisy and the step is off, and line searching ends with precisely this error.
Try plotting your criterion in an interval around your starting values but change one of the parameters from x0(i) to
linspace(x0(i)(1-1e07, x(i)(1+1e07), 100), one number at the time.
If the function looks very jittery, that may be your problem.
Alternatively, maybe you are starting in a region where the function is not convex? In that case try fminsearch to begin with.
Otherwise, consider using analytic gradients.
Also, perhaps your tolerance are set too fine. Try reducing tolfun and tolx to 1e-08. Your problem is very high dimensional.
%Great Circle Distnace -- Simplified
%% 12.18993,133.45898 %% point 1 (lat/long)
%% 14.34243,65.12750 %% point 2 (lat/long)
%%VARIABLES%%
phi_1=12.18993; %lat_1
phi_2=14.34243; %lat_2
gam_1=133.45898; %long_1
gam_2=65.12750; %long_2
delt_gam = abs(gam_1 - gam_2); %absoulte difference in longitudes
R_Earth = 6371000; %mean radius of the earth in meters, change to FT to get distance accordingly
%%Unsimplified Great-Circle Equation -- Breaking it up into numerator and
%%denominator sections to avoid more problems -- Spherical Case of the
%%Vincenty Formula
Numer_sec1= ((cos(phi_2))*(sin(delt_gam))^2);
Numer_sec2=(((((cos(phi_1))*(sin(phi_2)))+((sin(phi_1))*(cos(phi_2))*(delt_gam))))^2);
Denom_1= (((sin(phi_1))*(sin(phi_2)))+((cos(phi_1))*(cos(phi_2))*delt_gam));
delt_sig2=atan((sqrt(Numer_sec1+Numer_sec2))/(Denom_1));
delt_GC2=R_Earth*delt_sig2;
disp(delt_GC2)
Hey guys, so currently I'm trying to get my distance between two Lat/Long Points hammered out with the Spherical Case of the Vincenty formula in MatLab. I've been referencing http://en.wikipedia.org/wiki/Great-circle_distance
And from that have created the above MatLab code. I tried the first equation that was given (a more simplified version, but to no avail either), so I'm going with the Vincenty case. Given the two lat/long points (decimal format) that are listed at the beginning of the code I've yet to calculate the correct distance in between the two points with my program. I can't seem to find out what's going on, so I'm asking you guys if there's any way you could help me figure this out.
Thank you very much in advance, and I'll be looking at the post frequently so that I can help you help me by answering any questions you may have about my code thus far.
Based on this website: http://williams.best.vwh.net/gccalc.htm the distance should be 7381.56km.
The first answer below has reminded me that I have the mapping toolbox, yet I'm not sure how to interpret the results that I'm getting, so please check the commment that I posted below.
[ARCLEN, AZ] = distance(LAT1,LON1,LAT2,LON2)
this does in-fact work, but I'm not sure what I do with the arc-length or the azimuth that's produced.
Thank you and Happy New Year to all.
If you just want an answer for the WGS84 without programming up the
algorithm and without paying for the Mapping Toolbox, download the
Matlab package Geodesics on an ellipsoid of revolution. This
includes an improvement in the Mapping Toolbox function,
called geoddistance. To solve your problem
format long;
geoddistance(12.18993,133.45898,14.34243,65.12750)
->
7381566.23351761
The arguments to geoddistance are in degrees and the result is in
meters. This does the calculation for the WGS84 ellipsoid. If you want
to use a difference ellipsoid specify a 5th argument [a,e] (equatorial
radius, eccentricity). (For a sphere, set e = 0; if you want to specify a prolate ellipsoid, set e to a pure imaginary. Accurate answers are returned for |e| < 0.2.)
Incidentally many of the pictures of geodesics shown in the
Wikipedia article on ellipsoidal geodesics are drawn with this
package.
The default units for trigonometric functions in MATLAB are radians. You appear to be specifying your latitudes and longitudes in degrees. Either translate to radians or else use the sind() and cosd() functions.
Or, if you happen to have the mapping toolbox installed (Mathworks does charge extra for it, however), you can just use the distance() function. The distance() function should in principle actually be the superior way, if it is available to you, because it can accept an ellipsoidal Earth model.
How do I calculate the time it takes for a curve to reach a specific x coordinate (in Matlab). Let's say we have:
dx/dt = x^2 + y^2 and dy/dt = 5.x.y and the curve starts at the point (a,b). With help from ode45 I was able to get the figure of the curve. I need too calculate the time it takes for the curve too reach x = c, (c>a). I've been told that this can be done by interpolation, but I have no idea how to write the code.
Depending on the behavior of your system around c, using data interpolation methods such as interp1 on the output may or may not work. The more rigorous way to solve this is either with events (see my answers here or here) or by using the single structure output argument form of ode45 in conjunction with deval and regular data interpolation methods. Both of these use polynomial interpolation methods designed to work with the underlying ODEs. Though more complicated, events are probably the best way to accuratly determine crossing times like your case.
I'm having some difficulty trying to comprehend the answers that Matlab and my calculator are returning from sinusoidal functions.
Firstly, I figured that pi/2 and 90 deg are analogous, but when I pass them into a cosine function I get these two outputs:
Calculator: cos(90) = 0
Calculator: cos(pi/2) = 0.9996242169
Matlab: cos(90) = -0.4481
Matlab: cos(pi/2) = 6.1232e-17
I have been referencing the unit circle and things don't seem to stack up. I am fairly new to maths, so maybe I may be doing something wrong. I've been practising with the sine function and this is a lot closer to my calculator results:
Matlab: sin(90) = 0.8940
Matlab: sin(pi/2) = 1
If you want to provide angle in degrees then use cosd and sind and if angle is in radians then use cos and sin.
cos(0) and cosd(0) are producing 1 on my computer. However cos(pi/2) is producing 6.1232e-17 and cosd(0) is producing 0.
you can check matlab specification which number is close to 0.
They are only analogous if you calculator or whatever you are using to calculate is in the correct mode. For instance if you calculator is in degrees then yes cos(90) will equal 0. So it seems your calculator is in degress and not radians. I haven't used matlab in a long time so I don't know how that setting is set up but this is the problem you are experiencing. You must know when doing any trigonometric calculation for any calculator, whether that be an actual calculator or a program like matlab, if it is expecting you to enter an argument in degrees or radians.