Bending a plane into a closed surface/cylinder - matlab

I'm doing a mathematical experiment in Matlab and the result should be a circle in the x,y-plane. But sometimes, the circle starts spiraling. I'm now trying to bend the x,y-plane into a cylinder (as in the following picture). At the moment I only have the x and y coordinates of the points.
I've tried converting them into polar coordinates and then use some 'surf' commando's, but nothing works right now
(source: wtcoeselgem.be)
Edit: I've used the plot3 command, as suggested by Ander Biguri, resulting in the following figure.
(source: wtcoeselgem.be)

I will consider that you have a curve defined by x and y coordinates which you want to fold around a cylinder.
%% // Generate sample data
x = linspace(0,10*pi) ;
y2 = cos(x) ;
y1 = 10*cos(x/10) ;
y = y1+y2 ; y = y-min(y) ;
figure, plot(x,y,'-o') ;
This produces:
Next I define a basic cylinder, nothing original:
%% // Basic cylinder (just for background)
[Xc,Yc,Zc] = cylinder(1,100);
Zc = Zc * max(y) ;
hs = surf(Xc,Yc,Zc) ;
set(hs,'FaceColor',[.8 .8 .8],'FaceAlpha',0.5,'EdgeColor','none') ;
hold on
And here comes the interesting bit:
%% // Fold the points around the cylinder
Number_of_turn = 2 ;
xrange = [min(x),max(x)] ;
xspan = xrange(2)-xrange(1) ;
xc = x / xspan * 2*pi * Number_of_turn ;
Xp = cos(xc) ;
Zp = y ;
Yp = sin(xc) ;
hp = plot3(Xp,Yp,Zp,'-ok') ;
Which render:
For this example I assumed you wanted to wrap your curve around "2 turns" of the cylinder. This is easily changed with the Number_of_turn variable.
Note that you can also change the radius of the cylinder by multiplying the Xp and Yp coordinates by your radius.

The following seems to do more or less what you want
%// Data
xmin = -3;
xmax = 3; %// this piece will get folded into a cylinder
Rc = 5; %// cylinder radius
zmaxc = 5; %// cylinder max z
zminc = -5; %// cylinder min z
%// Spiral
t = linspace(0,1,1000);
r = 1+2*t;
theta = 2*pi*3*t;
x1 = r.*cos(theta);
y1 = r.*sin(theta); %// example spiral. Defined by x1, y1
%// Do the bending
z2 = y1;
phi = (x1-xmin)/(xmax-xmin)*2*pi;
x2 = Rc*cos(phi);
y2 = Rc*sin(phi);
%// Plot cylinder
[xc yc zc] = cylinder(Rc*ones(1,100),100);
zc = zminc + (zmaxc-zminc)*zc;
surf(xc,yc,zc)
shading flat
hold on
%// Plot bent spiral
plot3(x2,y2,z2, 'k.-');
Original spiral:
Two views of the result:

Related

How to plot a circle in Matlab? (least square)

