How to calculate the convolution of a function with itself in MATLAB and WolframAlpha? - matlab

I am trying to calculate the convolution of
x(t) = 1, -1<=t<=1
x(t) = 0, outside
with itself using the definition.
http://en.wikipedia.org/wiki/Convolution
I know how to do using the Matlab function conv, but I want to use the integral definition. My knowledge of Matlab and WolframAlpha is very limited.

I am still learning Mathematica myself, but here is what I came up with..
First we define the piecewise function (I am using the example from the Wikipedia page)
f[x_] := Piecewise[{{1, -0.5 <= x <= 0.5}}, 0]
Lets plot the function:
Plot[f[x], {x, -2, 2}, PlotStyle -> Thick, Exclusions -> None]
Then we write the function that defines the convolution of f with itself:
g[t_] = Integrate[f[x]*f[t - x], {x, -Infinity, Infinity}]
and the plot:
Plot[g[t], {t, -2, 2}, PlotStyle -> Thick]
EDIT
I tried to do the same in MATLAB/MuPad, I wasn't as successful:
f := x -> piecewise([x < -0.5 or x > 0.5, 0], [x >= -0.5 and x <= 0.5, 1])
plot(f, x = -2..2)
However when I try to compute the integral, it took almost a minute to return this:
g := t -> int(f(x)*f(t-x), x = -infinity..infinity)
the plot (also took too long)
plot(g, t = -2..2)
Note the same could have been done from inside MATLAB with the syntax:
evalin(symengine,'<MUPAD EXPRESSIONS HERE>')

Mathematica actually has a convolve function. The documentation on it has a number of different examples:
http://reference.wolfram.com/mathematica/ref/Convolve.html?q=Convolve&lang=en

I don't know much about Mathematica so I can only help you (partially) about the Matlab part.
To do the convolution with the Matlab conv functions means you do it numerically. What you mean with the integral definition is that you want to do it symbolically. For this you need the Matlab Symbolic Toolbox. This is essentially a Maple plugin for Matlab. So what you want to know is how it works in Maple.
You might find this link useful (wikibooks) for an introduction on the MuPad in Matlab.
I tried to implement your box function as a function in Matlab as
t = sym('t')
f = (t > -1) + (t < 1) - 1
However this does not work when t is ob symbolic type Function 'gt' is not implemented for MuPAD symbolic objects.
You could declare f it as a piecewise function see (matlab online help), this did not work in my Matlab though. The examples are all Maple syntax, so they would work in Maple straight away.
To circumvent this, I used
t = sym('t')
s = sym('s')
f = #(t) heaviside(t + 1) - heaviside(t - 1)
Unfortunately this is not successful
I = int(f(s)*f(t-s),s, 0, t)
gives
Warning: Explicit integral could not be found.
and does not provide an explicit result. You can still evaluate this expression, e.g.
>> subs(I, t, 1.5)
ans =
1/2
But Matlab/MuPad failed to give you and explicit expression in terms of t. This is not really unexpected as the function f is discontinuous. This is not so easy for symbolic computations.
Now I would go and help the computer, fortunately for the example that you asked the answer is very easy. The convolution in your example is simply the int_0^t BoxFunction(s) * BoxFunction(t - s) ds. The integrant BoxFunction(s) * BoxFunction(t - s) is again a box function, just not one that goes from [-1,1] but to a smaller interval (that depends on t). Then you only need to integrate the function f(x)=1 over this smaller interval.
Some of those steps you would have to to by hand first, then you could try to re-enter them to Matlab. You don't even need a computer algebra program at all to get to the answer.
Maybe Matematica or Maple could actually solve this problem, remember that the MuPad shipped with Matlab is only a stripped down version of Maple. Maybe the above might still help you, it should give you the idea how things work together. Try to put in a nicer function for f, e.g. a polynomial and you should get it working.

Related

Numeric solution to ODE with square-rooted coefficient

