How to code frequency response of convolution kernel in matlab - matlab

given a convolution kernel computed from sigma using the function fspecial('gaussian',,)
how can I plot the frequency response in Matlab?
I would like to do this on a gaussian function, and importantly would like to derive the 1D frequency response (coz I understand them better) of the horizontal convolution kernel with size N.
Thanks for the help!!!

kernel2 = fspecial('gaussian', [1 5], 1.3)
spike = [1 0 0 0 0];
[h, w] = freqz(kernel2, spike, 1024);
m = abs(h)
p = angle(h);
plot(w,m);
hat tip to https://courseware.ee.calpoly.edu/~fdepiero/curr/dsp/dsp11.htm

Related

How to generate Conditional distribution from Gaussian Copula in Matlab?

Matlab has a built-in function to simulate from copulas: copularnd
I need to have a conditional Gaussian Copula.
I had a suggestion for Clayton Copula by another user:
Clayton Copula Sampling
for which the code is :
Can anybody by an example show, how the coding can be done, using GAUSSIAN Copula?
%% Simulations of Clayton copulas using conditional cdf
%Example for theta=4
n=3000;
theta=5;
u=rand(1,n);
y=rand(1,n);
v=((y.^(1/(1+theta)).*u).^(-theta)+1-u.^(-theta)).^(-1/theta);
x1=norminv(u);
x2=norminv(v);
plot(x1,x2,'.')
I just found this code:
%%Simulations of bivariate Gaussian copulas
%Example for rho=0.5
n=30000;
rho=0.5;
x1=norminv(rand(1,n));
x2=norminv(rand(1,n));
X = [x1; x2];
C = [1, rho; rho,1]; %2x2 Correlation matrix
cholesky = chol(C,'lower'); %lower triangular matrix of C using Cholesky decomposition
Copsims = cholesky*X;
c1 = Copsims(1,:);
c2 = Copsims(2,:);
plot(c1,c2,'.')
corrcoef(c1,c2) %check for empirical rho, not on point the initial rho because of sampling error

Matlab FFT2 normalization after processing

I am trying to understand how the MATLAB FFT normalization works.
Lets discuss the following example.
%%
sum2D = #(a) sum(reshape(a,1,[])); % sum elements in 2D matrix
a = [0 0 0; 1 2 1; 1 1 1; 1 1 1; 0 0 0]
f1 = fft2(a)
m = [0 32 0; 0 0 0; 0 1 0; 0 2 0; 0 0 0]
fs = m.*fftshift(f1);
fs = fs./sqrt(numel(fs));
fm = ifft2(fs);
fm = fm.*sqrt(numel(fm))
% imshow(abs(fs))
norm(a(:))^2,norm(fs(:))^2,norm(fm(:))^2
sum2D(abs(a).^2)
sum2D(abs(fs).^2)
sum2D(abs(fm).^2)
sum2D(abs(fp).^2)
If the m = 1, the normalization works and the energy is the same in the initial signal, fft and inverse fft. But if I multiply the signal after making fft by some vector m, then I don't know how to normalize this again.
Should the energy change after multiplying with the m, or I am doing something wrong.
Yes, multiplying the frequencies by matrix m changes the energy. You have amplified some frequencies and killed others: this may well make the signal stronger or weaker. As a simple example, suppose m had all entries equal to 2: then you double the signal, multiplying its energy by 4. For a general multiplier m, the effect on the energy will depend on what the signal is.
If you really want fm to have the same energy as a, just make it so:
fm = fm*norm(a(:))/norm(fm(:));
To directly answer "how FFT normalization works": applying fft2 multiplies the energy by the number of elements of the matrix. The function ifft2, being the inverse of fft2, divides the energy by the number of elements. So, if you are using ifft2 after fft2 and don't care about intermediate results such as fs, you don't need to do any division or multiplication by sqrt(numel(...)).

Computing coefficients of FIR filter in Matlab

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];

How to solve a system of equations involving a tridiagonal matrix? MATLAB

