Issue with scatter3 - matlab

Probably it's scatter3 what I don't understand. I have a matrix of which all slices but the last are NaNed (M(:,:,1:10) = NaN;) and then it's permuted switching first and last dimension. So there are only values in M(11,:,:). I expect all plotted values to be in the Y-Z plane at x==11, but the plot looks differently (see code and picture below). Any explanations?
M = rand(22,55,11);
M(:,:,1:10) = NaN;
M = permute(M,[3 2 1]);
shape = size(M)
[x, y, z] = meshgrid(1:shape(1), 1:shape(2), 1:shape(3));
scatter3(x(:), y(:), z(:), 4, M(:), 'fill');
view([60 60]);
xlabel('X ', 'FontSize', 16);
ylabel('Y ', 'FontSize', 16);
zlabel('Z ', 'FontSize', 16);

The explanation is that meshgrid switches x and y:
From meshgrid documentation:
MESHGRID is like NDGRID except that the order of the first two input
and output arguments are switched (i.e., [X,Y,Z] = MESHGRID(x,y,z)
produces the same result as [Y,X,Z] = NDGRID(y,x,z)).
At first sight, this should result in a plot with values in the X-Z plane at y==11 (i.e. x and y interchanged with respect to what you initially expected). But note that your code treats x and y sizes incorrectly (because of meshgrid). This has the additional effect that the x and y coordinates get "shuffled" and you don't see a plane (even in X-Z), but rather a lattice.
So the solution is to use ndgrid, which doesn't do any switching. Just replace "meshgrid" by "ndgrid" in your code. The resulting figure is now as expected:

Related

MATLAB how to plot contour with special LineWidth for certain value

I have the following script:
close all; clear all; clc;
x = linspace(-2*pi,2*pi);
y = linspace(0,4*pi);
[X,Y] = meshgrid(x,y);
Z = sin(X)+cos(Y);
values = -10:0.5:10;
figure
[C,hh] = contour(X, Y, Z, values,'r', 'LineWidth',1);
clabel(C, hh, values, 'fontsize',7)
As you can see in the contour lines, all of the lines are plotted with LineWidth = 1. I would like to plot special line for the value = 0, with LineWidth = 2, how to set it? Thanks a lor for your help.
You will need to make a secondary contour plot to highlight the desired contour levels. The MathWorks has an example of this in the documentation.
For your case we'll have something like the following:
% Generate sample data
x = linspace(-2*pi,2*pi);
y = linspace(0,4*pi);
[X,Y] = meshgrid(x,y);
Z = sin(X)+cos(Y);
values = -10:0.5:10;
% Generate initial contour plot
figure
[C,hh] = contour(X, Y, Z, values,'r', 'LineWidth',1);
clabel(C, hh, values, 'fontsize',7)
% Generate second contour plot with desired contour level highlighted
hold on
contour(X, Y, Z, [0 0], 'b', 'LineWidth', 2);
hold off
Which returns the following:
Not that I've specified the single contour level as a vector. This is explained by the documentation for contour:
contour(Z,v) draws a contour plot of matrix Z with contour lines at the data values specified in the monotonically increasing vector v. To display a single contour line at a particular value, define v as a two-element vector with both elements equal to the desired contour level. For example, to draw contour lines at level k, use contour(Z,[k k])
If you want to highlight multiple levels then this does not apply (e.g. contour(X, Y, Z, [-1 0], 'b', 'LineWidth', 2) to highlight -1 and 0)

How to fit an elliptic cone to a set of data?

