Rotating complex matrix with arbitrary angle in Matlab? - matlab

I have implemented the Hermite-Gaussian function in matlab for producing different modes. The light beam along z direction can be seen as a complex matrix in the plane.
The function for HG modes is as below.
%Hermite polynomial
function hk = HermitePoly(n)
if n==0
hk = 1;
elseif n==1
hk = [2 0];
else
hkm2 = zeros(1,n+1);
hkm2(n+1) = 1;
hkm1 = zeros(1,n+1);
hkm1(n) = 2;
for k=2:n
hk = zeros(1,n+1);
for e=n-k+1:2:n
hk(e) = 2*(hkm1(e+1) - (k-1)*hkm2(e));
end
hk(n+1) = -2*(k-1)*hkm2(n+1);
if k<n
hkm2 = hkm1;
hkm1 = hk;
end
end
end
% this is the function of HG modes in z position.
function [HGBeam,X,Y] = Hermite_Gaussian(N,hx,hy,w0,delta,lamda,z)
[X Y]=meshgrid((-N/2:N/2-1)*delta);
[theta,rad] = cart2pol(X,Y);
k=2*pi/lamda;
zr=pi*w0^2/lamda;
wz=w0*sqrt(1+(z/zr)^2);
qz=z+1i*zr;
q0=1i*zr;
if z==0
rz=Inf;
else
rz=z*(1+(zr/z)^2);
end
AmpLGB=sqrt(2/(2^(hx+hy)*pi*factorial(hx)*factorial(hy)*w0^2)).*(q0/qz).*(-conj(qz)/qz)^((hx+hy)/2).*exp(-(rad.*rad)/(wz)^2).*polyval(HermitePoly(hx),sqrt(2)*X/wz).*polyval(HermitePoly(hy),sqrt(2)*Y/wz);
PsLGB=exp(-1i*(k*(rad.*rad)/(2*rz)+k*z-(hx+hy+1)*atan(z/zr)));
HGBeam=AmpLGB.*PsLGB;
end
Now I plot one example for HG(2,0) as the following (example1):
clc
clear all;
close all;
lambda=809e-9; % optical wavelength
w0=0.025; %optical beam waist 15mm
k=2*pi/lambda; % optical wavenumber
Zr=pi*w0^2/lambda; % Rayleigh range
z0=0; % start position z=0; but careful 0*Inf is undefined, here 0*Inf=NAN
N=1024; % samples/side length at source plane
D1=0.25; % side length [m] at source plane
delta1=D1/N; % grid spacing [m]
x1=-D1/2:delta1:D1/2-delta1; % source plane x and y coordinates
y1=x1;
%% HG modes
HGx=2;
HGy=0;
HGintheory=Hermite_Gaussian(N,HGx,HGy,w0,delta1,lambda,z0);
h7=figure(7);
imagesc(x1,y1,abs(HGintheory).^2);
title(sprintf('z=%d; HG(%d,%d)',z0,HGx,HGy))
xlabel('x (m)'); ylabel('y (m)');
The plot of the light field will be as the following picture in the left side (its intensity):
We can use rot90() function to rotate matrix HGintheory (which is add one line code: HGintheory=rot90(HGintheory);) and then the field will rotate 90 degree (right side of the intensity plot).
Because I want to work with the light field. So the question is how can I rotate the complex matrix HGintheory in
arbitrary angle? For example 45 degree?
Does anyone knows how to rotate a complex matrix with big size? If something is wrong or unclear, please pointing out and Thank you in advance!

You can decompose your complex field into two real fields (amplitude and phase), rotate both with imrotate, and combine them afterwards pixel-wise
Hamp=abs(HGintheory);
Hphase=angle(HGintheory);
RotAngle=45;
HampRot=imrotate(Hamp,RotAngle,'bilinear','crop');
HphaseRot=imrotate(Hphase,RotAngle,'bilinear','crop');
HfullRot=HampRot.*exp(1i*HphaseRot);
figure(1);
imagesc(x1,y1,abs(HGintheory).^2);
figure(2);
imagesc(x1,y1,abs(HfullRot).^2);

You can rotate your initial meshgrid using:
[X,Y] = meshgrid(x1,y1)
xyc = [mean(x1), mean(y1)];
angel = 45;
R = [cosd(angel), -sind(angel); sind(angel), cosd(angel)];
XY = xyc' + R * ([X(:) Y(:)]-xyc)';
XR = reshape(XY(1,:),size(X));
YR = reshape(XY(2,:),size(Y));
and then use those transformed coordinates to plot:
imagesc(XR,YR,IntensityHGin);

Related

