Curved arrows in matlab - matlab

For documentation purpose I'd like to show the various spherical coordinates systems that can be used to describe a position on a sphere (i.e. position can be described as xyz-coordinates or roll-over-azimuths, azimuth-over-elevation or elevation-over-azimuth, etc).
I did not find clear illustrations on the .net, especially for non-regular conventions, and I'd like to use matlab to create simple illustrations like the following one (roll-over-azimuth system) which, imao, is straightforward to understand :
Anyhow I was wondering how I can create the curved arrows to show the angular direction (phi/theta arrows in above illustration). Drawing straight vectors using quiver3 is ok. I tried reading about stream3 but did not get the point about usage. I'd like to have something simple like:
function [h] = CreateCurvedArrow(startXYZ, endXYZ)
%[
% Draw curved-line in the plane defined by
% vectors 'Origin->StartXYZ' and 'Origin->EndXYZ'
% going from 'StartXYZ' to 'EndXYZ'
%]
I hope there's some easy way to do it else I'll work-around using line segments.

Simply for the fun of doing it:
The algorithm slowy rotates Center->StartPoint vector toward Center->EndPoint vector around their Normal axis and uses intermediate points to draw the curved arrow. Implementation can be further improved of course:
function [] = TestCurvedArrow()
%[
hold on
CreateCurvedArrow3(0.3*[1 0 0], 0.3*[0 1 0]);
CreateCurvedArrow3(0.2*[0 1 0], 0.2*[0 0 1]);
CreateStraightArrow([0 0 0], [1 0 0], 'r');
CreateStraightArrow([0 0 0], [0 1 0], 'g');
CreateStraightArrow([0 0 0], [0 0 1], 'b');
hold off
daspect([1 1 1]);
%]
end
%% --- Creates a curved arrow
% from: Starting position - (x,y,z) upplet
% to: Final position - (x,y,z) upplet
% center: Center of arc - (x,y,z) upplet => by default the origin
% count: The number of segment to draw the arrow => by default 15
function [h] = CreateCurvedArrow3(from, to, center, count)
%[
% Inputs
if (nargin < 4), count = 15; end
if (nargin < 3), center = [0 0 0]; end
center = center(:); from = from(:); to = to(:);
% Start, stop and normal vectors
start = from - center; rstart = norm(start);
stop = to - center; rstop = norm(stop);
angle = atan2(norm(cross(start,stop)), dot(start,stop));
normal = cross(start, stop); normal = normal / norm(normal);
% Compute intermediate points by rotating 'start' vector
% toward 'end' vector around 'normal' axis
% See: http://inside.mines.edu/fs_home/gmurray/ArbitraryAxisRotation/
phiAngles = linspace(0, angle, count);
r = linspace(rstart, rstop, count) / rstart;
intermediates = zeros(3, count);
a = center(1); b = center(2); c = center(3);
u = normal(1); v = normal(2); w = normal(3);
x = from(1); y = from(2); z = from(3);
for ki = 1:count,
phi = phiAngles(ki);
cosp = cos(phi); sinp = sin(phi);
T = [(u^2+(v^2+w^2)*cosp) (u*v*(1-cosp)-w*sinp) (u*w*(1-cosp)+v*sinp) ((a*(v^2+w^2)-u*(b*v+c*w))*(1-cosp)+(b*w-c*v)*sinp); ...
(u*v*(1-cosp)+w*sinp) (v^2+(u^2+w^2)*cosp) (v*w*(1-cosp)-u*sinp) ((b*(u^2+w^2)-v*(a*u+c*w))*(1-cosp)+(c*u-a*w)*sinp); ...
(u*w*(1-cosp)-v*sinp) (v*w*(1-cosp)+u*sinp) (w^2+(u^2+v^2)*cosp) ((c*(u^2+v^2)-w*(a*u+b*v))*(1-cosp)+(a*v-b*u)*sinp); ...
0 0 0 1 ];
intermediate = T * [x;y;z;r(ki)];
intermediates(:,ki) = intermediate(1:3);
end
% Draw the curved line
% Can be improved of course with hggroup etc...
X = intermediates(1,:);
Y = intermediates(2,:);
Z = intermediates(3,:);
tf = ishold;
if (~tf), hold on; end
h = line(X,Y,Z);
quiver3(X(end-1), Y(end-1), Z(end-1), X(end)-X(end-1), Y(end)-Y(end-1), Z(end)-Z(end-1),1);
if (~tf), hold off; end
%]
end
%% --- Creates normal arrow
% from: Starting position - (x,y,z) upplet
% to: Final position - (x,y,z) upplet
% lineSpec: Line specifications
function [h] = CreateStraightArrow(from, to, lineSpec)
%[
h = quiver3(from(1), from(2), from(3), to(1)-from(1), to(2)-from(2), to(3)-from(3), lineSpec);
%]
end

Related

Is there a matlab function(s) I can use to create a realistic diagram of the I.S.S?

