how to integrate this Function in matlab - matlab

I'm new on matlab.
How can I integrate this line of code ? ?
p2= polyfit(x,y,length(x));
from= x(1);
to= x(length(x));
I need the integration of p2.
I tried a lot with the Integration function:
value = integral(p2,from,to);
but I got
Error using integral (line 82) First input argument must be a function
handle.
Error in poly_integral (line 5)
value = integral(p2,from,to);

That is because p2, in your code, is not a function. It is just a vector of coefficients. The first argument for integral needs to be handle to the function that you want to integrate.
Judging from your code, it seems that you would want to define a function that evaluates the polynomial p2. If so, you could do something like the following example:
% take an example set of x and y
x = linspace(0, pi, 1000); % uniform samples between 0 to pi
y = sin(x); % assume, for sake of example, output is sine function of input
% polynomial fit
p2 = polyfit(x,y,4); % 4th order polynomial
% Note that, in general, the order should be much smaller than length(x).
% So you probably should review this part of your code as well.
% define a function to evaluate the polynomial
fn = #(x) polyval(p2, x);
% this means: fn(x0) is same as polyval(p2, x0)
% compute integral
value = integral(fn,x(1),x(end));

You can use the polyint function to get the polynomial coefficients for exact integration of the polynomial:
p2 = polyfit(x,y,length(x));
int = diff(polyval(polyint(p2),x([1 end])));

Related

Interpolation using chebyshev points

Interpolate the Runge function of Example 10.6 at Chebyshev points for n from 10 to 170
in increments of 10. Calculate the maximum interpolation error on the uniform evaluation
mesh x = -1:.001:1 and plot the error vs. polynomial degree as in Figure 10.8 using
semilogy. Observe spectral accuracy.
The runge function is given by: f(x) = 1 / (1 + 25x^2)
My code so far:
x = -1:0.001:1;
n = 170;
i = 10:10:170;
cx = cos(((2*i + 1)/(2*(n+1)))*pi); %chebyshev pts
y = 1 ./ (1 + 25*x.^2); %true fct
%chebyshev polynomial, don't know how to construct using matlab
yc = polyval(c, x); %graph of approx polynomial fct
plot(x, yc);
mErr = (1 / ((2.^n).*(n+1)!))*%n+1 derivative of f evaluated at max x in [-1,1], not sure how to do this
%plotting stuff
I know very little matlab, so I am struggling on creating the interpolating polynomial. I did some google work, but I was confused with the current functions as I didn't find one that just simply took in points and the polynomial to be interpolated. I am also a bit confused in this case of whether I should be doing i = 0:1:n and n=10:10:170 or if n is fixed here. Any help is appreciated, thank you
Since you know very little about MATLAB, I will try explain everything step by step:
First, to visualize the Runge function, you can type:
f = #(x) 1./(1+25*x.^2); % Runge function
% plot Runge function over [-1,1];
x = -1:1e-3:1;
y = f(x);
figure;
plot(x,y); title('Runge function)'); xlabel('x');ylabel('y');
The #(x) part of the code is a function handle, a very useful feature of MATLAB. Notice the function is properly vecotrized, so it can receive as an argument a variable or an array. The plot function is straightforward.
To understand the Runge phenomenon, consider a linearly spaced vector of [-1,1] of 10 elements and use these points to obtain the interpolating (Lagrange) polynomial. You get the following:
% 10 linearly spaced points
xc = linspace(-1,1,10);
yc = f(xc);
p = polyfit(xc,yc,9); % gives the coefficients of the polynomial of degree 10
hold on; plot(xc,yc,'o',x,polyval(p,x));
The polyfit function does a polynomial curve fitting - it obtains the coefficients of the interpolating polynomial, given the poins x,y and the degree of the polynomial n. You can easily evaluate the polynomial at other points with the polyval function.
Obseve that, close to the end domains, you get an oscilatting polynomial and the interpolation is not a good approximation of the function. As a matter of fact, you can plot the absolute error, comparing the value of the function f(x) and the interpolating polynomial p(x):
plot(x,abs(y-polyval(p,x))); xlabel('x');ylabel('|f(x)-p(x)|');title('Error');
This error can be reduced if, instead of using a linearly space vector, you use other points to do the interpolation. A good choice is to use the Chebyshev nodes, which should reduce the error. As a matter of fact, notice that:
% find 10 Chebyshev nodes and mark them on the plot
n = 10;
k = 1:10; % iterator
xc = cos((2*k-1)/2/n*pi); % Chebyshev nodes
yc = f(xc); % function evaluated at Chebyshev nodes
hold on;
plot(xc,yc,'o')
% find polynomial to interpolate data using the Chebyshev nodes
p = polyfit(xc,yc,n-1); % gives the coefficients of the polynomial of degree 10
plot(x,polyval(p,x),'--'); % plot polynomial
legend('Runge function','Chebyshev nodes','interpolating polynomial','location','best')
Notice how the error is reduced close to the end domains. You don't get now that high oscillatory behaviour of the interpolating polynomial. If you plot the error, you will observe:
plot(x,abs(y-polyval(p,x))); xlabel('x');ylabel('|f(x)-p(x)|');title('Error');
If, now, you change the number of Chebyshev nodes, you will get an even better approximation. A little modification on the code lets you run it again for different numbers of nodes. You can store the maximum error and plot it as a function of the number of nodes:
n=1:20; % number of nodes
% pre-allocation for speed
e_ln = zeros(1,length(n)); % error for the linearly spaced interpolation
e_cn = zeros(1,length(n)); % error for the chebyshev nodes interpolation
for ii=1:length(n)
% linearly spaced vector
x_ln = linspace(-1,1,n(ii)); y_ln = f(x_ln);
p_ln = polyfit(x_ln,y_ln,n(ii)-1);
e_ln(ii) = max( abs( y-polyval(p_ln,x) ) );
% Chebyshev nodes
k = 1:n(ii); x_cn = cos((2*k-1)/2/n(ii)*pi); y_cn = f(x_cn);
p_cn = polyfit(x_cn,y_cn,n(ii)-1);
e_cn(ii) = max( abs( y-polyval(p_cn,x) ) );
end
figure
plot(n,e_ln,n,e_cn);
xlabel('no of points'); ylabel('maximum absolute error');
legend('linearly space','chebyshev nodes','location','best')

