Matlab numerical integration - matlab

I'm trying to integrate x using matlab, and that task is simple by using the following commands:
syms x
a=int(x)
The problem is I'm not sure how to implement numerical integration. I want to integrate x using a set amount of intervals using different techniques.
Can anyone help me with the syntax call for numerical integration? The MathWorks site isn't very helpful.
I also do know there is a method called traps, but I'm looking for other methods within matlab, like Riemann sum approximation.
Update
So specifically what I'm looking for is a function that will break x into 8 pieces of area and then add those 8 pieces together. Is there a predefined function other than trapz that does such a thing?
Okay, I think I've come to the conclusion that there is no such thing. You have to make your own.

For numerical integration you have a broad number of functions at your disposal:
trapz
quad
quadgk
integral
for uni-dimensional integration.
If, instead, you are interested in multi-dimensional integration techniques, you may think of making use of the following functions
dblquad
quad2d
integral2
integral3
EDIT
In your case, I would proceed this way:
x = 0:.1:2;
y = x;
trapz(x,y);
or
y = #(x) x;
quad(y,0,2);
EDIT 2
Give this a look:
clc,clear
s = 0:7;
y = #(x) x;
k = 1;
for ii = 1:numel(s)-1
f(k) = quad(y,s(k), s(k+1));
k = k + 1;
end
sum(f)

Related

Minimizing Function with vector valued input in MATLAB

