3D plot of part of hyperboloid - matlab

I would like to plot a 3D figure of a hyperbole that is cut down at the bottom of it in the following way (figure)
any ideas?

OK, here's my stab at your problem. This is the experimental script I've been using:
%%# first part
%#------------------
clf
%# use cylinder to get unit cone
[x,y,z] = cylinder( linspace(1, 0, 1e3), 1e3);
%# intersect the cone with this surface
inds = z < (cos(x).*sin(pi*y/2)+1)/4;
x(inds) = NaN; %# remove all corresponding
y(inds) = NaN; %# indices, in all arrays
z(inds) = NaN;
%# Now plot the cone. Note that edges are ugly when
%# using a large number of points
surf(x, y, z, 'edgecolor', 'none');
%%# second part
%#------------------
hold on
%# the surface to intersect the cone with
f = #(x,y) (cos(x).*sin(pi*y/2)+1)/4;
%# add the surfacfe to the cone plot
[x,y] = meshgrid( linspace(-1,1, 1e3) );
surf(x,y, f(x,y), 'edgecolor', 'none')
The first part shows a cone intersected with a curve. You might want to tinker a bit with the curve to get the overall shape right, which is what the second part is for.
If you want a paraboloid (or other), just use
[x,y] = meshgrid( linspace(-1,1, 1e3) );
z = 1-x.^2-y.^2; %# or whatever other equation
instead of the cylinder command.

Related

How can I fill an area below a 3D graph in MATLAB?

I created the following 3d plot in MATLAB using the function plot3:
Now, I want to get a hatched area below the "2d sub-graphs" (i.e. below the blue and red curves). Unfortunately, I don't have any idea how to realize that.
I would appreciate it very much if somebody had an idea.
You can do this using the function fill3 and referencing this answer for the 2D case to see how you have to add points on the ends of your data vectors to "close" your filled polygons. Although creating a pattern (i.e. hatching) is difficult if not impossible, an alternative is to simply adjust the alpha transparency of the filled patch. Here's a simple example for just one patch:
x = 1:10;
y = rand(1, 10);
hFill = fill3(zeros(1, 12), x([1 1:end end]), [0 y 0], 'b', 'FaceAlpha', 0.5);
grid on
And here's the plot this makes:
You can also create multiple patches in one call to fill3. Here's an example with 4 sets of data:
nPoints = 10; % Number of data points
nPlots = 4; % Number of curves
data = rand(nPoints, nPlots); % Sample data, one curve per column
% Create data matrices:
[X, Y] = meshgrid(0:(nPlots-1), [1 1:nPoints nPoints]);
Z = [zeros(1, nPlots); data; zeros(1, nPlots)];
patchColor = [0 0.4470 0.7410]; % RGB color for patch edge and face
% Plot patches:
hFill = fill3(X, Y, Z, patchColor, 'LineWidth', 1, 'EdgeColor', patchColor, ...
'FaceAlpha', 0.5);
set(gca, 'YDir', 'reverse', 'YLim', [1 nPoints]);
grid on
And here's the plot this makes:

How to find the area of an arbitrary shape contained within a circle using MATLAB