How to smooth a stairstep-like graph in Matlab

The stairstep-look of the graph is unintentional. When I plot the same-sized vectors Arb and V (plot (Arb, V, 'r')) I get the following graph:
enter image description here
To make it smoother, I tried using 1-D data interpolation, interp1, as follows:
xq = 0:0.001:max(Arb);
Vq = interp1 (Arb, V, xq);
plot (xq, Vq);
However, I get this error message:
Error using interp1>reshapeAndSortXandV (line 416)
X must be a vector.
Error in interp1 (line 92)
[X,V,orig_size_v] = reshapeAndSortXandV(varargin{1},varargin{2})
interp1 will use linear interpolation on your data so it won't help you much. One thing you can try is to use a cubic spline with interp1 but again given the nature of the data I don't think it will help much. e.g.
Alternative 1. Cubic Spline
xq = 0:0.001:max(Arb);
Vq = interp1 (Arb, V, xq, 'spline');
plot (xq, Vq);
Alternative 2. Polynomial fit
Another alternative you can try is, polynomial interpolation using polyfit. e.g.
p = polifit(Arb, V, 2); % I think a 2nd order polynomial should do
xq = 0:0.001:max(Arb);
Vq = polyval(p, xq);
plot (xq, Vq);
Alternative 3. Alpha-beta filter
Last but not least, another thing to try is to use an smoothing alpha-beta filter on your V data. One possible implementation can be:
% x is the input data
% a is the "smoothing" factor from [0, 1]
% a = 0 full smoothing
% a = 1 no smoothing
function xflt = alphaBeta(x, a)
xflt = zeros(1,length(x));
xflt(1) = x(1);
a = max(min(a, 1), 0); % Bound coefficient between 0 and 1;
for n = 2:1:length(x);
xflt(n) = a * x(n) + (1 - a) * xflt(n-1);
end
end
Usage:
plot (Arb, alphaBeta(V, 0.65), 'r')

Curvefitting for power law function y= a(x^b)+c

I am new to MATLAB, and I am trying to fit a power law through a dataset. I have been trying to use isqcurvefit function, but I am unsure how to proceed as the instructions found through Google are too convoluted for a beginner. I would like to derive the values b and c from the equation y = a(x^b)+c, and any suggestions would be greatly appreciated. Thanks.
You can use lsqcurvefit to fit a non linear curve through measured data points in least-square sense as follows:
% constant parameters
a = 1; % set the value of a
% initial guesses for fitted parameters
b_guess = 1; % provide an initial guess for b
c_guess = 0; % provide an initial guess for c
% Definition of the fitted function
f = #(x, xdata) a*(xdata.^x(1))+x(2);
% generate example data for the x and y data to fit (this should be replaced with your real measured data)
xdata = 1:10;
ydata = f([2 3], xdata); % create data with b=2 and c=3
% fit the data with the desired function
x = lsqcurvefit(f,[b_guess c_guess],xdata,ydata);
%result of the fit, i.e. the fitted parameters
b = x(1)
c = x(2)

Errors when using the Integral2 function in MATLAB