As part of a project I am undertaking at the moment, I have to solve the two-body problem of the international space station orbiting the Earth. I have managed to approximate this so far by using the sphere/surf function, however, I was wondering if there was any way I could create a more realistic figure representing the ISS? Unfortunately,this project has to be done solely through MATLAB so I cannot use any other tools which may provide better visualisation
NASA has 3D models of many objects, including the ISS, which can be found here. This file can be converted to an STL however you want, I found this random website which worked for me.
In Matlab, you can read in this file via
stl = stlread('isscombined.stl');
V = stl.Points;
F = stl.ConnectivityList
Then, you can plot it using
p = patch('vertices',V,'faces',F,'FaceColor',[.8 .8 .8]);
and then you can update the object with new vertex positions as the station orbits the Earth. Obviously, you can also scale the object by multiplying the vertices by some amount. If you don't want the facet edges plotted, you can also add 'EdgeAlpha', 0 to your patch options.
Here's a simple example which shows the ISS orbiting around a sphere
% Note: not to scale
ISS_radius = 2; % distance from center of Earth
RE = 1; % radius of earth
theta = 0:.05:2*pi;
x = ISS_radius*cos(theta);
y = ISS_radius*sin(theta);
stl = stlread('isscombined.stl');
r = .01; % scaling factor
V = stl.Points * r;
V = V - mean(V); % center at origin
F = stl.ConnectivityList;
figure; hold on;
plot3(x,y,zeros(numel(theta)),'--');
[X,Y,Z] = sphere(50);
surf(RE*X,RE*Y,RE*Z,'FaceColor',[0 0 .8],'EdgeAlpha',0);
p = patch('Vertices', V*r, 'Faces', F, 'FaceColor', [0 0 0], 'EdgeAlpha', 0);
axis equal;
set(gca,'View',[200 13])
grid on;
counter = 1;
while true
p.Vertices = V + [x(counter), y(counter), 0];
pause(0.01);
drawnow
counter = mod(counter + 1, numel(theta)) + 1;
axis([-1 1 -1 1 -1 1]*ISS_radius*1.2)
end

How to prevent an object from being illuminated by camlight in Matlab?