I am trying to plot a circle's equation-regression on x and y, but I do not know how to proceed. Any suggestions? (I want a circle to connect the points thru least square solution)
x = [5; 4; -1; 1];
y = [3; 5; 2; 1];
% circle's equation: x^2+y^2 = 2xc1+2yc2+c3
a = [2.*x,2.*y,ones(n,3)]
b = [x.^2 + y.^2];
c = a\b;
How do I plot the circle after this
There are a couple of ways how to plot a circle in matlab:
plot a line where the data points form a circle
use the 'o' marker in plot and the 'MarkerSize' name-value pair to set the radius of the circle
you can plot a circle image using the vscircle function
In your case, I would go with the first option, since you maintain in control of the circle size.
use the rectangle(...,'Curvature',[1 1]) function [EDITED: thx to #Cris Luengo]
So here is a plotting function
function circle(x,y,r)
%x and y are the coordinates of the center of the circle
%r is the radius of the circle
%0.01 is the angle step, bigger values will draw the circle faster but
%you might notice imperfections (not very smooth)
ang=0:0.01:2*pi+.01;
xp=r*cos(ang);
yp=r*sin(ang);
plot(x+xp,y+yp);
end
So with your (corrected) code, it looks like this
x = [5; 4; -1; 1];
y = [3; 5; 2; 1];
% circle's equation: x^2+y^2 = 2xc1+2yc2+c3
a = [2.*x,2.*y,ones(length(x),1)];
b = [x.^2 + y.^2];
c = a\b;
x_m = c(1)/2;
y_m = c(2)/2;
r = sqrt(x_m^2 + y_m^2 -c(3));
% plot data points
plot(x,y,'o')
hold on
% plot center
plot(x_m,y_m,'+')
% plot circle
circle(x_m,y_m,r)
hold off

How do I plot a curved surface in matlab?

I am trying to make a cut out of a pipe and I want to make a curved surface to represent the outside of the pipe. However when I plot the surface I only get the diagonal of the surface instead of the surface itself. How can I fix this?
MWE:
r = 0:0.1:3;
z = 0:0.1:10;
[rr, zz] = meshgrid(r,z);
% set cut planes angles
theta1 = 0;
theta2 = pi*135/180;
nt = 101; % angle resolution
figure(1);
clf;
t3 = linspace(theta1, (theta2 - 2*pi), nt);
[rr3, tt3] = meshgrid(r,t3);
% Create curved surface
xx5 = r(end) * cos(tt3);
yy5 = r(end) * sin(tt3);
h5 = surface(xx5, yy5,zz)
The mesh-grid you created is based on theta and the radius. However, the radius is constant for the outside of the pipe so instead it should be based on theta and z since those are the two independent variables defining the grid. Based on this reasoning I believe the following is what you're after.
r = 0:0.1:3;
z = 0:0.1:10;
% set cut planes angles
theta1 = 0;
theta2 = pi*135/180;
nt = 101; % angle resolution
figure(1);
clf;
% create a grid over theta and z
t3 = linspace(theta1, (theta2 - 2*pi), nt);
[tt3, zz3] = meshgrid(t3, z);
% convert from cylindical to Cartesian coordinates
xx5 = r(end) * cos(tt3);
yy5 = r(end) * sin(tt3);
% plot surface
h5 = surface(xx5, yy5, zz3, 'EdgeColor', 'none');
% extra stuff to make plot prettier
axis vis3d
axis equal
view(3)
camzoom(0.7);
Try with surf with surf(xx5, yy5, zz). Is this what you are looking for?

How can I make a cylindrical 3D contour plot in Matlab?

I have an axisymmetric flow with m x n grid points in r and z direction and I want to plot the temperature that is stored in a matrix with size mxn in a 3D cylindrical plot as visualized in the link below (My reputation is not high enough to include it as a picture).
I have managed to plot it in 2D (r,z plane) using contour but I would like to add the theta plane for visualization. How can I do this?
You can roll your own with multiple calls to surface().
Key idea is: for each surface: (1) theta=theta1, (2) theta=theta2, (3) z=zmax, (4) z=0, (5) r=rmax, generate a 3D mesh (xx,yy,zz) and the temperature map on that mesh. So you have to think about how to construct each surface mesh.
Edit: completed code is now provided. All magic number and fake data are put at (almost) the top of the code so it's easy to convert it into a general purpose Matlab function. Good luck!
% I have adjusted the range values to show the curved cylinder wall
% display a variable temperature
r = 0:0.1:2.6; % you can also try r = 0:0.1:3.0
z = 0:0.1:10; % you can also try z = 0:0.1:15;
[rr, zz] = meshgrid(r,z);
% fake temperature data
temp = 100 + (10* (3-rr).^0.6) .* (1-((zz - 7.5)/7.5).^6) ;
% visualize in 2D
figure(1);
clf;
imagesc(r,z,temp);
colorbar;
% set cut planes angles
theta1 = 0;
theta2 = pi*135/180;
nt = 40; % angle resolution
figure(2);
clf;
xx1 = rr * cos(theta1);
yy1 = rr * sin(theta1);
h1 = surface(xx1,yy1,zz,temp,'EdgeColor', 'none');
xx2 = rr * cos(theta2);
yy2 = rr * sin(theta2);
h2 = surface(xx2,yy2,zz,temp,'EdgeColor', 'none');
% polar meshgrid for the top end-cap
t3 = linspace(theta1, (theta2 - 2*pi), nt);
[rr3, tt3] = meshgrid(r,t3);
xx3 = rr3 .* cos(tt3);
yy3 = rr3 .* sin(tt3);
zz3 = ones(size(rr3)) * max(z);
temp3 = zeros(size(rr3));
for k = 1:length(r)
temp3(:,k) = temp(end,k);
end
h3 = surface(xx3,yy3,zz3,temp3,'EdgeColor', 'none');
% polar meshgrid for the bottom end-cap
zz4 = ones(size(rr3)) * min(z);
temp4 = zeros(size(rr3));
for k = 1:length(r)
temp4(:,k) = temp(1,k);
end
h4 = surface(xx3,yy3,zz4,temp4,'EdgeColor', 'none');
% generate a curved meshgrid
[tt5, zz5] = meshgrid(t3,z);
xx5 = r(end) * cos(tt5);
yy5 = r(end) * sin(tt5);
temp5 = zeros(size(xx5));
for k = 1:length(z)
temp5(k,:) = temp(k,end);
end
h5 = surface(xx5, yy5, zz5,temp5,'EdgeColor', 'none');
axis equal
colorbar
view(125,25); % viewing angles

Create random unit vector inside a defined conical region

I'm looking for a simple way for creating a random unit vector constrained by a conical region. The origin is always the [0,0,0].
My solution up to now:
function v = GetRandomVectorInsideCone(coneDir,coneAngleDegree)
coneDir = normc(coneDir);
ang = coneAngleDegree + 1;
while ang > coneAngleDegree
v = [randn(1); randn(1); randn(1)];
v = v + coneDir;
v = normc(v);
ang = atan2(norm(cross(v,coneDir)), dot(v,coneDir))*180/pi;
end
My code loops until the random generated unit vector is inside the defined cone. Is there a better way to do that?
Resultant image from test code bellow
Resultant frequency distribution using Ahmed Fasih code (in comments).
I wonder how to get a rectangular or normal distribution.
c = [1;1;1]; angs = arrayfun(#(i) subspace(c, GetRandomVectorInsideCone(c, 30)), 1:1e5) * 180/pi; figure(); hist(angs, 50);
Testing code:
clearvars; clc; close all;
coneDir = [randn(1); randn(1); randn(1)];
coneDir = [0 0 1]';
coneDir = normc(coneDir);
coneAngle = 45;
N = 1000;
vAngles = zeros(N,1);
vs = zeros(3,N);
for i=1:N
vs(:,i) = GetRandomVectorInsideCone(coneDir,coneAngle);
vAngles(i) = subspace(vs(:,i),coneDir)*180/pi;
end
maxAngle = max(vAngles);
minAngle = min(vAngles);
meanAngle = mean(vAngles);
AngleStd = std(vAngles);
fprintf('v angle\n');
fprintf('Direction: [%.3f %.3f %.3f]^T. Angle: %.2fº\n',coneDir,coneAngle);
fprintf('Min: %.2fº. Max: %.2fº\n',minAngle,maxAngle);
fprintf('Mean: %.2fº\n',meanAngle);
fprintf('Standard Dev: %.2fº\n',AngleStd);
%% Plot
figure;
grid on;
rotate3d on;
axis equal;
axis vis3d;
axis tight;
hold on;
xlabel('X'); ylabel('Y'); zlabel('Z');
% Plot all vectors
p1 = [0 0 0]';
for i=1:N
p2 = vs(:,i);
plot3ex(p1,p2);
end
% Trying to plot the limiting cone, but no success here :(
% k = [0 1];
% [X,Y,Z] = cylinder([0 1 0]');
% testsubject = surf(X,Y,Z);
% set(testsubject,'FaceAlpha',0.5)
% N = 50;
% r = linspace(0, 1, N);
% [X,Y,Z] = cylinder(r, N);
%
% h = surf(X, Y, Z);
%
% rotate(h, [1 1 0], 90);
plot3ex.m:
function p = plot3ex(varargin)
% Plots a line from each p1 to each p2.
% Inputs:
% p1 3xN
% p2 3xN
% args plot3 configuration string
% NOTE: p1 and p2 number of points can range from 1 to N
% but if the number of points are different, one must be 1!
% PVB 2016
p1 = varargin{1};
p2 = varargin{2};
extraArgs = varargin(3:end);
N1 = size(p1,2);
N2 = size(p2,2);
N = N1;
if N1 == 1 && N2 > 1
N = N2;
elseif N1 > 1 && N2 == 1
N = N1
elseif N1 ~= N2
error('if size(p1,2) ~= size(p1,2): size(p1,2) and/or size(p1,2) must be 1 !');
end
for i=1:N
i1 = i;
i2 = i;
if i > N1
i1 = N1;
end
if i > N2
i2 = N2;
end
x = [p1(1,i1) p2(1,i2)];
y = [p1(2,i1) p2(2,i2)];
z = [p1(3,i1) p2(3,i2)];
p = plot3(x,y,z,extraArgs{:});
end
Here’s the solution. It’s based on the wonderful answer at https://math.stackexchange.com/a/205589/81266. I found this answer by googling “random points on spherical cap”, after I learned on Mathworld that a spherical cap is this cut of a 3-sphere with a plane.
Here’s the function:
function r = randSphericalCap(coneAngleDegree, coneDir, N, RNG)
if ~exist('coneDir', 'var') || isempty(coneDir)
coneDir = [0;0;1];
end
if ~exist('N', 'var') || isempty(N)
N = 1;
end
if ~exist('RNG', 'var') || isempty(RNG)
RNG = RandStream.getGlobalStream();
end
coneAngle = coneAngleDegree * pi/180;
% Generate points on the spherical cap around the north pole [1].
% [1] See https://math.stackexchange.com/a/205589/81266
z = RNG.rand(1, N) * (1 - cos(coneAngle)) + cos(coneAngle);
phi = RNG.rand(1, N) * 2 * pi;
x = sqrt(1-z.^2).*cos(phi);
y = sqrt(1-z.^2).*sin(phi);
% If the spherical cap is centered around the north pole, we're done.
if all(coneDir(:) == [0;0;1])
r = [x; y; z];
return;
end
% Find the rotation axis `u` and rotation angle `rot` [1]
u = normc(cross([0;0;1], normc(coneDir)));
rot = acos(dot(normc(coneDir), [0;0;1]));
% Convert rotation axis and angle to 3x3 rotation matrix [2]
% [2] See https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
crossMatrix = #(x,y,z) [0 -z y; z 0 -x; -y x 0];
R = cos(rot) * eye(3) + sin(rot) * crossMatrix(u(1), u(2), u(3)) + (1-cos(rot))*(u * u');
% Rotate [x; y; z] from north pole to `coneDir`.
r = R * [x; y; z];
end
function y = normc(x)
y = bsxfun(#rdivide, x, sqrt(sum(x.^2)));
end
This code just implements joriki’s answer on math.stackexchange, filling in all the details that joriki omitted.
Here’s a script that shows how to use it.
clearvars
coneDir = [1;1;1];
coneAngleDegree = 30;
N = 1e4;
sol = randSphericalCap(coneAngleDegree, coneDir, N);
figure;plot3(sol(1,:), sol(2,:), sol(3,:), 'b.', 0,0,0,'rx');
grid
xlabel('x'); ylabel('y'); zlabel('z')
legend('random points','origin','location','best')
title('Final random points on spherical cap')
Here is a 3D plot of 10'000 points from the 30° spherical cap centered around the [1; 1; 1] vector:
Here’s 120° spherical cap:
Now, if you look at the histogram of the angles between these random points at the coneDir = [1;1;1], you will see that the distribution is skewed. Here’s the distribution:
Code to generate this:
normc = #(x) bsxfun(#rdivide, x, sqrt(sum(x.^2)));
mysubspace = #(a,b) real(acos(sum(bsxfun(#times, normc(a), normc(b)))));
angs = arrayfun(#(i) mysubspace(coneDir, sol(:,i)), 1:N) * 180/pi;
nBins = 16;
[n, edges] = histcounts(angs, nBins);
centers = diff(edges(1:2))*[0:(length(n)-1)] + mean(edges(1:2));
figure('color','white');
bar(centers, n);
xlabel('Angle (degrees)')
ylabel('Frequency')
title(sprintf('Histogram of angles between coneDir and random points: %d deg', coneAngleDegree))
Well, this makes sense! If you generate points from the 120° spherical cap around coneDir, of course the 1° cap is going to have very few of those samples, whereas the strip between the 10° and 11° caps will have far more points. So what we want to do is normalize the number of points at a given angle by the surface area of the spherical cap at that angle.
Here’s a function that gives us the surface area of the spherical cap with radius R and angle in radians theta (equation 16 on Mathworld’s spherical cap article):
rThetaToH = #(R, theta) R * (1 - cos(theta));
rThetaToS = #(R, theta) 2 * pi * R * rThetaToH(R, theta);
Then, we can normalize the histogram count for each bin (n above) by the difference in surface area of the spherical caps at the bin’s edges:
figure('color','white');
bar(centers, n ./ diff(rThetaToS(1, edges * pi/180)))
The figure:
This tells us “the number of random vectors divided by the surface area of the spherical segment between histogram bin edges”. This is uniform!
(N.B. If you do this normalized histogram for the vectors generated by your original code, using rejection sampling, the same holds: the normalized histogram is uniform. It’s just that rejection sampling is expensive compared to this.)
(N.B. 2: note that the naive way of picking random points on a sphere—by first generating azimuth/elevation angles and then converting these spherical coordinates to Cartesian coordinates—is no good because it bunches points near the poles: Mathworld, example, example 2. One way to pick points on the entire sphere is sampling from the 3D normal distribution: that way you won’t get bunching near poles. So I believe that your original technique is perfectly appropriate, giving you nice, evenly-distributed points on the sphere without any bunching. This algorithm described above also does the “right thing” and should avoid bunching. Carefully evaluate any proposed algorithms to ensure that the bunching-near-poles problem is avoided.)
it is better to use spherical coordinates and convert it to cartesian coordinates:
coneDirtheta = rand(1) * 2 * pi;
coneDirphi = rand(1) * pi;
coneAngle = 45;
N = 1000;
%perfom transformation preventing concentration of points around the pole
rpolar = acos(cos(coneAngle/2*pi/180) + (1-cos(coneAngle/2*pi/180)) * rand(N, 1));
thetapolar = rand(N,1) * 2 * pi;
x0 = rpolar .* cos(thetapolar);
y0 = rpolar .* sin(thetapolar);
theta = coneDirtheta + x0;
phi = coneDirphi + y0;
r = rand(N, 1);
x = r .* cos(theta) .* sin(phi);
y = r .* sin(theta) .* sin(phi);
z = r .* cos(phi);
scatter3(x,y,z)
if all points should be of length 1 set r = ones(N,1);
Edit:
since intersection of cone with sphere forms a circle first we create random points inside a circle with raduis of (45 / 2) in polar coordinates and as #Ahmed Fasih commented to prevent concentration of points near the pole we should first transform this random points, then convert polar to cartesian 2D coordinates to form x0 and y0
we can use x0 and y0 as phi & theta angle of spherical coordinates and add coneDirtheta & coneDirphi as offsets to these coordinates.
then convert spherical to cartesian 3D coordinates

fill function in MATLAB

I'm having issues unterstanding the function fill in MATLAB , I have a PSD of a file the I want to change it background like :
[xPSD,f] = pwelch(x,hanning(4096),2048,4096*2 ,fs);
plot(f,10*log10(xPSD));
x= f(100:150);
y= 10*log10(xPSD(100:150))
fill(x,y,'y')
the result is in the right direction but not what I need :
I would like get the color tell x axis like :
is their a way to do this
A working solution is:
[xPSD,f] = pwelch(x,hanning(4096),2048,4096*2 ,fs);
plot(f,10*log10(xPSD));
hold on
x= f(100:150);
y= 10*log10(xPSD(100:150));
yMax = ylim;
yMax = yMax(2);
x = x'; % Use this line only in the case that the size(x, 1) > 1
X = [x fliplr(x)];
Y = [y' ones(1, length(y)) .* yMax];
fill(X, Y, 'y')
What you were missing is that fill method looks for an area to fill. In the above code the area is defined by pairs of points. That, for the first (i.e. lower part) of the area we have the x vector and the y points. The second area (i.e. the upper part) is defined by the reversed vector x (image your pencil to first starting drawing towards rights for the lower part and then for the upper going left) and the points of the upper limit of your axes.
Edit:
Minimal example with the handel data from MATLAB:
load handel;
x = y; % Just to be consistent with the OP
fs = Fs; % Just to be consistent with the OP
[xPSD,f] = pwelch(x,hanning(4096),2048,4096*2 ,fs);
plot(f,10*log10(xPSD));
hold on
x= f(100:150);
y= 10*log10(xPSD(100:150));
yMax = ylim;
yMax = yMax(2);
x = x'; % Use this line only in the case that the size(x, 1) > 1
X = [x fliplr(x)];
Y = [y' ones(1, length(y)) .* yMax];
fill(X, Y, 'y')
xlim([0 200]) % To focus on the result
The result is:
Yes, there is always a way ;)
In your case, you simply need to add two points in x and y that go to the top boudary of the plot:
x = f(100:150);
y = 10*log10(xPSD(100:150))
% Add two points
Y = ylim;
x = [x(1) ; x(:) ; x(end)];
y = [Y(2) ; y(:) ; Y(2)];
% Display filled area
fill(x,y,'y')
Best,