Visualize sparsity pattern with intensity using Matlab spy function - matlab

Matlab has a function spy for visualizing sparsity patterns of graph adjacency matrices.
Unfortunately it does not display the points by taking into account the magnitude of the values in the matrix. It uses a single color with same intensity to display all entries.
I wish to display the same spy plot but with the points "color-coded" like in a heatmap to indicate the magnitude of the entries. How can I do that?

spy function uses plot, which cannot have different marker colors in a lineseries object.
On the other hand, patch object can have different marker colors for different vertices. patch is originally for drawing polygons, but with no face color and no edge color, one can get similar result to plot with no line style.
S = bucky();
[m, n] = size(S);
[X, Y] = meshgrid(1:m, 1:n);
S = (X + Y) .* S;
nonzeroInd = find(S);
[x, y] = ind2sub([m n], nonzeroInd);
figure();
hp = patch(x, y, S(nonzeroInd), ...
'Marker', 's', 'MarkerFaceColor', 'flat', 'MarkerSize', 4, ...
'EdgeColor', 'none', 'FaceColor', 'none');
set(gca, 'XLim', [0, n + 1], 'YLim', [0, m + 1], 'YDir', 'reverse', ...
'PlotBoxAspectRatio', [n + 1, m + 1, 1]);
colorbar();
You can easily use different colormap, e.g., colormap(flipud(hot)).

If your matrix is not very large you could try to view it as an image using imagesc(). (Well you could use it for quite large matrices as well, but the pixels become very small.)
Here is an example of 20 random points in a 100x100 matrix, using colormap hot:
N = 100;
n = 20;
x = randi(N,1,n);
y = randi(N,1,n);
z = randi(N,1,n);
data = sparse(x,y,z);
imagesc(data)
axis square
colormap('hot')
This is the resulting image.
This can be compared to the plot we get using spy(data) where the markers are a bit larger.
If a white background is desired an easy way to achieve this is to flip the colormap:
figure
imagesc(data)
axis square
cmap = flipud(colormap('hot'));
colormap(cmap)
Hack solution redefining spy()
Googling a bit I found this thread at Matlab Central:
Spy with color for values?
There a solution is suggested that redefines spy(). It's however worth noting that (further down in the thread) this solution can also cause Matlab to crash for larger matrices.

I submitted a file on matlab exchange that also performs the spy task with points colored according to their value. Please see here.

Related

How to implement a 3D boolean operation in MATLAB to make an intersection like in Blender (or any other 3D software)?