Matlab: patch area between two curves which depend on the curves values

I'm trying to fill an area between two curves with respect to a function which depends on the values of the curves.
Here is the code of what I've managed to do so far
i=50;
cc = #(xx,x,y) 1./(1+(exp(-xx)/(exp(-x)-exp(-y))));
n_vec = 2:0.1:10;
x_vec = linspace(2,10,length(n_vec));
y_vec = abs(sin(n_vec));
N=[n_vec,fliplr(n_vec)];
X=[x_vec,fliplr(y_vec)];
figure(1)
subplot(2,1,1)
hold on
plot(n_vec,x_vec,n_vec,y_vec)
hp = patch(N,X,'b')
plot([n_vec(i) n_vec(i)],[x_vec(i),y_vec(i)],'linewidth',5)
xlabel('n'); ylabel('x')
subplot(2,1,2)
xx = linspace(y_vec(i),x_vec(i),100);
plot(xx,cc(xx,y_vec(i),x_vec(i)))
xlabel('x'); ylabel('c(x)')
This code produces the following graph
The color code which I've added represent the color coding that each line (along the y axis at a point on the x axis) from the area between the two curves should be.
Overall, the entire area should be filled with a gradient color which depends on the values of the curves.
I've assisted the following previous questions but could not resolve a solution
MATLAB fill area between lines
Patch circle by a color gradient
Filling between two curves, according to a colormap given by a function MATLAB
NOTE: there is no importance to the functional form of the curves, I would prefer an answer which refers to two general arrays which consist the curves.
The surf plot method
The same as the scatter plot method, i.e. generate a point grid.
y = [x_vec(:); y_vec(:)];
resolution = [500,500];
px = linspace(min(n_vec), max(n_vec), resolution(1));
py = linspace(min(y), max(y), resolution(2));
[px, py] = meshgrid(px, py);
Generate a logical array indicating whether the points are inside the polygon, but no need to extract the points:
in = inpolygon(px, py, N, X);
Generate Z. The value of Z indicates the color to use for the surface plot. Hence, it is generated using the your function cc.
pz = 1./(1+(exp(-py_)/(exp(-y_vec(i))-exp(-x_vec(i)))));
pz = repmat(pz',1,resolution(2));
Set Z values for points outside the area of interest to NaN so MATLAB won't plot them.
pz(~in) = nan;
Generate a bounded colourmap (delete if you want to use full colour range)
% generate colormap
c = jet(100);
[s,l] = bounds(pz,'all');
s = round(s*100);
l = round(l*100);
if s ~= 0
c(1:s,:) = [];
end
if l ~= 100
c(l:100,:) = [];
end
Finally, plot.
figure;
colormap(jet)
surf(px,py,pz,'edgecolor','none');
view(2) % x-y view
Feel free to turn the image arround to see how it looks like in the Z-dimention - beautiful :)
Full code to test:
i=50;
cc = #(xx,x,y) 1./(1+(exp(-xx)/(exp(-x)-exp(-y))));
n_vec = 2:0.1:10;
x_vec = linspace(2,10,length(n_vec));
y_vec = abs(sin(n_vec));
% generate grid
y = [x_vec(:); y_vec(:)];
resolution = [500,500];
px_ = linspace(min(n_vec), max(n_vec), resolution(1));
py_ = linspace(min(y), max(y), resolution(2));
[px, py] = meshgrid(px_, py_);
% extract points
in = inpolygon(px, py, N, X);
% generate z
pz = 1./(1+(exp(-py_)/(exp(-y_vec(i))-exp(-x_vec(i)))));
pz = repmat(pz',1,resolution(2));
pz(~in) = nan;
% generate colormap
c = jet(100);
[s,l] = bounds(pz,'all');
s = round(s*100);
l = round(l*100);
if s ~= 0
c(1:s,:) = [];
end
if l ~= 100
c(l:100,:) = [];
end
% plot
figure;
colormap(c)
surf(px,py,pz,'edgecolor','none');
view(2)
You can use imagesc and meshgrids. See comments in the code to understand what's going on.
Downsample your data
% your initial upper and lower boundaries
n_vec_long = linspace(2,10,1000000);
f_ub_vec_long = linspace(2, 10, length(n_vec_long));
f_lb_vec_long = abs(sin(n_vec_long));
% downsample
n_vec = linspace(n_vec_long(1), n_vec_long(end), 1000); % for example, only 1000 points
% get upper and lower boundary values for n_vec
f_ub_vec = interp1(n_vec_long, f_ub_vec_long, n_vec);
f_lb_vec = interp1(n_vec_long, f_lb_vec_long, n_vec);
% x_vec for the color function
x_vec = 0:0.01:10;
Plot the data
% create a 2D matrix with N and X position
[N, X] = meshgrid(n_vec, x_vec);
% evaluate the upper and lower boundary functions at n_vec
% can be any function at n you want (not tested for crossing boundaries though...)
f_ub_vec = linspace(2, 10, length(n_vec));
f_lb_vec = abs(sin(n_vec));
% make these row vectors into matrices, to create a boolean mask
F_UB = repmat(f_ub_vec, [size(N, 1) 1]);
F_LB = repmat(f_lb_vec, [size(N, 1) 1]);
% create a mask based on the upper and lower boundary functions
mask = true(size(N));
mask(X > F_UB | X < F_LB) = false;
% create data matrix
Z = NaN(size(N));
% create function that evaluates the color profile for each defined value
% in the vectors with the lower and upper bounds
zc = #(X, ub, lb) 1 ./ (1 + (exp(-X) ./ (exp(-ub) - exp(-lb))));
CData = zc(X, f_lb_vec, f_ub_vec); % create the c(x) at all X
% put the CData in Z, but only between the lower and upper bound.
Z(mask) = CData(mask);
% normalize Z along 1st dim
Z = normalize(Z, 1, 'range'); % get all values between 0 and 1 for colorbar
% draw a figure!
figure(1); clf;
ax = axes; % create some axes
sc = imagesc(ax, n_vec, x_vec, Z); % plot the data
ax.YDir = 'normal' % set the YDir to normal again, imagesc reverses it by default;
xlabel('n')
ylabel('x')
This already looks kinda like what you want, but let's get rid of the blue area outside the boundaries. This can be done by creating an 'alpha mask', i.e. set the alpha value for all pixels outside the previously defined mask to 0:
figure(2); clf;
ax = axes; % create some axes
hold on;
sc = imagesc(ax, n_vec, x_vec, Z); % plot the data
ax.YDir = 'normal' % set the YDir to normal again, imagesc reverses it by default;
% set a colormap
colormap(flip(hsv(100)))
% set alpha for points outside mask
Calpha = ones(size(N));
Calpha(~mask) = 0;
sc.AlphaData = Calpha;
% plot the other lines
plot(n_vec, f_ub_vec, 'k', n_vec, f_lb_vec, 'k' ,'linewidth', 1)
% set axis limits
xlim([min(n_vec), max(n_vec)])
ylim([min(x_vec), max(x_vec)])
there is no importance to the functional form of the curves, I would prefer an answer which refers to two general arrays which consist the curves.
It is difficult to achieve this using patch.
However, you may use scatter plots to "fill" the area with coloured dots. Alternatively, and probably better, use surf plot and generate z coordinates using your cc function (See my seperate solution).
The scatter plot method
First, make a grid of points (resolution 500*500) inside the rectangular space bounding the two curves.
y = [x_vec(:); y_vec(:)];
resolution = [500,500];
px = linspace(min(n_vec), max(n_vec), resolution(1));
py = linspace(min(y), max(y), resolution(2));
[px, py] = meshgrid(px, py);
figure;
scatter(px(:), py(:), 1, 'r');
The not-interesting figure of the point grid:
Next, extract the points inside the polygon defined by the two curves.
in = inpolygon(px, py, N, X);
px = px(in);
py = py(in);
hold on;
scatter(px, py, 1, 'k');
Black points are inside the area:
Finally, create color and plot the nice looking gradient colour figure.
% create color for the points
cid = 1./(1+(exp(-py)/(exp(-y_vec(i))-exp(-x_vec(i)))));
c = jet(101);
c = c(round(cid*100)+1,:); % +1 to avoid zero indexing
% plot
figure;
scatter(px,py,16,c,'filled','s'); % use size 16, filled square markers.
Note that you may need a fairly dense grid of points to make sure the white background won't show up. You may also change the point size to a bigger value (won't impact performance).
Of cause, you may use patch to replace scatter but you will need to work out the vertices and face ids, then you may patch each faces separately with patch('Faces',F,'Vertices',V). Using patch this way may impact performance.
Complete code to test:
i=50;
cc = #(xx,x,y) 1./(1+(exp(-xx)/(exp(-x)-exp(-y))));
n_vec = 2:0.1:10;
x_vec = linspace(2,10,length(n_vec));
y_vec = abs(sin(n_vec));
% generate point grid
y = [x_vec(:); y_vec(:)];
resolution = [500,500];
px_ = linspace(min(n_vec), max(n_vec), resolution(1));
py_ = linspace(min(y), max(y), resolution(2));
[px, py] = meshgrid(px_, py_);
% extract points
in = inpolygon(px, py, N, X);
px = px(in);
py = py(in);
% generate color
cid = 1./(1+(exp(-py)/(exp(-y_vec(i))-exp(-x_vec(i)))));
c = jet(101);
c = c(round(cid*100)+1,:); % +1 to avoid zero indexing
% plot
figure;
scatter(px,py,16,c,'filled','s');