As far as I can tell, no one has asked this.
I've been asked to compute the double integral of a function, and also the same double integral but with the order of integration swapped (i.e: first integrate for dydx, then dxdy). Here is my code:
%Define function to be integrated
f = #(x,y) y^2*cos(x);
%First case. Integration order: dydx
ymin = #(x) cos(x);
I = integral2(f,ymin,1,0,2*pi)
%Second case. Integration order: dxdy
xmin = #(y) asin(y)+2*pi/2;
xmax = #(y) asin(y)-pi/2;
B = integral2(f,xmin,xmax,-1,1)
The error I'm getting is this:
Error using integral2 (line 71)
XMIN must be a floating point scalar.
Error in EngMathsA1Q1c (line 5)
I = integral2(f,ymin,1,0,2*pi)
I'm sure my mistake is something simple, but I've never used Integral2 before and I'm lost for answers. Thank you.
Per the integral2 documentation, the variable limits are given as the second pair of limits. So your first integral should be
% Define function to be integrated
f = #(x,y) y.^2.*cos(x);
% First case. Integration order: dydx
ymin = #(x) cos(x);
I = integral2(f,0,2*pi,ymin,1);
The set of constant limits always goes first, and Matlab assumes the first argument of f is associated with the first set of limits while the second argument of f is associated with the second set of limits, which may be a function of the first argument.
I point out that second part because if you wish to switch the order of integration, you also need to switch the order of the inputs of f accordingly. Consider the following example:
fun = #(x,y) 1./( sqrt(2*x + y) .* (1 + 2*x + y).^2 )
A nice little function that is not symmetric in its arguments (i.e., fun(x,y) ~= fun(y,x)). Let's integrate this over an elongated triangle in the first quadrant with vertices at (0,0), (2,0), and (0,1). Then integrating with dA == dy dx, we have
>> format('long');
>> ymax = #(x) 1 - x/2;
>> q = integral2(fun,0,2,0,ymax)
q =
0.220241017339352
Cool. Now let's integrate with dA == dx dy:
>> xmax = #(y) 2*(1-y);
>> q = integral2(fun,0,1,0,xmax)
q =
0.241956050772765
Oops, that's not equal to the first calculation! That's because fun is defined with x as the first argument and y as the second, but the previous call to integral2 is implying that y is the first argument to fun, and it has constant limits of 0 and 1. How do we fix this? Simply define a new function that flips the arguments:
>> fun2 = #(y,x) fun(x,y);
>> q = integral2(fun2,0,1,0,xmax)
q =
0.220241017706984
And all's right with the world. (Although you may notice small differences between the two correct answers due to the error tolerances of integral2, which can be adjusted via options per the documentation.)
The error states that you can't pass in a function for the limits of integration. You need to specify a scalar value for each limit of integration. Also, there are some errors in the dimensions/operations of the function. Try this:
%Define function to be integrated
f = #(x,y) y.^2.*cos(x);%changed to .^ and .*
%First case. Integration order: dydx
%ymin = #(x) cos(x);
I = integral2(f,-1,1,0,2*pi)%use scalar values for limits of integration
%Second case. Integration order: dxdy
%xmin = #(y) asin(y)+2*pi/2;
%xmax = #(y) asin(y)-pi/2;
B = integral2(f,0,2*pi,-1,1)% same issue, must use scalars

Matlab error error using - matrix dimensions must agree

I am trying to write a code for classification of data. I try to implement a sigmoid function and then I try to use that function in calculation the cost.I keep getting errors and I have a feeling that it is because of the sigmoid function.I would like the sigmoid function to return a vector.But it keeps returning a scalar.
function g = sigmoid(z)
%SIGMOID Compute sigmoid functoon
% J = SIGMOID(z) computes the sigmoid of z.
% You need to return the following variables correctly
g=zeros(size(z));
m=ones(size(z));
% ====================== YOUR CODE HERE ======================
% Instructions: Compute the sigmoid of each value of z (z can be a matrix,
% vector or scalar).
g=1/(m+exp(-z));
This is my cost function:
m = length(y); % number of training examples
% You need to return the following variables correctly
grad=(1/m)*((X*(sigmoid(X*theta)-y)));//this is the derivative in gradient descent
J=(1/m)*(-(transpose(y)*log(sigmoid((X*theta))))-(transpose(1-y)*log(sigmoid((X*theta)))));//this is the cost function
the dimension of X are 100,4; of theta are 4,1;y is 100,1.
THank you.
Errors:
Program paused. Press enter to continue.
sigmoid answer: 0.500000Error using -
Matrix dimensions must agree.
Error in costFunction (line 11)
grad=(1/m)*((X*(sigmoid(X*theta)-y)));
Error in ex2 (line 69)
[cost, grad] = costFunction(initial_theta, X, y);
Please replace g=1/(m+exp(-z)); with g=1./(m+exp(-z)); in your method sigmoid
z = [2,3,4;5,6,7] ;
%SIGMOID Compute sigmoid functoon
% J = SIGMOID(z) computes the sigmoid of z.
% You need to return the following variables correctly
g=zeros(size(z));
m=ones(size(z));
% ====================== YOUR CODE HERE ======================
% Instructions: Compute the sigmoid of each value of z (z can be a matrix,
% vector or scalar).
g=1./(m+exp(-z));