I'm trying to use MATLAB's ODE23 to solve the following equation:
u"(t) = -u'(t) - u(t)^0.5
I've created an auxiliary file for a function I simply called myfun2 as such:
function F2 = myfun2(t,x)
F2 = [-x(1) - power(x(2),0.5); x(1)];
Then I am calling ODE23 as:
[t,x] = ode23(#myfun2, [0:0.1:(7*pi())], [0, 1/0.6671])
The problem is that the solver is outputting a bunch of imaginary values for both t and u which doesn't make sense for u and absolutely none for t since t is supposed to be defined in a 0 to 7PI range at steps of 0.1, as far as I understand...

Numerical integration of symbolic differentiation - MATLAB

The following is a MATLAB problem.
Suppose I define an function f(x,y).
I want to calculate the partial derivative of f with respect to y, evaluated at a specific value of y, e.g., y=6. Finally, I want to integrate this new function (which is only a function of x) over a range of x.
As an example, this is what I have tried
syms x y;
f = #(x, y) x.*y.^2;
Df = subs(diff(f,y),y,2);
Int = integral(Df , 0 , 1),
but I get the following error.
Error using integral (line 82)
First input argument must be a function
handle.
Can anyone help me in writing this code?
To solve the problem, matlabFunction was required. The solution looks like this:
syms x y
f = #(x, y) x.*y.^2;
Df = matlabFunction(subs(diff(f,y),y,2));
Int = integral(Df , 0 , 1);
Keeping it all symbolic, using sym/int:
syms x y;
f = #(x, y) x.*y.^2;
Df = diff(f,y);
s = int(Df,x,0,1)
which returns y. You can substitute 2 in for y here or earlier as you did in your question. Not that this will give you an exact answer in this case with no floating-point error, as opposed to integral which calculated the integral numerically.
When Googling for functions in Matlab, make sure to pay attention what toolbox they are in and what classes (datatypes) they support for their arguments. In some cases there are overloaded versions with the same name, but in others, you may need to look around for a different method (or devise your own).

Integration of a system of differential equations MATLAB

I am a fairly new Matlab user which I had to explore to numerically integrate a system of differential equations. Now I am trying to resolve a simple equation but which gives me a "lambertw" output.
(s - 1) * exp(-s) = k
Therefore, for a given k, with k < exp(2) I should get approximately two different values of "s". Here is the bit of code I use for this task (using symbolic toolbox):
%%Hopf bifurcation calculations
syms s
solve((s-1) * exp(-s) == k, s)
%uhopf = s*k
And the output:
1 - lambertw(0, -(3*exp(1))/25)
After looking at some examples I tried to get an explicit solution with no success:
syms x
x=solve('(s-1)*exp(-s) == k')
Finally, my question is how do I change the result given in the first place into a simple numerical value that fir a given k would give me s1 and s2. Any hint or help would be much appreciated ! I am still looking at some other examples.
If I understand your question correctly, you can use the eval() function to evaluate the string to retrieve a simple numerical example.
e.g.
char s;
char k;
A=solve('(s-1) * exp(-s) = k', 'k=exp(1)');
sol_s=A.s(1);
sol_k=A.k(1);
ans=eval(sol_s)

How to vectorize a function for integral2?

I want to evaluate a double integral of the form
$$\int_{-\infty}^a \int_{-\infty}^b \sum_{i,j}^K a_ia_jx^iy^j\exp(-x^2 - y^2 + xy)dx dy $$
where $a_i$ and $a_j$ are constants. Since the integral is linear, I can interchange summation and integration, but in this case I have to evaluate $K^2$ integrals and it takes too long. In that case I do the following:
for i = 1:K
for j = 1:K
fun = #(x,y) x.^i.*y.^j.*exp(-2.*(x.^2 + y.^2 - 2.*x.*y))
part(i,j) = alpha(i)*alpha(j)*integral2(fun,-inf,a,-inf,b)
end
end
It takes too long, so I want to evaluate only one integral, but I don't know how to vectorize $\sum_{i,j}^K a_ia_jx^iy^j\exp(-x^2 - y^2 + xy)$, namely, how to supply it to integral2. I would be very grateful for any help.
It looks like you'll need to have i and j be third and fourth dimensions, in order for there to be a chance that the code will work.
I also don't have integral2 (I use octave, integral2 is a new matlab function that octave doesn't yet have), so I can't test it, but I'd think something like this might work:
alphaset=zeros(1,1,K,K);
alphaset(1,1,1:K,1:K)=alpha(1:K)'*alpha(1:K);
i_set=zeros(1,1,K,1);
j_set=zeros(1,1,1,K);
i_set(:)=1:K;
j_set(:)=1:K;
fun=#(x,y) x.^i_set.*y.^j_set.*exp(-2.*(x.^2 + y.^2 - 2.*x.*y));
part = squeeze(alphaset.*integral2(fun,-inf,a,-inf,b));
As I said, I can't promise that it'll work, because I don't know how integral2 works. But if you replace the integral2 with simply "sum(sum(fun([1,2,4],[3,-1,2])))", then it works as intended for that operation (that is, it sums over the x and y values, and the result is a matrix over the set of indices).
If you just want to improve speed, you may try parfor.
Let $X=(x,x^2,\cdots,x^K)$, $Y=(y,y^2,\cdots,y^K)$, $A=(a_{ij})$ be a matrix with $a_{ij}=a_{i}a_{j}$, then
$$\sum_{i,j}^K a_{i}a_{j}x^iy^j=XAY^{T}$$
I don't have integral2 function on my matlab, so I didn't test if it will improve the speed a lot.
Also, I think you need to use syms x and y, after you compute the $$XAY^{T}$$, then use matlabFunction to convert symbolic expression to function handle. Here it is my test code: syms x y; X=[x,x^2]; Y=[y,y^2]; Z=X*Y'; fun =matlabFunction(Z); ff=#(x,y) x^2+y^2; gg=fun(x,y).*ff(x,y);