Image Transformation - Cartesian to Polar, and back again (MATLAB)

I have been using Peter Kovesi's MatLab functions for machine vision (which are outstanding if you aren't aware of them).
I have been transforming images to polar co-ordinates using the polar transform. The function from Peter Kovesi is named 'PolarTrans' and can be found here -
http://www.peterkovesi.com/matlabfns/#syntheticimages
The function beautifully transforms an images into polar co-ordinates. However, I would like the reverse to happen also. Peter Kovesi uses interp2 to transform images, but I can't seem to figure out how to reverse this transform. A requirement of interp2 is that it needs a meshgrid as input.
In short - can you help me reverse the transformation: polar to cartesian. I would like it be accordance with Peter's function - i.e. using the same parameters for coherence.
Dear Swjm,
I am posting my reply here because I do not have space in the comments section.
Firstly, thank you very much indeed for your reply. You have shown me how to invert interp2 - something I thought was impossible. This is a huge step forwards. However your code only maps a small segment of the image. Please see the demo code below to understand what I mean.
clc; clear all; close all;
gauss = fspecial('gauss',64,15);
gauss = uint8(mat2gray(gauss).*255);
[H,W] = size(gauss);
pim = polartrans(gauss,64,360);
cim = carttrans(pim,64,64);
subplot(2,2,1);
imagesc(gauss); colormap(jet);
axis off;
title('Image to be Transformed');
subplot(2,2,2);
imagesc(pim); colormap(jet);
axis off;
title('Polar Representation');
subplot(2,2,3);
imagesc(cim); colormap(jet);
axis off;
title('Back to Cartesian');
subplot(2,2,4);
diff = uint8(gauss) - uint8(cim);
imagesc(diff); colormap(jet);
axis off;
title('Difference Image');
I've had a look at Kovesi's code and this code should perform the reverse transformation. It assumes you used the 'full' shape and 'linear' map parameters in polartrans. Note that polar transforms generally lose resolution at low radial values (and gain resolution at high values), so it won't be lossless even if your polar image has the same dimensions as your original image.
function im = carttrans(pim, nrows, ncols, cx, cy)
[rad, theta] = size(pim); % Dimensions of polar image.
if nargin==3
cx = ncols/2 + .5; % Polar coordinate center, should match
cy = nrows/2 + .5; % polartrans. Defaults to same.
end
[X,Y] = meshgrid(1:ncols, 1:nrows);
[TH,R] = cart2pol(X-cx,Y-cy); % Polar coordinate arrays.
TH(TH<0) = TH(TH<0)+2*pi; % Put angles in range [0, 2*pi].
rmax = max(R(:)); % Max radius.
xi = TH * (theta+1) / 2*pi; % Query array for angles.
yi = R * rad / (rmax-1) + 1; % Query array for radius.
pim = [pim pim(:,1)]; % Add first col to end of polar image.
[pX,pY] = meshgrid(1:theta+1, 1:rad);
im = interp2(pX, pY, pim, xi, yi);