I want to minimize a function like below:
Here, n can be 5,10,50 etc. I want to use Matlab and want to use Gradient Descent and Quasi-Newton Method with BFGS update to solve this problem along with backtracking line search. I am a novice in Matlab. Can anyone help, please? I can find a solution for a similar problem in that link: https://www.mathworks.com/help/optim/ug/unconstrained-nonlinear-optimization-algorithms.html .
But, I really don't know how to create a vector-valued function in Matlab (in my case input x can be an n-dimensional vector).
You will have to make quite a leap to get where you want to be -- may I suggest to go through some basic tutorial first in order to digest basic MATLAB syntax and concepts? Another useful read is the very basic example to unconstrained optimization in the documentation. However, the answer to your question touches only basic syntax, so we can go through it quickly nevertheless.
The absolute minimum to invoke the unconstraint nonlinear optimization algorithms of the Optimization Toolbox is the formulation of an objective function. That function is supposed to return the function value f of your function at any given point x, and in your case it reads
function f = objfun(x)
f = sum(100 * (x(2:end) - x(1:end-1).^2).^2 + (1 - x(1:end-1)).^2);
end
Notice that
we select the indiviual components of the x vector by matrix indexing, and that
the .^ notation effects that the operand is to be squared elementwise.
For simplicity, save this function to a file objfun.m in your current working directory, so that you have it available from the command window.
Now all you have to do is to call the appropriate optimization algorithm, say, the quasi Newton method, from the command window:
n = 10; % Use n variables
options = optimoptions(#fminunc,'Algorithm','quasi-newton'); % Use QM method
x0 = rand(n,1); % Random starting guess
[x,fval,exitflag] = fminunc(#objfun, x0, options); % Solve!
fprintf('Final objval=%.2e, exitflag=%d\n', fval, exitflag);
On my machine I see that the algorithm converges:
Local minimum found.
Optimization completed because the size of the gradient is less than
the default value of the optimality tolerance.
Final objval=5.57e-11, exitflag=1

Efficient Method in MATLAB for Producing a Numerical Solution to an Ordinary Differential Equation

I am attempting to write a MATLAB program that allows me to give it a differential equation and then ultimately produce a numerical solution.
In particular, I am looking to solve this equation:
The steps involved to create such a program would be, as I see it:
1st: Discretizing the domain of the ODE into n-intervals of equivalent length
2nd: Replace the differential operators write finite difference operators.
3rd: Somehow get MATLAB to construct a system of linear equations that approximates the ODE
4th: Solve the system of linear algebraic equations with MATLAB
5th: Plot the results.
And, on that conceptual level, that all makes sense to me. Attempting to carry out the steps using code is what is proving difficult.
Thus far, I have the program split into two parts. The first one is my attempt at graphing the function, while the second part attempts to perform the integration.
First Part:
function [y] = ODEs (n,a, b)
x= 0:(1/n):1;
A= zeros(n+1,n+1);
A(1,1)= -2;
A(1,2)= 1;
A(n+1, n+1)= -2;
A(n+1, n)=1;
for i= 2:n;
A(i,i)=-2;
A(i,i-1)=1;
A(i,i-1)=1;
end
for i=1:n+1;
b(i,1)=(x(1,i)).* (1/n);
end
y=inv(A)*b;
plot (x,y)
hold all
plot (x,(x(:).^3./6) +(b-a-(1/6)).*x(:) +a)
Second Part:
clear all;
clc;
prompt='How many times do you want to integrate the function y=x: ';
y = input(prompt);
syms ('x');
i = 1;
j = 1;
b = 1;
den_num = 1;
while i <= y
while j <= y
den_num = j*den_num;
j = j+1;
end
b = x.^y /den_num;
i = i+1;
end
pretty(b)
At this point, both parts are riddled with errors (the 2nd part doesn't even provide a graph like I would like), but hopefully what I'm attempting to do is clear. I'm not looking for a solution to all my problems to be handed to me: I know that would prove immense. However, it would be nice to know if I'm heading in the right direction? Or is there a more efficient way of going about things that I'm missing? Hopefully this all makes some sense.

How do I make the actual plot look like the correct plot?

The prompt is to develop a program to evaluate convolutions. This is to be done without using MATLAB's built in conv function. Therefore utilizing the Fourier transform, multiplying the two functions together and then inverse Fourier transforming the product. The transform is done by using direct integration. The trapz function is recommended form of integration to accomplish this goal.
I would appreciate ANY feedback on how to improve my code, please thoroughly explain what the improvements and link an reference as to how they work.
Given the code:
t = -5:.1:5;
w = pi;
X = zeros(101,1);
H = zeros(101,1);
Y = zeros(101,1);
y = zeros(101,1);
if t >= 0
x = 0;
h = 0;
else
x = exp((-3.*t)+(-1i*w.*t));
h = exp((-2*t)+(-1i*w.*t));
end
for k=2:101
X(k)=trapz(t(1:k),x(1:k));
H(k)=trapz(t(1:k),h(1:k));
Y = (X.*H)*exp(1i*w.*t);
y(k) = (1/(2*pi))*trapz(t(1:k),Y(1:k));
end
disp (length(x))
disp (length(X))
disp (length(Y))
disp (length(y))
disp (y)
figure(1);
subplot(1,2,1),plot(t,real(y));grid on;
As I do not have enough reputation to directly post images, the actual output and desired output are as follows:
The actual plot is this.
The desired plot is this.
My primary question is this: why is my plot not working?
Secondarily: What is unneeded in this code? What could make this code more efficient?
I won't do your entire homework, but I'll give you a few clues:
Skip the if t < 0 part, it doesn't work. For your exam, try to understand why. If you can't figure it out, come with your best guess and you might get an explanation =)
Try the following instead (no loops or ifs needed:
x = exp((-3.*t)+(-1i*pi.*t)).*(t>0);
And the same for h. Try to understand what .*(t<0) does in this context.
This one: Y = (X.*H)*exp(1i*w.*t); should be outside the loop. Why? Make a guess and you might get guidance if you're wrong.
Also Y is a 101x101 matrix. I guess you want it to be 101x1? You probably need to transform one of the vectors in the expression used to create Y. Before you do, you should figure out the difference between ' and .' (an important difference in this case).
You are using subplot, but only plotting one graph. If you want to graphs in the same plot, use hold on. If you want to plots beside each other, remember to plot the second one too.
And why use w = pi;, when you can just as well use pi in the equations?

vector valued limits in matlab integral

Is it possible to use vector limits for any matlab function of integration? I have to avoid from for loops because of the speed of my program. Can you please give me a clue on do
k=0:5
f=#(x)x^2
quad(f,k,k+1)
If somebody need, I found the answer of my question:quad with vector limit
I will try giving you an answer, based on my experience with quad function.
Starting from this:
k=0:5;
f=#(x) x.^2;
Notice the difference in your f definition (incorrect) and mine (correct).
If you only mean to integrate f within the range (0,5) you can easily call
quad(f,k(1),k(end))
Without handle function, you may reach the same results in a different way, by making use of trapz:
x = 0:5;
y = x.^2;
trapz(x,y)
If, instead, you mean to perform a step-by-step integration in the small range [k(i),k(i+1)] you may type
arrayfun(#(ii) quad(f,k(ii),k(ii+1)),1:numel(k)-1)
For a sake of convenince, notice that
sum(arrayfun(#(ii) quad(f,k(ii),k(ii+1)),1:numel(k)-1)) == quad(f,k(1),k(end))
I hope this helps.

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.