[Hereafter are 4 snippets, one should only be interested in reading the two first ones. However by copy-pasting all of these, one should be able to launch what I see, although screenshots are provided at the end.]
Hi, by launching this main.m :
%To see if plotting a tick after setting camlight headlight will leads to
%its background becoming gray or not
%clear all
figure
arrow = arrow3D([0 0 0], [1 1 1], 'r', 0.8, 0.2, 1.5);
set(arrow, 'EdgeColor', 'interp', 'FaceColor', 'interp');
%camlight headlight %might be interesting to uncomment this line
pause(5)
surfaceHandle = rotateAxisTicks('lol','r',10,-0.3,0.5,0.5,1,1,1,0);
pause(5)
camlight headlight
%material(surfaceHandle,'default') %doesn't work
%surfaceHandle1.FaceLighting = 'none' %doesn't work
, which uses that function rotateAxisTicks.m
function surfaceHandle = rotateAxisTicks(str,color,fontsize,zmax,graduSpace,boxHeight,perc,labelNumber,axnumber,thetaInput)
%https://stackoverflow.com/questions/9843048/matlab-how-to-plot-a-text-in-3d
%zmax : give it a negative value to not overlap the axis
%graduSpace : space between each graduation, within the projected on [0,1] axis if axis = x||y, OR local (not yet projected on x,y) axis !!
%boxHeight : width of the boxes depend on how much the axis graduations are refined, so height shouldn't depend on graduSpace
%perc : if perc = 1 (100%), then the labels are all sticked together with no space inbetween
%labelNumber : the first tick to be displayed is actually associated to the second graduation (0 can't get several labels)
%axnumber : out of nbParams, 1 for x, 2 for y, then, from closest to x, to closest to y : 3 to nbParams.
%thetaInput : (angle around z, from x to the axis) has to be in degree
%% Seems like there is no way to get rid of the black contouring...
hFigure = figure(1000);
set(hFigure,'Color', 'w', ... % Create a figure window
'MenuBar', 'none', ...
'ToolBar', 'none');
hText = uicontrol('Parent', hFigure, ... % Create a text object
'Style', 'text', ...
'String', str, ...
'BackgroundColor', 'w', ...
'ForegroundColor', color, ...
'FontSize', fontsize, ...
'FontWeight', 'normal');
set([hText hFigure], 'Pos', get(hText, 'Extent')); %# Adjust the sizes of the
%# text and figure
imageData = getframe(hFigure); %# Save the figure as an image frame
delete(hFigure);
textImage = imageData.cdata; %# Get the RGB image of the text
%% MAKE THE X,Y,Z (text) REVERSE DEPENDING ON AZIMUT VALUE (launch a fig and see on the bottom in real time the azimut value)
% X or Y or Z(1,1) = _______
% * |
% | |
% |_______|
% X or Y or Z(1,2) = _______
% | *
% | |
% |_______|
% X or Y or Z(2,1) = _______
% | |
% | |
% x_______|
% X or Y or Z(2,2) = _______
% | |
% | |
% |_______x
if axnumber == 2 %axis = y
X = [0 0; 0 0];
Y = [0 perc*graduSpace; 0 perc*graduSpace] + labelNumber*graduSpace - perc*graduSpace/2;
%(graduSpace/2)/2 to center under the graduation, (1-perc)/2) to
%additionally shift a bit so that the perc% of graduSpace stay centered
%under the graduation
else %I assume axis = x, that I might later rotate if it's not actually x
X = [0 perc*graduSpace; 0 perc*graduSpace] + labelNumber*graduSpace - perc*graduSpace/2; %+labelNumber*((graduSpace/2)+((1-perc)/2)*graduSpace)
Y = [0 0; 0 0];
end
Z = [zmax zmax; zmax-boxHeight zmax-boxHeight];
surfaceHandle = surf(X, Y, Z, 'FaceColor', 'texturemap', 'CData', textImage);
if axnumber > 2
rotate(surfaceHandle, [0 0 1], thetaInput,[0 0 0]);
end
end
as well as that function arrow3D.m :
function arrowHandle = arrow3D(pos, deltaValues, colorCode, stemRatio, cylRad, radRatioCone)
% arrowHandle = arrow3D(pos, deltaValues, colorCode, stemRatio) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Used to plot a single 3D arrow with a cylindrical stem and cone arrowhead
% pos = [X,Y,Z] - spatial location of the starting point of the arrow (end of stem)
% deltaValues = [QX,QY,QZ] - delta parameters denoting the magnitude of the arrow along the x,y,z-axes (relative to 'pos')
% colorCode - Color parameters as per the 'surf' command. For example, 'r', 'red', [1 0 0] are all examples of a red-colored arrow
% stemRatio - The ratio of the length of the stem in proportion to the arrowhead. For example, a call of:
% arrow3D([0,0,0], [100,0,0] , 'r', 0.82) will produce a red arrow of magnitude 100, with the arrowstem spanning a distance
% of 82 (note 0.82 ratio of length 100) while the arrowhead (cone) spans 18.
%
% Example:
% arrow3D([0,0,0], [4,3,7]); %---- arrow with default parameters
% axis equal;
%
% Author: Shawn Arseneau
% Created: September 14, 2006
% Updated: September 18, 2006
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin<2 || nargin>6
error('Incorrect number of inputs to arrow3D');
end
if numel(pos)~=3 || numel(deltaValues)~=3
error('pos and/or deltaValues is incorrect dimensions (should be three)');
end
if nargin<3
colorCode = 'interp';
end
if nargin<4
stemRatio = 0.75;
end
X = pos(1); %---- with this notation, there is no need to transpose if the user has chosen a row vs col vector
Y = pos(2);
Z = pos(3);
[sphi, stheta, srho] = cart2sph(deltaValues(1), deltaValues(2), deltaValues(3));
%******************************************* CYLINDER == STEM *********************************************
%cylinderRadius = 0.05*srho;
cylinderRadius = cylRad;
cylinderLength = srho*stemRatio;
[CX,CY,CZ] = cylinder(cylinderRadius);
CZ = CZ.*cylinderLength; %---- lengthen
%----- ROTATE CYLINDER
[row, col] = size(CX); %---- initial rotation to coincide with X-axis
newEll = rotatePoints([0 0 -1], [CX(:), CY(:), CZ(:)]); %CX(:) actually reshape the 2xN matrices in a 2N vert vector, by vertically concatenating each column
CX = reshape(newEll(:,1), row, col);
CY = reshape(newEll(:,2), row, col);
CZ = reshape(newEll(:,3), row, col);
[row, col] = size(CX);
newEll = rotatePoints(deltaValues, [CX(:), CY(:), CZ(:)]);
stemX = reshape(newEll(:,1), row, col);
stemY = reshape(newEll(:,2), row, col);
stemZ = reshape(newEll(:,3), row, col);
%----- TRANSLATE CYLINDER
stemX = stemX + X;
stemY = stemY + Y;
stemZ = stemZ + Z;
%******************************************* CONE == ARROWHEAD *********************************************
coneLength = srho*(1-stemRatio);
coneRadius = cylinderRadius*radRatioCone;
incr = 100; %---- Steps of cone increments
coneincr = coneRadius/incr;
[coneX, coneY, coneZ] = cylinder(cylinderRadius*2:-coneincr:0); %---------- CONE
coneZ = coneZ.*coneLength;
%----- ROTATE CONE
[row, col] = size(coneX);
newEll = rotatePoints([0 0 -1], [coneX(:), coneY(:), coneZ(:)]);
coneX = reshape(newEll(:,1), row, col);
coneY = reshape(newEll(:,2), row, col);
coneZ = reshape(newEll(:,3), row, col);
newEll = rotatePoints(deltaValues, [coneX(:), coneY(:), coneZ(:)]);
headX = reshape(newEll(:,1), row, col);
headY = reshape(newEll(:,2), row, col);
headZ = reshape(newEll(:,3), row, col);
%---- TRANSLATE CONE
V = [0, 0, srho*stemRatio]; %---- centerline for cylinder: the multiplier is to set the cone 'on the rim' of the cylinder
Vp = rotatePoints([0 0 -1], V);
Vp = rotatePoints(deltaValues, Vp);
headX = headX + Vp(1) + X;
headY = headY + Vp(2) + Y;
headZ = headZ + Vp(3) + Z;
%************************************************************************************************************
hStem = surf(stemX, stemY, stemZ, 'FaceColor', colorCode, 'EdgeColor', 'none');
hold on
hBottStem = fill3(stemX(1,:),stemY(1,:),stemZ(1,:), colorCode, 'EdgeColor', 'none');
hold on
hHead = surf(headX, headY, headZ, 'FaceColor', colorCode, 'EdgeColor', 'none');
hold on
hBottCone = fill3(headX(1,:),headY(1,:),headZ(1,:), colorCode, 'EdgeColor', 'none');
if nargout==1
arrowHandle = [hStem, hBottStem, hHead, hBottCone];
end
which itself uses that function rotatePoints.m :
function rotatedData = rotatePoints(alignmentVector, originalData)
% rotatedData = rotatePoints(alignmentVector, originalData) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Rotate the 'originalData' in the form of Nx2 or Nx3 about the origin by aligning the x-axis with the alignment vector
%
% Rdata = rotatePoints([1,2,-1], [Xpts(:), Ypts(:), Zpts(:)]) - rotate the (X,Y,Z)pts in 3D with respect to the vector [1,2,-1]
%
% Rotating using spherical components can be done by first converting using [dX,dY,dZ] = cart2sph(theta, phi, rho); alignmentVector = [dX,dY,dZ];
%
% Example:
% %% Rotate the point [3,4,-7] with respect to the following:
% %%%% Original associated vector is always [1,0,0]
% %%%% Calculate the appropriate rotation requested with respect to the x-axis. For example, if only a rotation about the z-axis is
% %%%% sought, alignmentVector = [2,1,0] %% Note that the z-component is zero
% rotData = rotatePoints(alignmentVector, [3,4,-7]);
%
% Author: Shawn Arseneau
% Created: Feb.2, 2006
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
alignmentDim = numel(alignmentVector); %number of elements in a matrix
DOF = size(originalData,2); %---- DOF = Degrees of Freedom (i.e. 2 for two dimensional and 3 for three dimensional data)
if alignmentDim~=DOF
error('Alignment vector does not agree with originalData dimensions');
end
if DOF<2 || DOF>3
error('rotatePoints only does rotation in two or three dimensions');
end
if DOF==2 % 2D rotation...
[rad_theta, rho] = cart2pol(alignmentVector(1), alignmentVector(2));
deg_theta = -1 * rad_theta * (180/pi);
ctheta = cosd(deg_theta); stheta = sind(deg_theta);
Rmatrix = [ctheta, -1.*stheta;...
stheta, ctheta];
rotatedData = originalData*Rmatrix;
%assumption: rotate all the datas from the original base to the
%base where the original x becomes alignmentVector
else % 3D rotation...
[rad_theta, rad_phi, rho] = cart2sph(alignmentVector(1), alignmentVector(2), alignmentVector(3));
rad_theta = rad_theta * -1;
deg_theta = rad_theta * (180/pi);
deg_phi = rad_phi * (180/pi);
ctheta = cosd(deg_theta); stheta = sind(deg_theta); %MM : is it more accurate??
Rz = [ctheta, -1.*stheta, 0;...
stheta, ctheta, 0;...
0, 0, 1]; %% First rotate as per theta around the Z axis
rotatedData = originalData*Rz;
[rotX, rotY, rotZ] = sph2cart(-1* (rad_theta+(pi/2)), 0, 1); %% Second rotation corresponding to phi
%assuming alignmentVector is the x for the new base, then the
%hereabove argument corresponds to the y (z inversed)
%the hereabove output = newX(in base 0) vectorial product -z(in base0)
rotationAxis = [rotX, rotY, rotZ];
u = rotationAxis(:)/norm(rotationAxis); %% Code extract from rotate.m from MATLAB
cosPhi = cosd(deg_phi);
sinPhi = sind(deg_phi);
invCosPhi = 1 - cosPhi;
x = u(1);
y = u(2);
z = u(3);
Rmatrix = [cosPhi+x^2*invCosPhi x*y*invCosPhi-z*sinPhi x*z*invCosPhi+y*sinPhi; ...
x*y*invCosPhi+z*sinPhi cosPhi+y^2*invCosPhi y*z*invCosPhi-x*sinPhi; ...
x*z*invCosPhi-y*sinPhi y*z*invCosPhi+x*sinPhi cosPhi+z^2*invCosPhi]';
rotatedData = rotatedData*Rmatrix;
end
I end up getting:
while I would like to conserve both intermediate plots containing the interp arrow:
and the text on flashy white background:
So there are actually two questions:
1) Why calling my text tick disables the interp effect (varying color from blue to yellow) ?
2) How can I keep the camlight without enlightening my tick box? (i.e while keeping its background white)
Basically one should only need to look at the two first snippets, the later 2 ones are useless for my issue.
By thanking you a lot!
Place it in another axes
As I said in comment, you have 2 graphic objects in the same axes which have to interpret their CData in a completely different manner.
The first options I looked for was to modify one of the arrow3d or rotateAxisTicks so their graphic objects would be "compatible" (in the way the color data are interpolated on an axes), but it would be quite intensive and the aspect of the 3d text would have to be constantly monitored/adjusted for any other change in the figure.
So the easiest option is a classic MATLAB hack ... place your graphic objects in different containers (different axes), then superimpose them on a figure, and match some properties (limits, view, etc ...) so they appear to be only one.
Here it goes:
%% Draw your main arrow in the main figure
mainfig = figure ;
ax1 = axes ;
arrow = arrow3D([0 0 0], [1 1 1], 'r', 0.8, 0.2, 1.5);
set(arrow, 'EdgeColor', 'interp', 'FaceColor', 'interp');
camlight headlight
%% Draw your text in a temporary figure
tempfig = figure ;
ax2 = axes ;
surfaceHandle = rotateAxisTicks('lol','r',10,-0.3,0.5,0.5,1,1,1,0);
camlight headlight
%material(surfaceHandle,'default') %doesn't work
%surfaceHandle1.FaceLighting = 'none' %doesn't work
%% Prepare and set matching limits
xl = [ax1.XLim ; ax2.XLim] ;
xl = [min(xl(:,1)) , max(xl(:,2))] ;
yl = [ax1.YLim ; ax2.YLim] ;
yl = [min(yl(:,1)) , max(yl(:,2))] ;
zl = [ax1.ZLim ; ax2.ZLim] ;
zl = [min(zl(:,1)) , max(zl(:,2))] ;
hax = [ax1;ax2] ;
set(hax,'XLim',xl,'YLim',yl,'ZLim',zl)
% Adjust the view to be sure
ax2.View = ax1.View ;
%% Remove secondary axes background, then move it to main figure
ax2.Visible = 'off' ;
ax2.Parent = mainfig ;
delete(tempfig)
%% link the view between axes
hl = linkprop( hax , 'View' ) ;
% or link even more properties at once
% hl = linkprop( hax , 'View' , 'XLim','YLim','ZLim') ;
Which gives you:
note: Your 3d arrow is also made up of 2 different graphic objects (2x surf and 2x patch). The 2 patches are not rendered when you set the interp mode. You should modify the arrow3d function to either (a) changes the patch objects to surf so everything is the same type and compatible, or (b) remove them completely from the function (if they are not rendered they are only annoying ... triggering warnings everywhere).
edit
And here is the modified code for arrow3d.m. I changed it so the output is now only one surface object, easier to assign properties and no danger of mismatch between patch and surf. I also simplified it, removed a few bits that were not necessary, and reduced the total number of points necessary for the surface.
With this you get the bottom of the stem and the under-cone:
function arrowHandle = arrow3D(pos, deltaValues, colorCode, stemRatio, cylRad )
% arrowHandle = arrow3D(pos, deltaValues, colorCode, stemRatio) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Used to plot a single 3D arrow with a cylindrical stem and cone arrowhead
% pos = [X,Y,Z] - spatial location of the starting point of the arrow (end of stem)
% deltaValues = [QX,QY,QZ] - delta parameters denoting the magnitude of the arrow along the x,y,z-axes (relative to 'pos')
% colorCode - Color parameters as per the 'surf' command. For example, 'r', 'red', [1 0 0] are all examples of a red-colored arrow
% stemRatio - The ratio of the length of the stem in proportion to the arrowhead. For example, a call of:
% arrow3D([0,0,0], [100,0,0] , 'r', 0.82) will produce a red arrow of magnitude 100, with the arrowstem spanning a distance
% of 82 (note 0.82 ratio of length 100) while the arrowhead (cone) spans 18.
%
% Example:
% arrow3D([0,0,0], [4,3,7]); %---- arrow with default parameters
% axis equal;
%
% Author: Shawn Arseneau
% Created: September 14, 2006
% Updated: September 18, 2006
%
% Updated: December 20, 2018
% Tlab - refactored to have only one surface object as ouput
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin<2 || nargin>6
error('Incorrect number of inputs to arrow3D');
end
if numel(pos)~=3 || numel(deltaValues)~=3
error('pos and/or deltaValues is incorrect dimensions (should be three)');
end
if nargin<3
colorCode = 'interp';
end
if nargin<4
stemRatio = 0.75;
end
Ncol = 21 ; % default number of column for the "cylinder.m" function
X = pos(1); %---- with this notation, there is no need to transpose if the user has chosen a row vs col vector
Y = pos(2);
Z = pos(3);
[~, ~, srho] = cart2sph(deltaValues(1), deltaValues(2), deltaValues(3));
%******************************************* CYLINDER == STEM *********************************************
cylinderRadius = cylRad;
cylinderLength = srho*stemRatio;
[CX,CY,CZ] = cylinder(cylinderRadius,Ncol-1);
CZ = CZ.*cylinderLength; %---- lengthen
%******************************************* CONE == ARROWHEAD *********************************************
coneLength = srho*(1-stemRatio);
[coneX, coneY, coneZ] = cylinder([cylinderRadius*2 0],Ncol-1); %---------- CONE
coneZ = coneZ.*coneLength;
% Translate cone on top of the stem cylinder
coneZ = coneZ + cylinderLength ;
% now close the bottom and add the cone to the stem cylinder surface
bottom = zeros(1,Ncol) ;
CX = [ bottom ; CX ; coneX ] ;
CY = [ bottom ; CY ; coneY ] ;
CZ = [ bottom ; CZ ; coneZ ] ;
Nrow = size(CX,1);
%----- ROTATE
%---- initial rotation to coincide with X-axis
newEll = rotatePoints([0 0 -1], [CX(:), CY(:), CZ(:)]); %CX(:) actually reshape the 2xN matrices in a 2N vert vector, by vertically concatenating each column
CX = reshape(newEll(:,1), Nrow, Ncol);
CY = reshape(newEll(:,2), Nrow, Ncol);
CZ = reshape(newEll(:,3), Nrow, Ncol);
newEll = rotatePoints(deltaValues, [CX(:), CY(:), CZ(:)]);
stemX = reshape(newEll(:,1), Nrow, Ncol);
stemY = reshape(newEll(:,2), Nrow, Ncol);
stemZ = reshape(newEll(:,3), Nrow, Ncol);
%----- TRANSLATE
stemX = stemX + X;
stemY = stemY + Y;
stemZ = stemZ + Z;
%----- DISPLAY
hStem = surf(stemX, stemY, stemZ, 'FaceColor', colorCode, 'EdgeColor', 'none');
%----- DISPLAY
if nargout==1
arrowHandle = hStem ;
end