I am working on creating 3D images from 3 individual binary images, that were taken with 3 cameras. I have a corresponding calibration and know the setup (see below). Since the image preprocessing is mostly done in MATLAB I would like to implement everything there.
The current idea of my code is to extrude the 2D binary image according to the camera calibration. Here's what a typical binary image looks like:
And an extruded image looks like this in MATLAB:
With all 3 cameras extruded and a binning algorithm, I can create my final 3D-shape. This works fine so far, but takes a long time to compute, since I need to create a lot of extrusion steps to get a good surface.
I was thinking now to speed this up by recreating the process I would do in a 3D-modeling software like Blender. There I also extrude the outline of the binary image and create an intersection easily by just creating a spline for the outline, extrude them and use a boolean operator. Here's a Blender example with 2 extruded images:
I have no idea how to implement something like this in MATLAB. I wanted to create two instances of my binary contour at the top and bottom end of the extrusion "tube" and then define faces between the individual points and create an intersection afterwards. The point creation is no problem but the face definition and the intersection (boolean operator) are. Does anyone have an idea how this could be implemented?
This might not be an easy thing to do in MATLAB, but it's possible. I'll outline one set of steps here, using two intersecting cylinders as an example...
Creating a tetrahedral mesh:
The first step is to create a tetrahedral mesh for your extrusion. If your 2D binary image that you're extruding is convex and has no holes, you could do this using the delaunayTriangulation function:
DT = delaunayTriangulation(P);
Here, P contains the coordinate points of the "end caps" of your extrusion (i.e. the faces on each end of your tube). However, when generating tetrahedral meshes, delaunayTriangulation doesn't allow you to specify constrained edges, and as such it can end up filling in holes or concavities in your extrusion. There may be some better mesh-generation alternatives in other toolboxes, such as the Partial Differential Equations Toolbox, but I don't have access to them and can't speak to their applicability.
If automated mesh-generation options don't work, you'll have to build your tetrahedral mesh yourself and pass that data to triangulation. This could be tricky, but I'll show you some steps for how you can do this for a cylinder, which may help you figure it out for more involved shapes. Below, we build a set of coordinate points P1 and an M-by-4 matrix T1 where each row contains indices into the rows of P1 which define one tetrahedron:
% Create circle coordinates for the end caps:
N = 21;
theta = linspace(0, 2*pi, N).';
x = sin(theta(1:(end-1)));
y = cos(theta(1:(end-1)))+0.5;
z = ones(N-1, 1);
% Build tetrahedrons for first cylinder, aligned along the z axis:
P1 = [0 0.5 -1; ... % Center point of bottom face
x y -z; ... % Edge coordinates of bottom face
0 0.5 1; ... % Center point of top face
x y z]; % Edge coordinates of top face
cBottom = ones(N-1, 1); % Row indices for bottom center coordinate
cEdgeBottom1 = (2:N).'; % Row indices for bottom edge coordinates
cEdgeBottom2 = [3:N 2].'; % Shifted row indices for bottom edge coordinates
cTop = cBottom+N; % Row indices for top center coordinate
cEdgeTop1 = cEdgeBottom1+N; % Row indices for top edge coordinates
cEdgeTop2 = cEdgeBottom2+N; % Shifted row indices for top edge coordinates
% There are 3 tetrahedrons per radial slice of the cylinder: one that includes the
% bottom face and half of the side face (all generated simultaneously by the first row
% below), one that includes the other half of the side face (second row below), and one
% that includes the top face (third row below):
T1 = [cEdgeBottom1 cEdgeBottom2 cEdgeTop1 cBottom; ...
cEdgeBottom2 cEdgeTop1 cEdgeTop2 cBottom; ...
cEdgeTop1 cEdgeTop2 cTop cBottom];
TR1 = triangulation(T1, P1);
To better visualize how the cylinder is being divided into tetrahedrons, here's an animation of an exploded view:
Now we can create a second cylinder, offset and rotated so it aligns with the x axis and intersecting the first:
% Build tetrahedrons for second cylinder:
P2 = [P1(:, 3) -P1(:, 2) P1(:, 1)];
T2 = T1;
TR2 = triangulation(T2, P2);
% Plot cylinders:
tetramesh(TR1, 'FaceColor', 'r', 'FaceAlpha', 0.6);
hold on;
tetramesh(TR2, 'FaceColor', 'g', 'FaceAlpha', 0.6);
axis equal;
xlabel('x');
ylabel('y');
zlabel('z');
And here's the plot to visualize them:
Finding the region of intersection:
Once we have tetrahedral representations of the volumes, we can generate a grid of points covering the region of intersection and use the pointLocation function to determine which points are within both cylinders:
nGrid = 101;
[X, Y, Z] = meshgrid(linspace(-1, 1, nGrid));
QP = [X(:) Y(:) Z(:)];
indexIntersect = (~isnan(pointLocation(TR1, QP))) & ...
(~isnan(pointLocation(TR2, QP)));
mask = double(reshape(indexIntersect, [nGrid nGrid nGrid]));
We now have volume data mask that contains zeroes and ones, with the ones defining the region of intersection. The finer you make your grid (by adjusting nGrid), the more accurately this will represent the true region of intersection between the cylinders.
Generating a 3D surface:
You may want to create a surface from this data, defining the boundary of the intersection region. There are a couple ways to do this. One is to generate the surface with isosurface, which you could then visualize using featureEdges. For example:
[F, V] = isosurface(mask, 0.5);
TR = triangulation(F, V);
FE = featureEdges(TR, pi/6).';
xV = V(:, 1);
yV = V(:, 2);
zV = V(:, 3);
trisurf(TR, 'FaceColor', 'c', 'FaceAlpha', 0.8, 'EdgeColor', 'none');
axis equal;
xlabel('x');
ylabel('y');
zlabel('z');
hold on;
plot3(xV(FE), yV(FE), zV(FE), 'k');
And the resulting plot:
Another option is to create a "voxelated" Minecraft-like surface, as I illustrate here:
[X, Y, Z, C] = build_voxels(permute(mask, [2 1 3]));
hSurface = patch(X, Y, Z, 'c', ...
'AmbientStrength', 0.5, ...
'BackFaceLighting', 'unlit', ...
'EdgeColor', 'none', ...
'FaceLighting', 'flat');
axis equal;
view(-37.5, 30);
set(gca, 'XLim', [0 101], 'YLim', [25 75], 'ZLim', [0 102]);
xlabel('x');
ylabel('y');
zlabel('z');
grid on;
light('Position', get(gca, 'CameraPosition'), 'Style', 'local');
And the resulting plot:

How to create a color gradient using a third variable in Matlab? [duplicate]

This question already has answers here:
Change color of 2D plot line depending on 3rd value
(5 answers)
Closed 5 years ago.
How do you create a color gradient in Matlab such that you plot a 2D line plot of y=y(x), and you color it using another variable that also depends on x such that z=z(x). A scatter or point plot is also fine by me.
I would also like to have a colormap legend kind of thing showing the color gradient and it's actual representation of z. This stuff is quite common in visualisation tools such as VisIt and ParaView but I could not yet FIGURE it out in Matlab.
If a scatter plot is fine, you can use the 4th input to scatter:
x = -10:0.01:10;
y = sinc(x);
z = sin(x);
scatter(x,y,[],z,'fill')
where z is the color.
The only way I know of to do this is with a little trick using surf:
% Create some sample data:
x = cumsum(rand(1,20)); % X data
y = cumsum(rand(1,20)); % Y data
z = 1:20; % "Color" data
% Plot data:
surf([x(:) x(:)], [y(:) y(:)], [z(:) z(:)], ... % Reshape and replicate data
'FaceColor', 'none', ... % Don't bother filling faces with color
'EdgeColor', 'interp', ... % Use interpolated color for edges
'LineWidth', 2); % Make a thicker line
view(2); % Default 2-D view
colorbar; % Add a colorbar
And the plot:
To manipulate the color of the line continuously, you'll want to use surface.
While at first look, this function looks most useful for plotting 3d surfaces, it provides more flexibility for line coloring than the basic plot function. We can use the edges of the mesh to plot our line, and take advantage of the vertex colors, C, to render interpolated color along the edge.
You can check out the full list of rendering properties, but the ones you are most likely to want are
'FaceColor', 'none', do not draw the faces
'EdgeColor', 'interp', interpolate between vertices
Here's an example adapted from MATLAB Answers post
x = 0:.05:2*pi;
y = sin(x);
z = zeros(size(x)); % We don't need a z-coordinate since we are plotting a 2d function
C = cos(x); % This is the color, vary with x in this case.
surface([x;x],[y;y],[z;z],[C;C],...
'FaceColor','none',...
'EdgeColor','interp');
Generate a colormap, e.g. jet(10). The example would generate a 10*3 matrix.
Use interp1 to interpolate between the values in the RGB space using your data by setting the first color as the lowest value and the last color as the highest value. This would generate a n*3 matrix where n is the number of data points.
Use scatter with the optional parameter c to plot the points with the interpolated colors.
activate colorbar to show the colorbar.

Draw error bars in Matlab