How do I make a function from a symbolic expression in MATLAB?

How can I make a function from a symbolic expression? For example, I have the following:
syms beta
n1,n2,m,aa= Constants
u = sqrt(n2-beta^2);
w = sqrt(beta^2-n1);
a = tan(u)/w+tanh(w)/u;
b = tanh(u)/w;
f = (a+b)*cos(aa*u+m*pi)+a-b*sin(aa*u+m*pi); %# The main expression
If I want to use f in a special program to find its zeroes, how can I convert f to a function? Or, what should I do to find the zeroes of f and such nested expressions?
You have a couple of options...
Option #1: Automatically generate a function
If you have version 4.9 (R2007b+) or later of the Symbolic Toolbox you can convert a symbolic expression to an anonymous function or a function M-file using the matlabFunction function. An example from the documentation:
>> syms x y
>> r = sqrt(x^2 + y^2);
>> ht = matlabFunction(sin(r)/r)
ht =
#(x,y)sin(sqrt(x.^2+y.^2)).*1./sqrt(x.^2+y.^2)
Option #2: Generate a function by hand
Since you've already written a set of symbolic equations, you can simply cut and paste part of that code into a function. Here's what your above example would look like:
function output = f(beta,n1,n2,m,aa)
u = sqrt(n2-beta.^2);
w = sqrt(beta.^2-n1);
a = tan(u)./w+tanh(w)./u;
b = tanh(u)./w;
output = (a+b).*cos(aa.*u+m.*pi)+(a-b).*sin(aa.*u+m.*pi);
end
When calling this function f you have to input the values of beta and the 4 constants and it will return the result of evaluating your main expression.
NOTE: Since you also mentioned wanting to find zeroes of f, you could try using the SOLVE function on your symbolic equation:
zeroValues = solve(f,'beta');
Someone has tagged this question with Matlab so I'll assume that you are concerned with solving the equation with Matlab. If you have a copy of the Matlab Symbolic toolbox you should be able to solve it directly as a previous respondent has suggested.
If not, then I suggest you write a Matlab m-file to evaluate your function f(). The pseudo-code you're already written will translate almost directly into lines of Matlab. As I read it your function f() is a function only of the variable beta since you indicate that n1,n2,m and a are all constants. I suggest that you plot the values of f(beta) for a range of values. The graph will indicate where the 0s of the function are and you can easily code up a bisection or similar algorithm to give you their values to your desired degree of accuracy.
If you broad intention is to have numeric values of certain symbolic expressions you have, for example, you have a larger program that generates symbolic expressions and you want to use these expression for numeric purposes, you can simply evaluate them using 'eval'. If their parameters have numeric values in the workspace, just use eval on your expression. For example,
syms beta
%n1,n2,m,aa= Constants
% values to exemplify
n1 = 1; n2 = 3; m = 1; aa = 5;
u = sqrt(n2-beta^2);
w = sqrt(beta^2-n1);
a = tan(u)/w+tanh(w)/u;
b = tanh(u)/w;
f = (a+b)*cos(aa*u+m*pi)+a-b*sin(aa*u+m*pi); %# The main expression
If beta has a value
beta = 1.5;
eval(beta)
This will calculate the value of f for a particular beta. Using it as a function. This solution will suit you in the scenario of using automatically generated symbolic expressions and will be interesting for fast testing with them. If you are writing a program to find zeros, it will be enough using eval(f) when you have to evaluate the function. When using a Matlab function to find zeros using anonymous function will be better, but you can also wrap the eval(f) inside a m-file.
If you're interested with just the answer for this specific equation, Try Wolfram Alpha, which will give you answers like:
alt text http://www4c.wolframalpha.com/Calculate/MSP/MSP642199013hbefb463a9000051gi6f4heeebfa7f?MSPStoreType=image/gif&s=15
If you want to solve this type of equation programatically, you probably need to use some software packages for symbolic algebra, like SymPy for python.
quoting the official documentation:
>>> from sympy import I, solve
>>> from sympy.abc import x, y
Solve a polynomial equation:
>>> solve(x**4-1, x)
[1, -1, -I, I]
Solve a linear system:
>>> solve((x+5*y-2, -3*x+6*y-15), x, y)
{x: -3, y: 1}