Rotating gaussian filter in matlab - matlab

I am trying to create and rotate gaussian filter in matlab. Here is my code:
function f = createGaussianArray(length, sigma, theta)
half = length/2;
[x,y] = meshgrid(-half:half, -half:half);
x2 = cos(theta)*(x)-sin(theta)*(y);
y2 = sin(theta)*(x)+cos(theta)*(x);
matrix = exp(- (x2.^2+y2.^2) / (2*sigma.^2));
f = matrix ./ sum(matrix(:));
end
When I call this function(function is in gauss.m file):
filter = gauss(31, 10, pi/2);
imagesc(filter)
It works well for pi/3, pi/6 vs. However when I send 3pi/4, 0, pi or 2*pi as an argument, It displays only a straight line. What is wrong with my code, I did not understand.

The rotation transform is:
x2 = cos(theta)*(x)-sin(theta)*(y);
y2 = sin(theta)*(x)+cos(theta)*(y); % last term is not cos(theta)*(x)

Related

Error plotting spherical harmonics in MATLAB: Grid arrays must have NDGRID structure

I am trying to use the spherical harmonics to represent a perturbation of a spherical object in an acoustic and fluid flow in 3D.
So far, I have been able to use a 2D perturbation on a 3D spherical object, however, I would like to extend that.
The current code represents a 3D sphere with a 2D perturbation, so the perturbation is only in x and y:
clearvars; clc; close all;
Nx = 128;
Ny = 128;
Nz = 128;
Lx =128;
Ly = 128;
Lz = 128;
xi = (0:Nx-1)/Nx*2*pi;
xi_x = 2*pi/Lx;
x = xi/xi_x;
yi = (0:Ny-1)/Ny*2*pi;
yi_y = 2*pi/Ly;
y = yi/yi_y;
zi = (0:Nz-1)/Nz*2*pi;
zi_z = 2*pi/Lz;
z = zi/zi_z;
[X,Y,Z] = meshgrid(x,y,z);
A = 2*pi / Lx;
B = 2*pi / Ly;
C = 2*pi / Lz;
x0 = 64;
y0 = 64;
z0 = 64;
rx0 = 20;
ry0 = 20;
rz0 = 20;
p = 3;
b = 0.1; % pert amplitude
c = 12;
d = 1;
a = 4;
theta = atan2(Y -y0, X-x0) - (pi/c);
p0 = ((X-x0) .* (X-x0)) /(rx0 * rx0) + ((Y-y0) .* (Y-y0))/(ry0 * ry0) + ((Z-z0) .* (Z-z0))/(rz0 * rz0);
Test =d + a * exp((-1. * p0 .* (1 - b .* cos(c * theta))).^p) ;
figure
isosurface(X,Y,Z,Test);
shading flat;
grid on;
Which returns the isosurface:
However, I would like to achieve something similar to this plot (perturbation in z as well):
This is my attempt using spherical harmonics to reproduce the above picture:
clearvars; clc; close all;
%in spherical coord
%calculate r
Nx = 128;
Ny = 128;
Nz = 128;
Lx =128;
Ly = 128;
Lz = 128;
xi = (0:Nx-1)/Nx*2*pi;
xi_x = 2*pi/Lx;
x = xi/xi_x;
yi = (0:Ny-1)/Ny*2*pi;
yi_y = 2*pi/Ly;
y = yi/yi_y;
zi = (0:Nz-1)/Nz*2*pi;
zi_z = 2*pi/Lz;
z = zi/zi_z;
r = sqrt(x.^2 + y.^2 + z.^2);
% Create the grid
delta = pi/127;
%Taking for instance l=1, m=-1 you can generate this harmonic on a (azimuth, elevation) grid like this:
azimuths = 0 : delta : pi;
elevations = 0 : 2*delta : 2*pi;
[R, A, E] = ndgrid(r, azimuths, elevations); %A is phi and E is theta
H = 0.25 * sqrt(3/(2*pi)) .* exp(-1j*A) .* sin(E) .* cos(E);
%transform the grid back to cartesian grid like this:
%can also add some radial distortion to make things look nicer:
%the radial part depends on your domain
X = r .* cos(A) .* sin(E);
Y = r .* sin(A) .* sin(E);
Z = r .* cos(E);
%parameters
x0 = 64;
y0 = 64;
z0 = 64;
rx0 = 20;
ry0 = 20;
rz0 = 20;
p = 3;
b = 0.1; % pert amplitude
%c = 12;
d = 1;
a = 4;
p0 = ((X-x0) .* (X-x0)) /(rx0 * rx0) + ((Y-y0) .* (Y-y0))/(ry0 * ry0) + ((Z-z0) .* (Z-z0))/(rz0 * rz0);
Test1 =d + a * exp((-1. * p0 .*H).^p) ;
figure
isosurface(X,Y,Z,real(Test1)); %ERROR
This gives me the following error:
Error using griddedInterpolant
Grid arrays must have NDGRID structure.
Is the issue in the way I am setting up the spherical harmonics? or the functional form of Test1?? Thanks
I think the problem is that you've created a NDGrid in the second code. In the first code that worked you created a meshgrid.
isosurface expects a grid in meshgrid format and transforms it later into an NDGrid format with permute just for the usage of the griddedInterpolant function. By the input of an NDGrid this operation will fail.
Why did you switch to creating a NDGrid? Did you get the same error when using meshgrid?
EDIT
OK, new theory: I think the problem is the grid itsself. Read the documentation on ndgrid for more information but for short: A NDGrid format is a completely rectangular grid where all nodes are exclusivly surrounded by 90° angles. By spanning up a grid with ndgrid(r, azimuths, elevations) or meshgrid(r, azimuths, elevations) you are getting this rectangular grid but of course this grid is meaningless because r, azimuths and elevations represent spherical coordinates. By later converting R, A and E into the carthesian coordinates X, Y and Z you get a propper spherical grid but the grid isn't a NDGrid structure anymore since it's not rectangular anymore.
So you have to find a workaround to calculate with your spherical grid.
Maybe you can use another function to visualize your data that dosn't take any grid format as input
Or maybe you can try working with a rectangular cartesian grid by setting all values outside the sphere to 0. (You have to refine your grid accordingly to achieve a good estimation of the sphere)