I have a set of 3d data (300 points) that create a surface which looks like two cones or ellipsoids connected to each other. I want a way to find the equation of a best fit ellipsoid or cone to this dataset. The regression method is not important, the easier it is the better. I basically need a way, a code or a matlab function to calculate the constants of the elliptic equation for these data.
You can also try with fminsearch, but to avoid falling on local minima you will need a good starting point given the amount of coefficients (try to eliminate some of them).
Here is an example with a 2D ellipse:
% implicit equation
fxyc = #(x, y, c_) c_(1)*x.^2 + c_(2).*y.^2 + c_(3)*x.*y + c_(4)*x + c_(5).*y - 1; % free term locked to -1
% solution (ellipse)
c_ = [1, 2, 1, 0, 0]; % x^2, y^2, x*y, x, y (free term is locked to -1)
[X,Y] = meshgrid(-2:0.01:2);
figure(1);
fxy = #(x, y) fxyc(x, y, c_);
c = contour(X, Y, fxy(X, Y), [0, 0], 'b');
axis equal;
grid on;
xlabel('x');
ylabel('y');
title('solution');
% we sample the solution to have some data to fit
N = 100; % samples
sample = unique(2 + floor((length(c) - 2)*rand(1, N)));
x = c(1, sample).';
y = c(2, sample).';
x = x + 5e-2*rand(size(x)); % add some noise
y = y + 5e-2*rand(size(y));
fc = #(c_) fxyc(x, y, c_); % function in terms of the coefficients
e = #(c) fc(c).' * fc(c); % squared error function
% we start with a circle
c0 = [1, 1, 0, 0, 0];
copt = fminsearch(e, c0)
figure(2);
plot(x, y, 'rx');
hold on
fxy = #(x, y) fxyc(x, y, copt);
contour(X, Y, fxy(X, Y), [0, 0], 'b');
hold off;
axis equal;
grid on;
legend('data', 'fit');
xlabel('x'); %# Add an x label
ylabel('y');
title('fitted solution');
The matlab function fit can take arbitrary fit expressions. It takes a bit of figuring out the parameters but it can be done.
You would first create a fittype object that has a string representing your expected form. You'll need to work out the expression yourself that best fits what you're expecting, I'm going to take a cone expression from the Mathworld site for an example and rearrange it for z
ft = fittype('sqrt((x^2 + y^2)/c^2) + z_0', ...
'independent', {'x', 'y'}, 'coeff', {'c', 'z_0'});
If it's a simple form matlab can work out which are the variables and which the coefficients but with something more complex like this you'd want to give it a hand.
The 'fitoptions' object holds the configuration for the methods: depending on your dataset you might have to spend some time specifying upper and lower bounds, starting values etc.
fo = fitoptions('Upper', [one, for, each, of, your, coeffs, in, the, order, they, appear, in, the, string], ...
'Lower', [...], `StartPoint', [...]);
then get the output
[fitted, gof] = fit([xvals, yvals], zvals, ft, fo);
Caveat: I've done this plenty with 2D datasets and the docs state it works for three but I haven't done that myself so the above code might not work, check the docs to make sure you've got your syntax right.
It might be worth starting with a simple fit expression, something linear, so that you can get your code working. Then swap the expression out for the cone and play around until you get something that looks like what you're expecting.
After you've got your fit a good trick is that you can use the eval function on the string expression you used in your fit to evaluate the contents of the string as if it was a matlab expression. This means you need to have workspace variables with the same names as the variables and coefficients in your string expression.

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.

Plotting MATLAB values in two different colors

Anyway, I wish to plot two column vectors, filled with random numbers with no negative values in them, on a 2D plot(x and y).
The 'x-vector' I can leave as it is, but with the 'y vector', I wish to plot that any y values that is equal to zero as a different color(Say red) to the other positive non-zero values(Say blue).
Please try to keep solution relatively simple, if possible, as I myself am relatively new to MATLAB as well as to this site.
I'm not sure what you mean by 2D plot but I assuming you mean just a normal curve. Try this:
x = rand(10, 1);
y = rand(10, 1);
y([5 8]) = 0; %Force a couple of values to be 0 for visualisation
t = 1:10;
plot(t, x);
hold on
plot(t, y, 'g');
ind = y == 0; %Make a logical index that masks all the value where y is not 0
plot(t(ind), y(ind), 'r*');

3D plot of part of hyperboloid

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.