I have created an example scatter plot with five points in MATLAB as follows:
x = linspace(0,pi,5);
y = cos(x);
scatter(x,y);
In my case, the y-value of each point shall be in a predefined range defined as follows:
y_limits = {[0.9 1.1], [0.6 0.8], [-0.1 0.1], [-0.8 -0.6], [-1.1 -0.9]};
So for example, the y value of point 1 at x = 0 shall be in the range [0.9 1.1].
I would somehow like to draw five vertical boundaries nicely in the same plot perhaps by means of
five vertical lines with endpoints at the respective two limits
five filled vertical areas between the respective two limits
something else that may be more appropriate
I would like to get some suggestions or sample code of people who are more experienced than me in such kind of graphical representations.
You can do this in one line by using the errorbar function
% Your example variables
x = linspace(0,pi,5)';
y = cos(x);
y_limits = [0.9, 1.1; 0.6, 0.8; -0.1, 0.1; -0.8, -0.6; -1.1, -0.9];
% Plot
errorbar(x, y, y - y_limits(:,1), y_limits(:,2) - y, 'x');
% Format: (x, y, negative error, positive error, point style)
Result:
Edit, you can set the line properties of the plot as you call errorbar. For example, you could use larger, blue circle markers with thicker, red error bars
using:
errorbar(x, y, y - y_limits(:,1), y_limits(:,2) - y, 'o', 'MarkerSize', 2, 'MarkerFaceColor', 'b', 'MarkerEdgeColor', 'b', 'Color', 'r', 'LineWidth', 1);
Note for these images I'm using grid on to add the grid. Second result:
Creating a lines is done with the line command.
for i = 1:length(x)
line([x(i) x(i)], [y_limits{i}]);
end
Filled areas can be done with patch or fill. Some reordering of the limits is necessary so that the order given follows a path around the area to be filled. One nice trick is to use the alpha command on those filled areas to create transparency.
hold on
y_corners = reshape([y_limits{:}], 2, length(x)).'; %make an array
y_corners = [y_corners(:,1); flipud(y_corners(:,2))]; %corners follow a path around the shape
fill([x fliplr(x)], y_corners, 'blue');
alpha(0.5);

How to interpolate and plot a 4-Dimensional hamburger?

I have solved the heat equation in octave via finite difference and produced the following 3-D plot whose point colors correspond to the temperatures in each element of my three dimensional hamburger.
My computational resources limit the resolution at which I may solve my burger. Thus the only way to get the plot I want is to make my scatter3 points huge blobs of color and it looks kind of bad.
[x,y,z] = meshgrid(1:nx,1:ny,1:nz) % Defines a grid to plot on
scatter3(x(:), y(:), z(:), 40, burgermatrix(:), 's', 'filled')% Point color=value
What I want is a nice gorgeous smooth rectangular prism like this:
So I figure I need to somehow interpolate between the 3D points that I have. Can anyone help me figure out how to do this?
I might be missing something obvious, but here's the example from octave's help slice:
[x, y, z] = meshgrid (linspace (-8, 8, 32));
v = sin (sqrt (x.^2 + y.^2 + z.^2)) ./ (sqrt (x.^2 + y.^2 + z.^2));
slice (x, y, z, v, [], 0, []);
[xi, yi] = meshgrid (linspace (-7, 7));
zi = xi + yi;
slice (x, y, z, v, xi, yi, zi);
shading interp; %addition by me
Isn't this exactly what you need? You have your grid (x,y,z), your solutions (T), so you just need to plot it slicing along [0 0 1] etc. Something like
[xi yi]=meshgrid(unique(x),unique(y));
slice (x, y, z, T, xi, yi, max(z(:))*ones(size(xi)));
and the same for cuts along the two other axes. (Obviously the unique calls should be substituted with the vectors you already have from which you constructed the 3d mesh in the first place.)
NOTE: By the way, you should really consider changing the default (jet) colormap. I was yesterday enlightened by a colleague about the viridis colormap made by the SciPy people, see for instance this post and video link therein. Their reasoning is overwhelming, and their colormap is beautiful. This should define it: viridis, although I haven't tried it myself yet.
(If it wasn't for jet, I'd tell you that your temperature profile seems strongly 1d. Do you happen to have periodic boundary conditions along the vertical walls and homogeneous (i.e. constant) boundary conditions along the horizontal ones?)