Plotting a Parametric Spline Curve Using a Periodic Spline

I want to plot a curve like this using a periodic spline:
I have the following values:
And so, I have created the following matlab code to plot this function:
%initializing values
t = [1,2,3,4,5,6,7,8,9,10,11,12,13];
tplot = [1:0.1:13];
x = [2.5,1.3,-0.25,0.0,0.25,-1.3,-2.5,-1.3,0.25,0.0,-0.25,1.3,2.5];
y = [0.0,-0.25,1.3,2.5,1.3,-0.25,0.0,0.25,-1.3,-2.5,-1.3,0.25,0.0];
[a1, b1, c1, d1] = perspline2(t,x);
[a2, b2, c2, d2] = perspline2(t,y);
for i = 1:12
xx = linspace(x(i), x(i+1), 100);
xxx = a1(i) + b1(i)*(xx-x(i)) + c1(i)*(xx-x(i)).^2 ...
+ d1(i)*(xx-x(i)).^3;
yyy = a2(i) + b2(i)*(xx-x(i)) + c2(i)*(xx-x(i)).^2 ...
+ d2(i)*(xx-x(i)).^3;
h3=plot(xxx, yyy, 'r-');
hold on
end
plot(x,y,'k.', 'MarkerSize', 30)
hold off
With perspline2() looking like this:
function [a1,b1,c1,d1] = perspline2(xnot,ynot)
x = xnot';
y = ynot';
n = length(x) - 1;
h = diff(x);
diag0 = [1; 2*(h(1:end-1)+h(2:end)); 2*h(end)];
A = spdiags([[h;0], diag0, [0;h]], [-1, 0, 1], n+1, n+1);
% Do a little surgery on the matrix:
A(1,2) = 0;
A(1,end) = -1;
A(end,1) = 2*h(1);
A(end,2) = h(1);
dy = diff(y);
rhs = 6*[0; diff(dy./h); dy(1)/h(1)-dy(end)/h(end)];
m = A \ rhs; % Solve for the slopes, S''(x_i)
% Compute the coefficients of the cubics.
a1 = y;
b1 = dy./h - h.*m(1:end-1)/2 - h.*diff(m)/6;
c1 = m/2;
d1 = diff(m)./h/6;
So basically, I know that I must use a parametric spline in order to find the correct points to plot.
I use t = [1,2,3,4,5,6,7,8,9,10,11,12,13]; as my indexes. So, I find the coefficients for the cubic spline polynomial of t vs. x and then find the coefficients for t vs. y, and then I attempt to plot them against each other using values from t in order to plot the parametric curve. However, I keep getting this curve:
I am really not sure why this is occurring.
P.S I know I can use the matlab spline function but when I do, it results in the right cusp being a bit bigger than the other cusps. I want all cusps to be equal in size and the assignment says that we must use a cubic spline.
Any help is greatly appreciated.

How to use surf to plot sphere function in matlab