Plotting a 3D graph of normalized prices in MatLab

I'm doing Gaussian processes and I calculated a regression per year from a given matrix where each row represents a year , so the code is:
M1 = MainMatrix; %This is the given Matrix
ker =#(x,y) exp(-1013*(x-y)'*(x-y));
[ns, ms] = size(M1);
for N = 1:ns
x = M1(N,:);
C = zeros(ms,ms);
for i = 1:ms
for j = 1:ms
C(i,j)= ker(x(i),x(j));
end
end
u = randn(ms,1);
[A,S, B] = svd(C);
z = A*sqrt(S)*u; % z = A S^.5 u
And I wanna plotting each regression in a Graph 3D as the below:
I know that plot is a ribbon, but I have not idea how can I do that
The desired plot can be generated without the use of ribbon. Just use a surf-plot for all the prices and a fill3-plot for the plane at z=0. The boundaries of the plane are calculated from the actual limits of the figure. Therefore we need to set the limits before plotting the plane. Then just some adjustments are needed to generate almost the same appearance.
Here is the code:
% generate some data
days = (1:100)';
price = days*[0.18,-0.08,0.07,-0.10,0.12,-0.08,0.05];
price = price + 0.5*randn(size(price));
years = 2002+(1:size(price,2));
% prepare plot
width = 0.6;
X = ones(size(price,1),1)*0.5;
X = [-X,X]*width;
figure; hold on;
% plot all 'ribbons'
for i = 1:size(price,2)
h = surf([days,days],X+years(i),[price(:,i),price(:,i)]);
set(h,'MeshStyle','column');
end
% set axis limits
set(gca,'ZLim',[-20,20]);
% plot plane at z=0
limx = get(gca,'XLim');
limy = get(gca,'YLim');
fill3(reshape([limx;limx],1,[]),[flip(limy),limy],zeros(1,4),'g','FaceAlpha',0.2)
% set labels
xlabel('Day of trading')
ylabel('Year')
zlabel('Normalized Price')
% tweak appearance
set(gca,'YTick',years);
set(gca,'YDir','reverse');
view([-38,50])
colormap jet;
grid on;
%box on;
This is the result:
That's a ribbon plot with an additional surface at y=0 which can be drawn with fill3

