I have the following system, specified by the set of coefficients:
b = [1 2 3];
a = [1 .5 .25];
In the Z-Domain, such function will have the following transfer function:
H(Z) = Y(Z)/X(Z)
So the frequency response will be just the unit circle, where:
H(e^jw) = Y(e^jw)/X(e^jw)
Do I just substitute in the e^jw for 'Z' in my transfer function to obtain the frequency response of the system mathematically, on paper? Seems a bit ridiculous from my (a student's) point of view.
Have you tried freqz()? It returns the frequency response vector, h, and the corresponding angular frequency vector, w, for the digital filter with numerator and denominator polynomial coefficients stored in b and a, respectively.
In your case, simply follow the help:
[h,w]=freqz(b,a);
You do sub in e^jw for Z. This isn't ridiculous. Then you just sweep w from -pi to pi. Your freq response will be the absolute value of the result.
As Alessiox mentioned, freqz is the command you want to use in matlab.
I would indeed be as simple as substituting exp(j*w) in your transfer function. There are of course different ways to implement this with Matlab. For the purpose of illustration, I will be assuming bs are the coefficients of the x sequence and as are the coefficients of the y sequence, such that the b are in the numerator and the as are in the denominator:
A direct evaluation with Matlab could be done with:
b = [1 2 3];
a = [1 .5 .25];
N = 513; % number of points at which to evaluate the transfer function
w = linspace(0,2*pi,N);
num = 0;
for i=1:length(b)
num = num + b(i) * exp(-j*i*w);
end
den = 0;
for i=1:length(a)
den = den + a(i) * exp(-j*i*w);
end
H = num ./ den;
This would be equivalent to the following which makes use of the builtin polyval:
N = 513; % number of points at which to evaluate the transfer function
w = linspace(0,2*pi,N);
H = polyval(fliplr(b),exp(-j*w))./polyval(fliplr(a),exp(-j*w));
Also, this is really evaluating the transfer function at discrete equally spaced angular frequencies w = 2*pi*k/N which corresponds to the Discrete Fourier Transform (DFT). As such it could also be done with:
N = 512;
H = fft(b,N) ./ fft(a,N);
Incidentally this is what freqz does, so you could also get the same result with:
N = 512;
H = freqz(b,a,N,'whole');
Related
How to implement this equation
in Matlab,
where: A and B are mxm matrices.
for example:
A = [3.45 32.54 78.2; 8.4 33.1 4.66; 68.2 9.336 33.87 ]
B = [6.45 36.54 28.24; 85.4 323.1 74.66; 98.2 93.336 38.55 ]
my code:
f1 = #(A) (abs(A) ).^2;
f2 = #(B) (abs(B) ).^2;
Q = integral2( f1, 0, 1, 0, 1) * integral2(f2, 0, 1, 0, 1);
But when i run the code I got the error "Too many input arguments.".
What is the problem in the code?
After clarification of your question, let me change my post.
What you are after is numerical integration of a function that was already sampled on a fixed grid, and the function values are stored in matrices A and B that are two dimensional M by M. I suppose that you have the associated gridpoints as well, suppose they are denoted xc and yc. Then, if you have sufficiently fine sampling of a smooth function, the integral approaches:
xc = linspace(0,1,M);
yc = linspace(0,1,M);
Q = trapz(xc,trapz(yc, abs(A).^2)) * trapz(xc,trapz(yc, abs(B).^2 ));
To test that, I made a simple example that evaluates the surface of a circle, i.e.
so to do that with trapezoidal method with N samples for r and M samples for phi, we have,
r = 2; % Pick a value for r
M = 100; % Pick M samples for the angular coordinate from 0 to 2*pi
N = 101; % Pick N samples for the radial coordinate from 0 to r
phic = linspace(0,2*pi,M); % take M samples uniformly for example
rc = linspace(0,r,N); % take N samples uniformly for example
integrand = repmat(rc,M,1); % Make MxN matrix, phi along rows, r along columns
I = trapz(rc, trapz(phic, integrand));
So for the case r=2, it gives indeed 4*pi.
We are given a n x n data. Approximate the funxtion.
For example. If we are given 2(1,1), 3(1,2), 4(2,1), 5(2,2)
Then we have to interpolate the 2 D- ultinomial as $0*x*y+y+2*x-1$.
This problem can be formulated as a set of linear equations, which are trivial to solve using mldivide function.
Let me illustrate this using the example you included.
% from the given example
in = [...
1,1;
1,2;
2,1;
2,2];
out = [...
2;
3;
4;
5];
% compute the variable terms in the polynomial
x = in(:,1);
y = in(:,2);
xy = x .* y;
c = ones(size(out)); % constant
% compute the coefficients of the polynomial
p = [xy,y,x,c] \ out;
% result: [0; 1; 2; -1]
The statementp = [xy,y,x,c] \ out computes the optimal coefficients (least-square error) when the problem is overconstrained (i.e. no solution exists to exactly satisfy all equations). But if there are only as many equations as there are variables (like in this example, there are 4 equations due to 4 input-output pairs and there are 4 coefficients that need to be estimated), then the coefficients can be computed simply by p = inv([xy,y,x,c]) * out.
We were asked to define our own differential operators on MATLAB, and I did it following a series of steps, and then we should use the differential operators to solve a boundary value problem:
-y'' + 2y' - y = x, y(0) = y(1) =0
my code was as follows, it was used to compute this (first and second derivative)
h = 2;
x = 2:h:50;
y = x.^2 ;
n=length(x);
uppershift = 1;
U = diag(ones(n-abs(uppershift),1),uppershift);
lowershift = -1;
L= diag(ones(n-abs(lowershift),1),lowershift);
% the code above creates the upper and lower shift matrix
D = ((U-L))/(2*h); %first differential operator
D2 = (full (gallery('tridiag',n)))/ -(h^2); %second differential operator
d1= D*y.'
d2= ((D2)*y.')
then I changed it to this after posting it here and getting one response that encouraged the usage of Identity Matrix, however I still seem to be getting no where.
h = 2;
n=10;
uppershift = 1;
U = diag(ones(n-abs(uppershift),1),uppershift);
lowershift = -1;
L= diag(ones(n-abs(lowershift),1),lowershift);
D = ((U-L))/(2*h); %first differential operator
D2 = (full (gallery('tridiag',n)))/ -(h^2); %second differential operator
I= eye(n);
eqn=(-D2 + 2*D - I)*y == x
solve(eqn,y)
I am not sure how to proceed with this, like should I define y and x, or what exactly? I am clueless!
Because this is a numerical approximation to the solution of the ODE, you are seeking to find a numerical vector that is representative of the solution to this ODE from time x=0 to x=1. This means that your boundary conditions make it so that the solution is only valid between 0 and 1.
Also this is now the reverse problem. In the previous post we did together, you know what the input vector was, and doing a matrix-vector multiplication produced the output derivative operation on that input vector. Now, you are given the output of the derivative and you are now seeking what the original input was. This now involves solving a linear system of equations.
Essentially, your problem is now this:
YX = F
Y are the coefficients from the matrix derivative operators that you derived, which is a n x n matrix, X would be the solution to the ODE, which is a n x 1 vector and F would be the function you are associating the ODE with, also a n x 1 vector. In our case, that would be x. To find Y, you've pretty much done that already in your code. You simply take each matrix operator (first and second derivative) and you add them together with the proper signs and scales to respect the left-hand side of the ODE. BTW, your first derivative and second derivative matrices are correct. What's left is adding the -y term to the mix, and that is accomplished by -eye(n) as you have found out in your code.
Once you formulate your Y and F, you can use the mldivide or \ operator and solve for X and get the solution to this linear system via:
X = Y \ F;
The above essentially solves the linear system of equations formed by Y and F and will be stored in X.
The first thing you need to do is define a vector of points going from x=0 to x=1. linspace is probably the most suitable where you can specify how many points we want. Let's assume 100 points for now:
x = linspace(0,1,100);
Therefore, h in our case is just 1/100. In general, if you want to solve from the starting point x = a up to the end point x = b, the step size h is defined as h = (b - a)/n where n is the total number of points you want to solve for in the ODE.
Now, we have to include the boundary conditions. This simply means that we know the beginning and ending of the solution of the ODE. This means that y(0) = y(1) = 0. As such, we make sure that the first row of Y has only the first column set to 1 and the last row of Y has only the last column set to 1, and we'll set the output position in F to both be 0. This symbolizes that we already know the solution at these points.
Therefore, your final code to solve is just:
%// Setup
a = 0; b = 1; n = 100;
x = linspace(a,b,n);
h = (b-a)/n;
%// Your code
uppershift = 1;
U = diag(ones(n-abs(uppershift),1),uppershift);
lowershift = -1;
L= diag(ones(n-abs(lowershift),1),lowershift);
D = ((U-L))/(2*h); %first differential operator
D2 = (full (gallery('tridiag',n)))/ -(h^2);
%// New code - Create differential equation matrix
Y = (-D2 + 2*D - eye(n));
%// Set boundary conditions on system
Y(1,:) = 0; Y(1,1) = 1;
Y(end,:) = 0; Y(end,end) = 1;
%// New code - Create F vector and set boundary conditions
F = x.';
F(1) = 0; F(end) = 0;
%// Solve system
X = Y \ F;
X should now contain your numerical approximation to the ODE in steps of h = 1/100 starting from x=0 up to x=1.
Now let's see what this looks like:
figure;
plot(x, X);
title('Solution to ODE');
xlabel('x'); ylabel('y');
You can see that y(0) = y(1) = 0 as per the boundary conditions.
Hope this helps, and good luck!
I have to create the function G(z) = [3*H^2(z)-2H^3(z)]*(z^-2) which takes as an input the impulse response of the filter H(z) , and outputs the impulse response of G(z).
I assume H(z) is a generic FIR filter
b = fir1(10,0.5);
h = impz(b);
t = impzlength(b);
where h is the values of the impulse response.
I think H^2(z) = h(n).*z(-2n) and H^3(z) = h(n).*z^(-3n); H(z) is the transfer function of the filter .
I have to calculate the coefficients of num and den of the equation now, but I am stuck.
I thought at first to use coeffs and a for loop but i need also the zero coefficients, while coeffs only provides the non zero coefficients.
Now I thought that maybe there is a work-around for obtaining the coefficients: basically I have to select only certain values of h.
For example, to obtain the coefficients only for z^-3n:
n = 3;
y = h(n:n:end); % = 3 6 9 12 ...
But now I can't figure out how to sum appropriately the coefficients for z^-3n and z^-2n.
Unless you are using a non-standard notation, H^2(z) is not h(n).*z(-2n) but rather the multiplication of a polynomial with coefficients h with itself. This can be computed with:
H2 = conv(h, h);
Similarly, H^3(z) can be computed using:
H3 = conv(H2, h);
Then, summing the polynomials boils down to summing the coefficients, with the only catch that you have to pad H2 so that the two vectors of coefficients have the same size:
H2 = [H2 zeros(1,length(H3)-length(H2))];
S = 3*H2 -2*H3;
The final multiplication by z^(-2) (which can be represented by the polynomial coefficients [0 0 1]) could be achieve in the same way using conv with:
G = conv(S, [0 0 1 zeros(1,length(Sum)-3)]);
or alternatively, you may realize that multiplying by a single term polynomial is essentially equivalent to shifting the coefficients:
G = [0 0 S];
I have some obscurely long symbolic expression of 3 variables (g_eq), which i would like to minimize with some constraints. I am trying to do so by converting it to a function handle and using fmicon:
cfun = matlabFunction(g_eq,'vars',[kappa;theta;sigma]);
A = [-1 0 0; 0 -1 0; 0 0 -1];
b = [0; 0; 0];
[x,fval] = fmincon(#(kappa, theta, sigma) cfun, x0, A, b)
Which Matlab doesn't like:
FMINCON requires all values returned by user functions to be of
data type double.
I would suspect, that the problem is with cfun, as it is full of numbers with symbolic precision, can I somehow convert it, so that they're double? Or better (computation time wise) while creating my objective function (cfun) (complicated process of some transformation of data and a parametric model), can I use symbols or some other "proxy for the variables" with double for the numeric part of the expressions?
Thanks,
J.
Edit - MCVE:
My aim is to find parameters of a model by minimizing a difference between the model implied and data implied laplace transforms over some weighted regions. Here I provide the problem over one small region without use of weights over the regions and some further simplifications. In part 0, I provide the code for functions of the transformation, in part II I make the parametric transformation, while in III the data transformation and attempt to minimize it in IV.
%% 0. Functions used
%% 0.1 L_V1 - transform of parametric
function lv = L_V1(u,sigma,kappa,theta)
lv = (1/(1+u.*sigma^2/(2*kappa))).^(2*kappa*theta/sigma^2);
end
%% 0.2 LV_2 - transform of data
function lv = L_hat1(u,D,n,T)
A_u = cos(sqrt(2 .*u) *sqrt(n) .*D);
Z_u = 1/n * sum(A_u);
lv = 1/T * sum(Z_u);
end
%% I. Pre-estimation
ulng1=100; %select number of points on the evaluated interval
u1 = linspace(.8, 1.6,ulng1); % create region of interest
%% II. Parametric part
par_mat1 = sym(zeros(ulng1,1)); % create interval for parametric
syms sigma kappa theta LV_par1;
for i = 1:ulng1
par_mat1(i) = L_V1(u1(i),sigma,kappa,theta); %transformations of parametric
end
LV_par1 = sum(par_mat1); %sum of parametric over the region
%% III. Data part
n = 100; %choose number of days
T = 20; %choose number of obs over a day
D = rand([n-1, T]); %vector of observations, here just random numbers
for i = 1:ulng1
hat_mat1(i) = L_hat1(u1(i),D,n,T); %transformations of data
end
hat_1 = sum(hat_mat1); %sum of transforms over the region
%% IV. Minimize
W = 1; %weighting matrix, here just one region, hence 1
MC = hat_1 - LV_par1 ; %moment condition
g_eq = (MC) * (W) *(MC.'); %objective function (symbolic)
cfun = matlabFunction(g_eq,'vars',[kappa;theta;sigma]); %create a function handle from the symbolic
x0 = [.5; 1; .5];
A = [-1 0 0; 0 -1 0; 0 0 -1]; %constrains
b = [0; 0; 0]; %constrains
[x,fval] = fmincon(#(kappa, theta, sigma) cfun, x0, A, b) %minimize
The optimization parameters are always passed as vector.
[x,fval] = fmincon(#(x) cfun(x(1),x(2),x(3)), x0, A, b)