Drawing rectangles around vertical groups of pixels having the same value

Consider the following visualization of a 7x5 matrix consisting of 3 distinct regions/values:
bL = toeplitz( [zeros(1,5) -2*ones(1,2)], [0 -ones(1,4)] );
hF = figure(); hA = axes(hF);
imagesc(hA,bL); axis(hA,'image'); set(hA,'XTick',[],'YTick',[]);
N = 4; cmap = parula(N); colormap(cmap(1:end-1,:));
Now let's say I "select" 0 or more pixels in each column such that:
Selected pixels can only be chosen in the green region.
Selected pixels are always contiguous.
Selection is performed by assigning a constant new value, which is different from the 3 initial regions.
Several examples of selection (using the value 1):
%Example 1:
cSF = toeplitz([ones(1,1) zeros(1,4) -2*ones(1,2)],[1 -ones(1,4)]);
%Example 2:
oSF = toeplitz( [zeros(1,5) -2*ones(1,2)], [0 -ones(1,4)] );
oSF(end-2:end,find(any(oSF==-2,1),1,'last')+1:end) = 1;
%Example 3:
iSF = toeplitz([ones(1,3) zeros(1,2) -2*ones(1,2)],[1 -ones(1,4)]);
% Plot:
hF = figure();
hP(1) = subplot(1,3,1); imagesc(cSF);
hP(2) = subplot(1,3,2); imagesc(oSF);
hP(3) = subplot(1,3,3); imagesc(iSF);
axis(hP,'image'); set(hP,'XTick',[],'YTick',[]);
My objective is to draw a set of rectangles encompassing "selected" (yellow) pixels belonging to the same column. For the examples above, the results should look like this (respectively):
The way I see it, for the code to be general it should accept: (1) an axes handle where the imagesc should be plotted; (2) a data array; (3) a value found in the data array, representing "chosen" pixels; and optionally the color of the enclosed pixels.
I found some ways of doing this using patch and rectangle (see own answer), but I'm wondering if this can be achieved with fewer function calls or in other ways I hadn't thought of.
Loopless solution using patch:
Here's a solution that generates coordinates for patch without needing a loop:
function column_highlight(hA, data, selectionVal)
assert(nargin >= 2);
if (nargin < 3) || isempty(selectionVal)
selectionVal = 1;
end
nCol = size(data, 2);
data = diff([false(1, nCol); (data == selectionVal); false(1, nCol)]);
[r, c] = find(data);
r = reshape(r-0.5, 2, []);
c = c(1:2:end);
X = [c-0.5 c+0.5 c+0.5 c-0.5].';
Y = r([1 1 2 2], :);
patch(hA, 'XData', X, 'YData', Y, 'FaceColor', 'none');
end
Solution using regionprops:
If you have the Image Processing Toolbox, you can solve this by labeling each masked column section and getting the 'BoundingBox' shape measure using regionprops:
function column_highlight(hA, data, selectionVal)
assert(nargin >= 2);
if (nargin < 3) || isempty(selectionVal)
selectionVal = 1;
end
labelMat = bsxfun(#times, (data == selectionVal), 1:size(data, 2));
coords = regionprops(labelMat, 'BoundingBox');
coords = vertcat(coords.BoundingBox);
coords(:, 3:4) = coords(:, 1:2)+coords(:, 3:4);
X = coords(:, [1 3 3 1]).';
Y = coords(:, [4 4 2 2]).';
patch(hA, 'XData', X, 'YData', Y, 'FaceColor', 'none');
end
A solution using rectangle:
function markStreaksRect(hA, data, selectionVal)
% Check inputs:
assert(nargin >= 2); if nargin < 3 || isempty(selectionVal), selectionVal = 1; end
% Create a mask for "selected" values:
oneMask = data == selectionVal;
% Find the first encountered "selected" element from both the top and the bottom:
[~,I1] = max(oneMask,[],1); [~,I2] = max(flipud(oneMask),[],1);
% Express the "selected" extent as a 2 row vector:
firstLast = [I1; size(oneMask,1)-I2+1].*any(oneMask,1);
% For nonzero extents, plot shifted rectangles:
for ind1 = find(all(firstLast,1))
rectangle(hA,'Position',[ind1-0.5, firstLast(1,ind1)-0.5, 1, diff(firstLast(:,ind1))+1 ]);
end
A solution using patch:
function markStreaksPatch(hA, data, selectionVal)
% Check inputs:
assert(nargin >= 2); if nargin < 3 || isempty(selectionVal), selectionVal = 1; end
% Create a mask for "selected" values:
oneMask = data == selectionVal;
% Find the first encountered "selected" element from both the top and the bottom:
[~,I1] = max(oneMask,[],1); [~,I2] = max(flipud(oneMask),[],1);
% Express the "selected" extent as a 2 row vector:
firstLast = [I1; size(oneMask,1)-I2+1].*any(oneMask,1);
% For nonzero extents, plot shifted patches:
for ind1 = find(all(firstLast,1))
[XX,YY] = meshgrid(ind1-0.5 + [0 1], firstLast(1,ind1)-0.5+[0 diff(firstLast(:,ind1))+1]);
patch(hA, XX(:), [YY(1:2) YY(4:-1:3)], 'y', 'FaceAlpha', 0);
end
The above solutions can be tested using:
function q45965920
iSF = toeplitz([ones(1,3) zeros(1,2) -2*ones(1,2)],[1 -ones(1,4)]);
hF = figure(); hA = axes(hF); imagesc(hA,iSF);
axis(hA,'image'); set(hA,'XTick',[],'YTick',[]);
...then running either markStreaksRect(hA, iSF, 1); or markStreaksPatch(hA, iSF, 1); produces the desired result.

Finding the most common point of intersection among plotted triangles

I plotted a set of triangles using the code below:
A=[1, 1; 1, 5; 3, 9; 4, 2;9,9];
plot(A(:,1),A(:,2),'oc','LineWidth',2,'MarkerSize',5);
axis([0 10 0 10]);
grid on
for ii = 1:size(A, 1) - 1
for jj = ii + 1:size(A, 1)
line([A(ii, 1), A(jj, 1)], [A(ii, 2), A(jj, 2)])
end
end
The problem is, i will like the plot to indicate the region with the highest number of intersections. In this particular code, the region is the black polygon (i had to indicate this region manually).
Please can anyone help out with this problem. Thanks
Here is a variant with a more graphical approach.
Create a grid of points
Check the number of triangles that a point
is inside
Plot the points with highest number of intersecting
triangles
The code
% Create the combination of all points that make the triangles
% This could be used to plot the lines as well
N = size(A,1);
comb = [];
for i = 1:N-2
for j = i+1:N-1
comb = [comb; repmat([i j], N-j,1) (j+1:N)']; %#ok<AGROW>
end
end
nComb = size(comb,1);
% Create a mesh grid
dg = 0.1; % Resolution - tune this!
gridEdge = [min(A);max(A)];
[X, Y] = meshgrid(gridEdge(1,1):dg:gridEdge(2,1), gridEdge(1,2):dg:gridEdge(2,2));
% Check if a point is inside each triangle
[isInside, onEdge] = deal(zeros(numel(X),nComb));
for i = 1:nComb
[isInside(:,i), onEdge(:,i)] = inpolygon(X(:),Y(:),A(comb(i,:),1),A(comb(i,:),2));
end
% Remove points on edge
isInside = isInside - onEdge;
% Get index of points with most intersection
inTri = sum(isInside,2);
idx = find(inTri == max(inTri));
% Plot result
hold on
plot(X(idx),Y(idx),'.')
text(mean(X(idx)),mean(Y(:)),num2str(max(inTri)),'FontSize',20)

3d Ring in Matlab using Patch

I am trying to make a 3d ring in a matlab. Following is something similar to what I am upto:
t = linspace(0,2*pi);
rin = 0.1;
rout = 0.25;
xin = 0.5 + rin*cos(t);% 0.5 is the center of the ring
xout = 0.5 + rout*cos(t);
yin = 0.5 + rin*sin(t);
yout = 0.5 + rout*sin(t);
% Make patch
hp = patch([xout,xin],[yout,yin],'g','linestyle','none','facealpha',0.25);
Now, I want to extend this to the 3d case. I wanted to give height to this ring. But when I try to add a vector [z1,z2] where
z1=0.5*ones(size(xin));
z2=z1;
I have tried different combination of Z1 and Z2 still I am unable to find the solution.
I tend to keep the usage of patch for 2D surfaces of object which are really faceted and if you need control over the properties of every face, otherwise for volumes like you want surf is a much easier object to handle.
The example below shows how to do it with one single surface, but is easily adaptable if you really need to use patch.
To explain step by step I start with the patch you created. I calculate the coordinates of the center line (called ring in the code), then display it (with the starting point highlighted)
%% // Ring properties
ring.x0 = 0.5 ; %// Center of ring
ring.y0 = 0.5 ; %// Center of ring
ring.radius = (0.25+0.1)/2 ; %// Radius of core circle profile
ring.nDiv = 37 ; %// number of divisions for the core circle profile
ring.theta = linspace(0,2*pi,ring.nDiv) ;
ring.X = cos(ring.theta) * ring.radius + ring.x0 ;
ring.Y = sin(ring.theta) * ring.radius + ring.y0 ;
%// plot (optional, just for intermediate visualisation)
hold on ; plot(ring.X,ring.Y) ; plot(ring.X(1),ring.Y(1),'ok')
view(18,72) ; xlabel('X') ; ylabel('Y') ; zlabel('Z') ;
which render:
Then I create a basic cross section:
%% // Create a base SQUARE cross section
Npts = 4 ;
cs.width = 0.25-0.1 ; %// width of each cross section square
cs.height = 0.25 ; %// height of each cross section square
%// first cross section is the the XZ plane
csY0 = zeros(1,Npts) ; %// will be used as base for rotating cross sections
csX = [-cs.width/2 cs.width/2 cs.width/2 -cs.width/2 ] ;
csZ = [-cs.height/2 -cs.height/2 cs.height/2 cs.height/2] ;
This defined a basic square hanging in space around the origin, I'll place the first one in position just to illustrate:
%% // plot (optional, just for intermediate visualisation)
hp0 = patch(csX+ring.X(1),csY0+ring.Y(1),csZ,'r','FaceAlpha',0.5) ;
view(164,38)
Which renders:
Now we just need to replicate this cross section wrapped around the master ring:
%% Generate coordinates for each cross section and merge them
nCS = length(ring.X) ; %// number of cross sections composing the surface
%// pre-allocation is always good
X = zeros( nCS , Npts ) ;
Y = zeros( nCS , Npts ) ;
Z = zeros( nCS , Npts ) ;
for ip = 1:nCS
%// rotate the cross section (around Z axis, around origin)
Rmat = [ cos(ring.theta(ip)) -sin(ring.theta(ip)) ; ...
sin(ring.theta(ip)) cos(ring.theta(ip)) ] ;
csTemp = Rmat * [csX ; csY0] ;
%// translate the coordinates of cross section to final position and store with others
X(ip,:) = csTemp(1,:) + ring.X(ip) ;
Y(ip,:) = csTemp(2,:) + ring.Y(ip) ;
Z(ip,:) = csZ ;
end
Now you have in X,Y and Z the coordinates of points all around the profile you defined, ready to be plotted in one graphical object:
%% // Plot the final surface
hs = surf(X,Y,Z) ;
set(hs,'FaceColor',[.7 .7 .7],'FaceAlpha',0.5,'EdgeAlpha',0.2)
view(155,26)
Which renders:
The 2 nice points about this method are:
Only one graphic object to handle (still versatile though, the CData allows many possibilities)
The cross section can be anything, just define it once, and repeat the method.
To illustrate point 2 above, just replace the paragraph of code %% // Create a base square cross section by this circular cross section:
%% // Create a base CIRCULAR cross section
cs.Ndiv = 13 ; %
cs.radius = (0.25-0.1)/2 ; %// Radius of each cross section circle
cs.rout = 0.25;
cs.theta = linspace(0,2*pi,cs.Ndiv) ;
Npts = length(cs.theta) ;
%// first cross section is the the XZ plane
csY0 = zeros(1,Npts) ; %// will be used as base for rotating cross sections
csX = sin(cs.theta) * cs.radius ;
csZ = cos(cs.theta) * cs.radius ;
The rest of the code is the same, you'll obtain your doughnut:
I included that anyway because that was my first answer, until I realized from the comment that you wanted a cylinder!
Duplicating your annulus and adding two cylinders i get:
%% Config
t = linspace(0,2*pi);
rin = 0.1;
rout = 0.25;
center = [1, 0.5];
xin = rin*cos(t);
xout = rout*cos(t);
yin = rin*sin(t);
yout = rout*sin(t);
z1 = 0;
z2 = 0.24;
%% Plot
clf;
hold on;
bottom = patch(center(1)+[xout,xin], ...
center(2)+[yout,yin], ...
z1*ones(1,2*length(xout)),'');
top = patch(center(1)+[xout,xin], ...
center(2)+[yout,yin], ...
z2*ones(1,2*length(xout)),'');
[X,Y,Z] = cylinder(1,length(xin));
outer = surf(rout*X+center(1), ...
rout*Y+center(2), ...
Z*(z2-z1)+z1);
inner = surf(rin*X+center(1), ...
rin*Y+center(2), ...
Z*(z2-z1)+z1);
set([bottom, top, outer, inner], ...
'FaceColor', [0 1 0], ...
'FaceAlpha', 0.99, ...
'linestyle', 'none', ...
'SpecularStrength', 0.7);
light('Position',[1 3 2]);
light('Position',[-3 -1 3]);
axis vis3d; axis equal; view(3);