Is there any way to make an iterative plot that rotates the axes at every iteration

I would like to make a plot then rotate the x-y axes by an angle;
then make the same plot again on the rotated axes, then rotate axes again for the next similar plot
Something like this:
hold all;
for k= 0:1:10
% rotate-axis-about-origin(angle * k)
plot(XY(:,1),XY(:,2));
end
Is there any way to achieve what I am proposing?
Use a rotation matrix inside the loop:
hold all;
% test vector and matrix
x = (1:10)';
y = x.^2;
XY0 = [x y];
angle = 1/180*pi; % 1 degree
for k= 0:1:10
% rotate-axis-about-origin(angle * k)
rot = [cos(angle*k) sin(angle*k);-sin(angle*k) cos(angle*k)];
XY = XY0*rot;
plot(XY(:,1),XY(:,2));
end
XY0 is the original matrix and XY varies each step.
Hope this is what you are looking for.
You can do that by rolling the camera at each step via camroll. Here's a toy working example for plotting sine:
hold all
x = -3:0.01:3;
y = sin(x);
angle = 1; % in degrees
for k = 1:90 % 90 steps
plot(x,y, 'k');
camroll(angle); % roll 'angle' degrees at each step
drawnow
pause(0.05)
end

Hough transform in MATLAB

Does anyone know how to use the Hough transform to detect the strongest lines in the binary image:
A = zeros(7,7);
A([6 10 18 24 36 38 41]) = 1;
Using the (rho; theta) format with theta in steps of 45° from -45° to 90°. And how do I show the accumulator array in MATLAB as well.
Any help or hints please?
Thank you!
If you have access to the Image Processing Toolbox, you can use the functions HOUGH, HOUGHPEAKS, and HOUGHLINES:
%# your binary image
BW = false(7,7);
BW([6 10 18 24 36 38 41]) = true;
%# hough transform, detect peaks, then get lines segments
[H T R] = hough(BW);
P = houghpeaks(H, 4);
lines = houghlines(BW, T, R, P, 'MinLength',2);
%# show accumulator matrix and peaks
imshow(H./max(H(:)), [], 'XData',T, 'YData',R), hold on
plot(T(P(:,2)), R(P(:,1)), 'gs', 'LineWidth',2);
xlabel('\theta'), ylabel('\rho')
axis on, axis normal
colormap(hot), colorbar
%# overlay detected lines over image
figure, imshow(BW), hold on
for k = 1:length(lines)
xy = [lines(k).point1; lines(k).point2];
plot(xy(:,1), xy(:,2), 'g.-', 'LineWidth',2);
end
hold off
Each pixel (x,y) maps to a set of lines (rho,theta) that run through it.
Build an accumulator matrix indexed by (rho theta).
For each point (x,y) that is on, generate all the quantized (rho, theta) values that correspond to (x,y) and increment the corresponding point in the accumulator.
Finding the strongest lines corresponds to finding peaks in the accumulator.
In practice, the descritization of the polar parameters is important to get right. Too fine and not enough points will overlap. Too coarse and each bin could correspond to multiple lines.
in pseudo code with liberties:
accum = zeros(360,100);
[y,x] = find(binaryImage);
y = y - size(binaryImage,1)/2; % use locations offset from the center of the image
x = x - size(binaryImage,2)/2;
npts = length(x);
for i = 1:npts
for theta = 1:360 % all possible orientations
rho = %% use trigonometry to find minimum distance between origin and theta oriented line passing through x,y here
q_rho = %% quantize rho so that it fits neatly into the accumulator %%
accum(theta,rho) = accum(theta,rho) + 1;
end
end