I'm not sure if this typical behaviour or not but I am solving a finite-difference problem using the backward differencing method.
I populated a sparse matrix with the appropriate diagonal terms (along the central diagonal and one above and below it) and I attempted to solve the problem using MATLAB's built-in method (B=A\x) and it seems MATLAB just gets it wrong.
Furthermore, if use inv() and use the inverse of the tridiagonal matrix I get the correct solution.
Why does this behave like this?
Additional info:
http://pastebin.com/AbuEW6CR (Values are tabbed so its easier read)
Stiffness matrix K:
1 0 0 0
-0.009 1.018 -0.009 0
0 -0.009 1.018 -0.009
0 0 0 1
Values for d:
0
15.55
15.55
86.73
Built-in output:
-1.78595556155136e-05
0.00196073713853244
0.00196073713853244
0.0108149483252210
Output using inv(K):
0
15.42
16.19
86.73
Manual output:
0
15.28
16.18
85.16
Code
nx = 21; %number of spatial steps
nt = 501; %number of time steps (varies between 501 and 4001)
p = alpha * dt / dx^2; %arbitrary constant
a = [0 -p*ones(1,nx-2) 0]'; %diagonal below central diagonal
b = (1+2*p)*ones(nx,1); %central diagonal
c = [1 -p*ones(1,nx-2) 1]'; %diagonal above central diagonal
d = zeros(nx, 1); %rhs values
% Variables a,b,c,d are used for the manual tridiagonal method for
% comparison with MATLAB's built-in functions. The variables represent
% diagonals and the rhs of the matrix
% The equation is K*U(n+1)=U(N)
U = zeros(nx,nt);
% Setting initial conditions
U(:,[1 2]) = (60-32)*5/9;
K = sparse(nx,nx);
% Indices of the sparse matrix which correspond to the diagonal
diagonal = 1:nx+1:nx*nx;
% Populating diagonals
K(diagonal) =1+2*p;
K(diagonal(2:end)-1) =-p;
K(diagonal(1:end-1)+1) =-p;
% Applying dirichlet condition at final spatial step, the temperature is
% derived from a table for predefined values during the calculation
K(end,end-1:end)=[0 1];
% Applying boundary conditions at first spatial step
K(1,1:2) = [1 0];
% Populating rhs values and applying boundary conditions, d=U(n)
d(ivec) = U(ivec,n);
d(nx) = R; %From table
d(1) = 0;
U(:,n+1) = tdm(a,b,c,d); % Manual solver, gives correct answer
U(:,n+1) = d\K; % Built-in solver, gives wrong answer
The following line:
U(:,n+1) = d\K;
should have been
U(:,n+1) = K\d;
By mistake I had them the wrong way round and didn't notice it, it obviously changes the mathematical expression and hence the wrong answers.

correlation of a 3d matrix with a vector in matlab

I have a KxLxM matrix A which is an image with a feature vector, length M, for each pixel location.
I have also have a feature vector v, length M. At each pixel location of image A i want to calculate the correlation of the pixel's feature vector with my feature vector v.
I've already done this using a loop, but loops are slow in matlab. Does anyone have a suggestion of how to vectorize this?
function test()
A = rand(4,5,3);
v = [1 2 3];
c = somecorr(A, v);
size(c)
function c = somecorr(a,v)
c = a(:,:,1).*0;
for y = 1:size(a,1)
for x = 1:size(a,2)
c(y,x) = corr2(squeeze(a(y,x,1:length(v)))',v);
end
end
>>test()
ans =
4 5
You could try this and see, if its faster:
function c = somecorr2(a,v)
as = reshape(a,size(a,1)*size(a,2),size(a,3));
cs = corr(as',v');
c = reshape(cs,size(a,1),size(a,2));
size(c)
I only did some small tests, but it seems to be more than 100x faster. At least for my test cases.
If you do not have the 'corr' function you can use this on, inspired by this [answer](
What is a fast way to compute column by column correlation in matlab):
function C = manualCorr(A,B)
An=bsxfun(#minus,A,mean(A,1)); %%% zero-mean
Bn=bsxfun(#minus,B,mean(B,1)); %%% zero-mean
An=bsxfun(#times,An,1./sqrt(sum(An.^2,1))); %% L2-normalization
Bn=bsxfun(#times,Bn,1./sqrt(sum(Bn.^2,1))); %% L2-normalization
C=sum(An.*repmat(Bn,1,size(An,2)),1); %% correlation
For a 100x100x3 matrix I get the following runtimes:
Your version: 1.643065 seconds.
mine with 'corr': 0.007191 seconds.
mine with 'manualCorr': 0.006206 seconds.
I was using Matlab R2012a.