Monday, February 27, 2012

MATLAB: Surface plot of nonuniform data

It would be common to get a set of data: [X, Y, Z] for many simulations, and sometime I want to draw it "fancy" in Matlab, using either contour or 3-D surface plot. However, Matlab use a stupid "mesh" to do the job: when you want to draw a contour or surface, you need to run:

command(X, Y, Z), with X, Y, Z has the same size (n*n) dimension.

This is inconvenient for me, so I try to gather some information, how to easily generate a MESH for matlab from a 3-D xyz data.

(This blog is REALLY helpful: http://blogs.mathworks.com/pick/2007/11/02/advanced-matlab-surface-plot-of-nonuniform-data/, does this count a citation? ) 

1. Matlab ONLY use uniform data to do contour plot or surface plot

2. One need to generate a uniform data from the non-uniform data, so that matlab will plot it.


Suppose you save the xyz data into x, y, z, with a length N,

xlin = linspace(min(x),max(x),100);     
%  Generate 100 points linearly between (including) min(x) and max(x)

ylin = linspace(min(y),max(y),100);     
%  Generate 100 points linearly between (including) min(y) and max(y)

[X,Y]=meshgrid(xlin,ylin);
% Generate a MESH using the linear grid :) Finally, get the MESH in matlab

Z=griddata(x,y,z, X,Y,’cubic’);
% ZI = griddata(x,y,z,XI,YI) fits a surface of the form z = f(x,y) to the data in the (usually) nonuniformly spaced vectors (x,y,z). 
% Griddata interpolates this surface at the points specified by (XI,YI) to produce ZI.
% The surface always passes through the data points. 
% XI and YI usually form a uniform grid (as produced by meshgrid)
% The method defines the type of surface fit to the data. 
% The 'cubic' and 'v4' methods produce smooth surfaces while 'linear' and 'nearest' have discontinuities in the first and zero'th derivatives, respectively. 
% All the methods except 'v4' are based on a Delaunay triangulation of the data. If method is [], then the default 'linear' method is used.
% Keep in mind to use the 'cubic'  !!!

% Now you can check the surface and whether it is good generated :) 
mesh(X,Y,Z);
hold on
plot3(x,y,z, '*', 'MarkerSize',15)



Finally ~ No need to worry about this topic in the future:)


Saturday, February 25, 2012

MATLAB Graph: Bit-Mapped Images

Previously, what I learned is to "plot some data", those data are more like X, Y axis data, which is more organized. However, Images, like pictures taken with camera, are more randomly for each pixel to connects.

In Matlab, once a graphics file format image is displayed, it becomes a Handle Graphics image object. Matlab supports:
BMP (Microsoft Windows Bitmap), HDF (Hierarchical Data Format), JPEG (Joint Photographic Experts Group), PCX (Paintbrush), PNG (Portable Network Graphics), TIFF (Tagged Image File Format), XWD (X Window Dump)

+++++
Images in Matlab

MATLAB stores most images as two-dimensional arrays (i.e., matrices), in which each element of the matrix corresponds to a single pixel in the displayed image.
MATLAB supports reading the most commonly used bit depths (bits per pixel) of any of the supported graphics file formats. When the data is in memory, it can be stored as uint8, uint16, or double.
Saving the bit depths in uint8 or uint16 will save a lot of memory space.

+++++
Image Types
In MATLAB, an image consists of a data matrix and possibly a colormap matrix. There are three image types used:

  • indexed image
    • An indexed image consists of a data matrix, X, and a colormap matrix map. Map is an m-by-3 array of class double containing floating-point values in the range [0, 1].
    • Each row of map specifies the red, green, and blue components of a single color.
    • Use "image" to display it
  • intensity (or grayscale) image
    • An intensity image is a data matrix, I, whose values represent intensities within some range.
    • MATLAB stores an intensity image as a single matrix, with each element of the matrix corresponding to one image pixel.
    • MATLAB handles intensity images as indexed images. 
    • Use "imagesc" to display it
  • RGB (or truecolor) image
    • It is stored in MATLAB as an m-by-n-by-3 data array that defines red, green, and blue color components for each individual pixel.
    • Graphics file formats store RGB images as 24-bit images, where the red, green, and blue components are 8 bits each.
    • Use "image" to display it