I have an arbitrary shape, of which the exterior boundary has been traced in MATLAB using bwboundaries. Using regionprops, I can calculate the total area enclosed by this shape.
However, I want to know the area for only the parts of the shape that fall within a circle of known radius R centered at coordinates [x1, y1]. What is the best way to accomplish this?
There are a few ways to approach this. One way you could alter the mask before performing bwboundaries (or regionprops) so that it only includes pixels which are within the given circle.
This example assumes that you already have a logical matrix M that you pass to bwboundaries.
function [A, boundaries] = traceWithinCircle(M, x1, y1, R);
%// Get pixel centers
[x,y] = meshgrid(1:size(M, 1), 1:size(M, 2));
%// Compute their distance from x1, y1
distances = sqrt(sum(bsxfun(#minus, [x(:), y(:)], [x1, y1]).^2, 2));
%// Determine which are inside of the circle with radius R
isInside = distances <= R;
%// Set the values outside of this circle in M to zero
%// This will ensure that they are not detected in bwboundaries
M(~isInside) = 0;
%// Now perform bwboundaries on things that are
%// inside the circle AND were 1 in M
boundaries = bwboundaries(M);
%// You can, however, get the area by simply counting the number of 1s in M
A = sum(M(:));
%// Of if you really want to use regionprops on M
%// props = regionprops(M);
%// otherArea = sum([props.Area]);
end
And as an example
%// Load some example data
data = load('mri');
M = data.D(:,:,12) > 60;
%// Trace the boundaries using the method described above
B = traceWithinCircle(M, 70, 90, 50);
%// Display the results
figure;
hax = axes();
him = imagesc(M, 'Parent', hax);
hold(hax, 'on');
colormap gray
axis(hax, 'image');
%// Plot the reference circle
t = linspace(0, 2*pi, 100);
plot(x1 + cos(t)*R, y1 + sin(t)*R);
%// Plot the segmented boundaries
B = bwboundaries(M);
for k = 1:numel(B)
plot(B{k}(:,2), B{k}(:,1), 'r');
end

PCA on a 3D image to obtain 3 principal axes

I have an anatomical volume image (B), which is an indexed image i,j,k:
B(1,1,1)=0 %for example.
The file contains only 0s and 1s.
I can visualize it correctly with isosurface:
isosurface(B);
I would like to cut the volume at some coordinate in j (it is different for each volume).
The problem is that the volume is tilted vertically, it maybe has 45% degrees, so the cut will not be following the anatomical volume.
I would like to obtain a new orthogonal coordinate system for the data, so my plane in coordinate j would cut the anatomical volume in a more accurate way.
I've been told to do it with PCA, but I don't have a clue how to do it, and reading the help pages haven't been of help. Any direction will be welcome!
EDIT:
I have been following the recommendations, and now I got a new volume, zero-centered, but I think that axes don't follow the anatomical image as they should. These are the pre and post images:
This is the code I used to create the images (I took some code from the answer and the idea from the comments):
clear all; close all; clc;
hippo3d = MRIread('lh_hippo.mgz');
vol = hippo3d.vol;
[I J K] = size(vol);
figure;
isosurface(vol);
% customize view and color-mapping of original volume
daspect([1,1,1])
axis tight vis3d;
camlight; lighting gouraud
camproj perspective
colormap(flipud(jet(16))); caxis([0 1]); colorbar
xlabel x; ylabel y; zlabel z
box on
% create the 2D data matrix
a = 0;
for i=1:K
for j=1:J
for k=1:I
a = a + 1;
x(a) = i;
y(a) = j;
z(a) = k;
v(a) = vol(k, j, i);
end
end
end
[COEFF SCORE] = princomp([x; y; z; v]');
% check that we get exactly the same image when going back
figure;
atzera = reshape(v, I, J, K);
isosurface(atzera);
% customize view and color-mapping for the check image
daspect([1,1,1])
axis tight vis3d;
camlight; lighting gouraud
camproj perspective
colormap(flipud(jet(16))); caxis([0 1]); colorbar
xlabel x; ylabel y; zlabel z
box on
% Convert all columns from SCORE
xx = reshape(SCORE(:,1), I, J, K);
yy = reshape(SCORE(:,2), I, J, K);
zz = reshape(SCORE(:,3), I, J, K);
vv = reshape(SCORE(:,4), I, J, K);
% prepare figure
%clf
figure;
set(gcf, 'Renderer','zbuffer')
% render isosurface at level=0.5 as a wire-frame
isoval = 0.5;
[pf,pv] = isosurface(xx, yy, zz, vv, isoval);
p = patch('Faces',pf, 'Vertices',pv, 'FaceColor','none', 'EdgeColor',[0.5 1 0.5]);
% customize view and color-mapping
daspect([1,1,1])
axis tight vis3d;view(-45,35);
camlight; lighting gouraud
camproj perspective
colormap(flipud(jet(16))); caxis([0 1]); colorbar
xlabel x; ylabel y; zlabel z
box on
Can anybody provide a hint what might be happening? It seems that the problem might be the reshape command, Is it possible that I am canceling out the job previously done?
Not sure about PCA, but here is an example showing how to visualize a 3D scalar volume data, and cutting the volume at a tilted plane (non-axis aligned). Code is inspired by this demo in the MATLAB documentation.
% volume data
[x,y,z,v] = flow();
vv = double(v < -3.2); % threshold to get volume with 0/1 values
vv = smooth3(vv); % smooth data to get nicer visualization :)
xmn = min(x(:)); xmx = max(x(:));
ymn = min(y(:)); ymx = max(y(:));
zmn = min(z(:)); zmx = max(z(:));
% let create a slicing plane at an angle=45 about x-axis,
% get its coordinates, then immediately delete it
n = 50;
h = surface(linspace(xmn,xmx,n), linspace(ymn,ymx,n), zeros(n));
rotate(h, [-1 0 0], -45)
xd = get(h, 'XData'); yd = get(h, 'YData'); zd = get(h, 'ZData');
delete(h)
% prepare figure
clf
set(gcf, 'Renderer','zbuffer')
% render isosurface at level=0.5 as a wire-frame
isoval = 0.5;
[pf,pv] = isosurface(x, y, z, vv, isoval);
p = patch('Faces',pf, 'Vertices',pv, ...
'FaceColor','none', 'EdgeColor',[0.5 1 0.5]);
isonormals(x, y, z, vv, p)
% draw a slice through the volume at the rotated plane we created
hold on
h = slice(x, y, z, vv, xd, yd, zd);
set(h, 'FaceColor','interp', 'EdgeColor','none')
% draw slices at axis planes
h = slice(x, y, z, vv, xmx, [], []);
set(h, 'FaceColor','interp', 'EdgeColor','none')
h = slice(x, y, z, vv, [], ymx, []);
set(h, 'FaceColor','interp', 'EdgeColor','none')
h = slice(x, y, z, vv, [], [], zmn);
set(h, 'FaceColor','interp', 'EdgeColor','none')
% customize view and color-mapping
daspect([1,1,1])
axis tight vis3d; view(-45,35);
camlight; lighting gouraud
camproj perspective
colormap(flipud(jet(16))); caxis([0 1]); colorbar
xlabel x; ylabel y; zlabel z
box on
Below is the result showing the isosurface rendered as wire-frame, in addition to slicing planes both axes-aligned and one rotated. We can see that the volume space on the inside of the isosurface has values equal to 1, and 0 on the outside
I don't think that PCA solves your problem. If you apply PCA to your data it will give you three new axes. These axes are called principal components (PCs). They have the property that the first PC has the largest variance when the data is projected on it. The second PC must also has the largest variance when data is projected on it subject to the constraint that it should be orthogonal to the first, the third PC is similar.
Now the question is when you project your data into the new coordinate system (defined by the PCs) will it match the anatomical volume? Not necessarily and most probably will not. The right axes for your data do not have the optimization objective of PCA.
Sorry, I tried to answer to #Tevfik-Aytekin, but the answer is too long.
Hopefully this answer will be useful for somebody:
Hi #Tevfik, thanks for your answer. I've struggling for days with this same problem, and I think I got it right now.
I think that the difference respect to what you are saying is that I am working with coordinates. When I perform PCA over my coordinates, I get a 3x3 transformation matrix for my data (COEFF matrix, which is unitary and orthogonal, it is just a rotation matrix), so I know that I get exactly the same volume when transformed.
These are the steps I followed:
I had a (I,J,K), 3D volume.
As per #werner suggestion, I changed it to a 4 column matrix (x,y,z,v), size (I*J*K, 4).
Eliminated the coordinates (x,y,z) when v == 0, and v too. So right now, size is (original volume, 3). Only the coordinates with value 1, so the length of the vector is the volume of the figure.
Perform PCA to obtain COEFF and SCORE.
COEFF is a 3x3 matrix. It is unitary and orthogonal, it is a rotation matrix for my volume data.
I did the editing in the PCA1 axis (i.e. delete al values when COEFF(1) is bigger than some-value). This was my problem, I wanted to cut the volume perpendicular to the main axis.
This was enough for me, the reamining coordinates are giving me the volume I wanted. But:
I didn't need to go back, as I just needed the remaining volume, but
In order to go back, I just had to reconstruct the original coordinates. So first I transformed the remaining coordinates with SCORE*COEFF'.
Then I created again a (I*J*K, 4) matrix, making the v column = 1 only when the transformed coordinates matched the new matrix (with ismember, option 'row').
I created the indexed volume back using reshape(v, I, J, K).
If I visualize the new volume back, it is cut perpendicular to the main geometric axes of the figure, just as I needed.
Please, I would really like to hear any comment or suggestion on the method.

Graphing a parameterized 3D circle in MATLAB

I'm new to MATLAB and have a fundamental problem that I'm having issues finding online resources for. I have an equation for a circle: C = center + (radius*cos(theta)) + (radius*sin(theta)). I want to graph this circle IN ADDITION to other things I'm graphing beforehand...all in 3D. I've tried using theta = linspace(0,2*pi) but then in constructing my equation for the circle it says matrix sizes don't agree! If you could offer any help that would be great!
Here's an example of plotting a circle with a given radius and center (and assuming the circle lies in the plane z = 0):
radius = 2; %# Define your radius
center = [1 2]; %# Define your circle center [Cx Cy]
theta = linspace(0,2*pi); %# Create an array of theta values
X = center(1)+radius.*cos(theta); %# Create the X values for the circle
Y = center(2)+radius.*sin(theta); %# Create the Y values for the circle
Z = zeros(size(X)); %# Create the Z values for the circle (needed
%# for 3D plotting)
hold on; %# Add to the current existing plot
plot3(X,Y,Z); %# Plot your circle in 3D
And here are some links to online resources that should be a good starting point for learning the basics of plotting in MATLAB:
Using Basic Plotting Functions in MATLAB
PLOT function documentation
PLOT3 function documentation
HOLD function documentation
Since circle is fundamentally a 2D entity, you'll need to generate the points representing it to some known 2D plane embedded in 3D space. Then you'll be able to rotate, scale and translate it as you wish.
A simple demonstration code hopefully makes it clear:
n= 78; theta= linspace(0, 2* pi, n); c= [1 2 3]'; r= sqrt(2);
points= r*[cos(theta); sin(theta); zeros(1, n)]+ repmat(c, 1, n);
plot3(points(1,:), points(2,:), points(3,:), 's-')
axis equal, hold on
R= rref([rand(3) eye(3)]); R= R(:, 4: 6);
points= R* points;
plot3(points(1,:), points(2,:), points(3,:), 'ro')
I am not sure what you are trying to do, but consider this example:
theta = linspace(0,2*pi,100);
C = [0;0];
r = 1;
p = bsxfun(#plus, r.*[cos(theta);sin(theta)], C);
plot(p(1,:), p(2,:), '.-')
axis equal

Texture mapping in MATLAB

I have points in 3D space and their corresponding 2D image points. How can I make a mesh out of the 3D points, then texture the triangle faces formed by the mesh?
Note that the function trisurf that you were originally trying to use returns a handle to a patch object. If you look at the 'FaceColor' property for patch objects, you can see that there is no 'texturemap' option. That option is only valid for the 'FaceColor' property of surface objects. You will therefore have to find a way to plot your triangular surface as a surface object instead of a patch object. Here are two ways to approach this:
If your data is in a uniform grid...
If the coordinates of your surface data represent a uniform grid such that z is a rectangular set of points that span from xmin to xmax in the x-axis and ymin to ymax in the y-axis, you can plot it using surf instead of trisurf:
Z = ... % N-by-M matrix of data
x = linspace(xmin, xmax, size(Z, 2)); % x-coordinates for columns of Z
y = linspace(ymin, ymax, size(Z, 1)); % y-coordinates for rows of Z
[X, Y] = meshgrid(x, y); % Create meshes for x and y
C = imread('image1.jpg'); % Load RGB image
h = surf(X, Y, Z, flipdim(C, 1), ... % Plot surface (flips rows of C, if needed)
'FaceColor', 'texturemap', ...
'EdgeColor', 'none');
axis equal
In order to illustrate the results of the above code, I initialized the data as Z = peaks;, used the built-in sample image 'peppers.png', and set the x and y values to span from 1 to 16. This resulted in the following texture-mapped surface:
If your data is non-uniformly spaced...
If your data are not regularly spaced, you can create a set of regularly-spaced X and Y coordinates (as I did above using meshgrid) and then use one of the functions griddata or TriScatteredInterp to interpolate a regular grid of Z values from your irregular set of z values. I discuss how to use these two functions in my answer to another SO question. Here's a refined version of the code you posted using TriScatteredInterp (Note: as of R2013a scatteredInterpolant is the recommended alternative):
x = ... % Scattered x data
y = ... % Scattered y data
z = ... % Scattered z data
xmin = min(x);
xmax = max(x);
ymin = min(y);
ymax = max(y);
F = TriScatteredInterp(x(:), y(:), z(:)); % Create interpolant
N = 50; % Number of y values in uniform grid
M = 50; % Number of x values in uniform grid
xu = linspace(xmin, xmax, M); % Uniform x-coordinates
yu = linspace(ymin, ymax, N); % Uniform y-coordinates
[X, Y] = meshgrid(xu, yu); % Create meshes for xu and yu
Z = F(X, Y); % Evaluate interpolant (N-by-M matrix)
C = imread('image1.jpg'); % Load RGB image
h = surf(X, Y, Z, flipdim(C, 1), ... % Plot surface
'FaceColor', 'texturemap', ...
'EdgeColor', 'none');
axis equal
In this case, you have to first choose the values of N and M for the size of your matrix Z. In order to illustrate the results of the above code, I initialized the data for x, y, and z as follows and used the built-in sample image 'peppers.png':
x = rand(1, 100)-0.5; % 100 random values in the range -0.5 to 0.5
y = rand(1, 100)-0.5; % 100 random values in the range -0.5 to 0.5
z = exp(-(x.^2+y.^2)./0.125); % Values from a 2-D Gaussian distribution
This resulted in the following texture-mapped surface:
Notice that there are jagged edges near the corners of the surface. These are places where there were too few points for TriScatteredInterp to adequately fit an interpolated surface. The Z values at these points are therefore nan, resulting in the surface point not being plotted.
If your texture is already in the proper geometry you can just use regular old texture mapping.
The link to the MathWorks documentation of texture mapping:
http://www.mathworks.com/access/helpdesk/help/techdoc/visualize/f0-18164.html#f0-9250
Re-EDIT: Updated the code a little:
Try this approach (I just got it to work).
a=imread('image.jpg');
b=double(a)/255;
[x,y,z]=peaks(30); %# This is a surface maker that you do have
%# The matrix [x,y,z] is the representation of the surface.
surf(x,y,z,b,'FaceColor','texturemap') %# Try this with any image and you
%# should see a pretty explanatory
%# result. (Just copy and paste) ;)
So [x,y,z] is the 'surface' or rather a matrix containing a number of points in the form (x,y,z) that are on the surface. Notice that the image is stretched to fit the surface.