I'm trying to plot sphere function below, But I'm getting wrong result
Here is the code I'm using
x1 = [-10:1:10];
x2 = [-10:1:10];
y = zeros(1,21);
for i = 1:21
y(i) = sphere([x1(i) x2(i)]);
end
Y = meshgrid(y);
surf(x1,x2,Y);
colormap hsv;
sphere.m
function [y] = sphere(x)
d = length(x);
sum = 0;
for i = 1:d
sum = sum + x(i)^2;
end
y = sum;
end
For the sake of completness your code is not working because you are only evaluating your function on the pairs (x,x) for some x \in [-10,10] so you don't cover the whole domain. It would work with this:
x1 = [-10:1:10];
x2 = [-10:1:10];
y = zeros(1,21);
for i = 1:21
for j=1:21
Y(i,j) = sphere([x1(i) x2(j)]);
end
end
surf(x1,x2,Y);
colormap hsv;
or way faster (because you should always avoid unnecessary loops for computation time reasons):
x1 = meshgrid([-10:1:10]);
x2 = x1';
Y = x1.^2+x2.^2;
surf(x1,x2,Y)
sphere(10)
It is a MatLab built in function.
Please enjoy responsibly.
If you need to see the source code use: edit sphere or help sphere when your sphere function is not on the path.

mesh gaussian after rotation matrix in matlab

I am trying to rotate the derivative of a gaussian (or the original guassian for that matter) by applying a rotation matrix to the X,Y coordinates and then plotting it as a mesh in matlab, but I'm running into an issue that the plot will only rotate by 90 degress each time and for all n*pi points there is no mesh appearing at all. I am wondering what I am doing wrong, hopefully someone can spot my error. I'm fairly new to matlab so forgive me if the code is not pretty. Thank you!
This is the code that I have:
sigma = 4;
[x,y] = deal(-3*sigma:.5:3*sigma);
[X,Y] = meshgrid(x,y);
B = [transpose(x) transpose(y)];
for i=1:1:16
figure(i);
theta = i*pi/8;
rotation = [cos(theta) sin(theta); -sin(theta) cos(theta)];
A = B * rotation;
[x_new, y_new] = meshgrid(A(:,1)', A(:,2)');
mesh(x_new, y_new, dgauss_x(x_new, y_new, sigma));
end
function f = dgauss_x(x, y, sigma)
%first order derivative of Gaussian
f = -x .* gaussian(x, y, sigma) ./ sigma^2;
function f = gaussian(x, y, sigma)
f = exp(-(x .^ 2 + y .^ 2)/(2*sigma^2)) / (sqrt(2*pi*(sigma^2)));
I figure it out. It was a dumb error. Basically I had to create a meshgrid for X and Y, reshape it into an Nx2 matrix of X and Y. Apply the rotation matrix, then reshape back and apply the Gaussian.
The code looks as follows (could be cleaned up):
for i=1:1:16
figure(i);
theta = i*pi/8;
rotation = [cos(theta) -sin(theta); sin(theta) cos(theta)];
X1 = reshape(X, length(x)*length(x), 1);
Y1 = reshape(Y, length(y)*length(y), 1);
B2 = [X1 Y1];
A = B2 * rotation;
X1 = A(:,1);
X1 = reshape(X1, length(x), length(x));
Y1 = A(:,2);
Y1 = reshape(Y1, length(y), length(y));
mesh(X1, Y1, dgauss_x(X1, Y1, sigma));
end

Inverse fast fourier transform in MATLAB

My MATLAB code for fft and ifft below has a problem with the inverse Fourier signal y not matching the in put signal x. Is there any solution to resolve this?
N = 1000;
t0 = 1e-13;
tau = 2*1e-14;
n = [0:t0/40:2*1e-13-t0/40];
f0 = 3*1e8/(150*1e-9);
x = cos(2*pi*f0*n);
x = x.*exp((-(n-t0).^2)./(tau^2));
X = abs(fft(x,N));
F = [-N/2 : N/2 - 1]/N;
X = fftshift(X);
y=ifft(X,80);
figure(3)
plot(n,y)
I see a number of issues here:
N = 1000;
t0 = 1e-13;
tau = 2*1e-14;
n = [0:t0/40:2*1e-13-t0/40];
f0 = 3*1e8/(150*1e-9);
x = cos(2*pi*f0*n);
x = x.*exp((-(n-t0).^2)./(tau^2));
% X = abs(fft(x,N)); <-- Not seen this technique before, and why N=1000?
% try something more like:
X = fft(x);
F = [-N/2 : N/2 - 1]/N;
% this is fine to shift and plot the function
Xshifted = fftshift(X);
plot( abs( Xshifted ) )
% now you're taking the inverse of the shifted function, not what you want
% y=ifft(X,80); also not sure about the 80
y = ifft(X);
figure(3)
plot(n,y)
figure(4)
plot( n, x ); hold on; plot( n, y, 'o' )
That's all I see at first. HTH!
If you take the absolute value of the fft, you destroy the phase information needed to reconstruct the original signal, i.e. the moment you compute
X = abs(fft(x,N));
You cannot go back via ifft, because now you only have the magnitude.
Also, the inverse transformation only works if you use the same number of FFT bins with NFFT>=length(x).
y=ifft(fft(x));
should be exactly the same as x.