Matlab Ploting with different color for iso-surface

I was trying use the code shown below to plot in such a way that each iso-surface will be different in color and there will be a color bar at the right. I made a ss(k) color matrix for different colors. Number of iso-surfaces is 10 but I have only 8 colors. That's why I wrote ss(9)='r' and ss(10)='r'.
I need a solution to plot the iso-surface with different color and bar at the right side.
ss=['y','m','c','r','g','b','w','k','r','r']
k=1;
for i=.1:.1:1
p=patch(isosurface(x,y,z,v,i));
isonormals(x,y,z,v,p)
hold on;
set(p,'FaceColor',ss(k),'EdgeColor','none');
daspect([1,1,1])
view(3); axis tight
camlight
lighting gouraud
k=k+1;
end
Another possibility is to draw the patches with direct color-mapping (by setting the property 'CDataMapping'='direct'), while assigning the 'CData' of each patch to an index in the colormap of your choice. This is in fact recommended for maximum graphics performance.
Consider the following example:
%# volumetric data, and iso-levels we want to visualize
[x,y,z,v] = flow(25);
isovalues = linspace(-2.5,1.5,6);
num = numel(isovalues);
%# plot isosurfaces at each level, using direct color mapping
figure('Renderer','opengl')
p = zeros(num,1);
for i=1:num
p(i) = patch( isosurface(x,y,z,v,isovalues(i)) );
isonormals(x,y,z,v,p(i))
set(p(i), 'CData',i);
end
set(p, 'CDataMapping','direct', 'FaceColor','flat', 'EdgeColor','none')
%# define the colormap
clr = hsv(num);
colormap(clr)
%# legend of the isolevels
%#legend(p, num2str(isovalues(:)), ...
%# 'Location','North', 'Orientation','horizontal')
%# fix the colorbar to show iso-levels and their corresponding color
caxis([0 num])
colorbar('YTick',(1:num)-0.5, 'YTickLabel',num2str(isovalues(:)))
%# tweak the plot and view
box on; grid on; axis tight; daspect([1 1 1])
view(3); camproj perspective
camlight; lighting gouraud; alpha(0.75);
rotate3d on
I also included (commented) code to display the legend, but I found it to be redundant, and a colorbar looks nicer.
Matlab usually plots different iso-surfaces in different colors automatically, so you don't need to care about that. What kind of bar do you need? A colorbar or a legend? Either way, it is just to use the colorbar or legend function..
%Create some nice data
[x y z] = meshgrid(1:5,1:5,1:5);
v = ones(5,5,5);
for i=1:5
v(:,:,i)=i;
end
v(1:5,3:5,2)=1
v(1:5,4:5,3)=2
%Plot data
for i=1:5
isosurface(x,y,z,v,i)
end
%Add legend and/or colorbar
legend('one','Two','Three','Four')
colorbar
Since the color bar encodes value->color, it is impossible to do what you ask for, unless there is no intersection in z-values between all pairs of surfaces. So the solution below assumes this is the case. If this is not the case, you can still achieve it by adding a constant value to each surface, so to separate the surfaces along the z axis, and eliminate any intersection.
The solution is based on constructing a colormap matrix of piecewise constant values, distributed similarly to the z values of your surfaces. So for example, if you have 3 surfaces, the first has z values between 1 and 10, the 2nd between 11 and 30, and the 3rd between 31 and 60, you should do something like this (I plot in 2D for simplicity)
r = [1 0 0];
g = [0 1 0];
b = [0 0 1];
cmap = [r(ones(10,1),:); g(ones(20,1),:); b(ones(30,1),:)];
z1 = 1:10;
z2 = 11:30;
z3 = 31:60;
figure; hold on
plot(z1,'color',r)
plot(z2,'color',g)
plot(z3,'color',b)
colorbar
colormap(cmap)
More complex colormaps (i.e, more colors) can be constructed with different mixtures of red, green, and blue (http://www.mathworks.com/help/techdoc/ref/colorspec.html)