+++++
Reading, Writing, and Querying Graphics Image Files

  • Load or save a matrix as a MAT-file: load, save
  • Load or save graphics file format image: imread, imwrite
  • Display any image loaded into MATLAB, image, imagesc
  • Utility: imfinfo, ind2rdg
-----------------------------------------------------------------------------------------
Image Type           Display Commands                       Uses Colormap Colors
Indexed                 image(X), colormap(map)              Yes
Intensity                imagesc(I, [0, 1]); colormap(gray)  Yes
RGB(truecolor)     image(RGB)                                    No
-----------------------------------------------------------------------------------------

+++++

The Image Object and Its Properties

Image objects are children of axes objects, as are line, patch, surface, and text objects.
The commands image and imagesc create image objects.

The most important properties of the image object with respect to appearance are CData, CDataMapping, XData, YData, and EraseMode.

CData: The CData property of an image object contains the data array
CDataMapping: The CDataMapping property controls whether an image is indexed or intensity.
XData, YData: The XData and YData properties control the coordinate system of the image. For an m-by-n image, the default XData is [1 n] and the default YData is [1 m].
EraseMode: The EraseMode property controls how MATLAB updates the image on the screen if the image object's CData property changes. The default setting of EraseMode is 'normal'. With this setting, if you change the CData of the image object using the set command, MATLAB erases the image on the screen before redrawing the image using the new CData array.

MATLAB Graph: Animation

This post just shows how a simple animation is constructed.

Two ways to create animated sequence:

  • save a number of different pictures and then play them back as a movie
  • continuously erase & redraw the object on screen
Remember, a movie is not rendered in real time, it is just a playback of previously rendered frames.

Two steps to "save & replay":
  1. use "getframe" to generate each movie frame
  2. use "movie" to run the movie
when one use "getframe" two properties are returned:
  1. cdate: Image data in a uint8 matrix: The matrix has dimensions of height-by-width on indexed-color systems and height-by-width-by-3 on truecolor systems
  2. colormap:  The colormap in an n-by-3 matrix, where n is the number of colors. On truecolor systems, the colormap field is empty. 
Example:
h = uicontrol('style','slider','position',...
    [10 50 20 300],'Min',1,'Max',16,'Value',1)
for k = 1:16
    plot(fft(eye(k+16)))
    axis equal
    set(h,'Value',k)
    M(k) = getframe(gcf);
end

clf
axes('Position',[0 0 1 1])
movie(M,30)

Friday, February 24, 2012

MATLAB Graph: Introduction

All of these stuffs are abstracted from Matlab Help file, re-writing/summarizing them down will enhance my understanding over this part:

Three Components of a Graph:

  • Figure window: display the graph
  • Coordinate system: so that graph is placed within axis, which are contained by the Figure
  • other graph objects: lines and surfaces
Basic Plotting Commands:
  • plot: graph 2-D data with linear scales for both axes
  • plot3: graphe 3-D data with linear scales for both axes
  • loglog, semilogx, lemilogy, plotyy et al. 
Plotting Steps:
  1. Preparing the data                                      [x = 0:0.1:1; y = bessel(1,x);]
  2. Select a window and position a plot region within the window  [figure 1; subplot(2,2,1);]
  3. Call elementary plotting function               [h = plot(x,y)]
  4. Select line and marker characters               [set(h, 'LineWidth', 2, {'LineStyle'}, {'--'} ]
  5. Set axis limit, tick marks, and grid lines     [axis ([0 12 -0.5 1]); grid on;]
  6. Annotate the graph with axis labels, legend and text  [xlabel('Time'); legand(h, 'First')]
  7. export graph                                              [ print -depsc -tiff -r200 myplot]
The Figure Window:
  • MATLAB directs graphics output to a window separated from command window, which is refereed to as Figure
  • Graphics functions automatically create new figure windows if none currently exist. If a figure already exists, MATLAB uses that window.
These are some of the most common matlab graphic process, and there are other specialized figures, such as contour, histogram, et al, which I will not detailed them here.