Thursday, January 31, 2008

Matlab (2) - Drawing

Basic functions:
plot mesh

How to query handles of a graph?
findall
findobj
When a handle is obtained, then following function can be used to set properties of the object corresponding to the handle.
set() 

Other functions related to manipulation of handles: 
gcf: get current graph. If no figure exists, MATLAB creates one and returns its handle
gca: get current axes handle.
gco: Return handle of current object
gcbo: Return handle of object whose callback is executing
root object: Root object properties
figure: creates a new figure object using default property values. Figure objects are the individual windows on the screen in which MATLAB displays graphical output.
delete: Delete files or graphics objects
close: deletes the current figure or the specified figure(s).
cla: deletes from the current axes all graphics objects.
clf: deletes from the current figure all graphics objects including axes.
clc: Clear Command Window.
clear:Remove items from workspace, freeing up system memory
home: moves the cursor to the upper-left corner of the Command Window. You can use the scroll bar to see the history of previous functions.
reset: resets all properties having factory defaults on the object identified by h.
hold: determines whether new graphics objects are added to the graph or replace objects in the graph.
ishold: Returns current hold state
newplot: prepares a figure and axes for subsequent graphics commands

load: Load workspace variables from disk
save: Save workspace variables on disk
who, whos: List variables in workspace
workspace:
what: List MATLAB files in current directory
which: Locate functions and files
type: Display contents of file
path: View or change MATLAB directory search path
savepath: Save current MATLAB search path to pathdef.m file
rmpath: Remove directories from MATLAB search path
restoredefaultpath: Restore default MATLAB search path
pathdef: List of directories in MATLAB search path
partialpath:Partial pathname description.A partial pathname is a pathname relative to the MATLAB path, matlabpath. It is used to locate private and method files, which are usually hidden, or to restrict the search for files when more than one file with the given name exists.
fileparts: Return filename parts
fullfile:Build full filename from parts
genpath: Generate path string
pathsep: Return path separator for current platform
filesep: Return directory separator for current platform
addpath: Add directories to MATLAB search path

File operations:
fprintf: Write formatted data to file
fscanf: Read formatted data from file
fclose: Close one or more open files
fopen: Open file, or obtain information about open files
ferror: Query MATLAB about errors in file input or output
fread: Read binary data from file
fwrite: Write binary data to file
fseek: Set file position indicator
ftell: Get file position indicator
feof: Test for end-of-file
fgetl: Read line from file, discarding newline character
fgets: Read line from file, keeping newline character


sprintf
sscanf
int2str
num2str
str2num
hex2num
hex2dec
dec2bin
bin2dec
dec2hex
num2hex
mat2str

format
textread
disp
text

Tools:
pathtool: Open Set Path dialog box to view and change MATLAB path
imtool:

To see the list of factory defaults, use the statement
get(0,'factory')

 

more: Control paged output for Command Window
diary: Save session to file. The diary function creates a log of keyboard input and the resulting text output.
evalc: Evaluate MATLAB expression with capture
eval: Execute string containing MATLAB expression
evalin: Execute MATLAB expression in specified workspace
feval: Evaluate function

function_handle(@):Handle used in calling functions indirectly. E.g. handle = @functionname
functions: Return information about function handle
func2str: Construct function name string from function handle
str2func" Construct function handle from function name string
builtin: Execute built-in function from overloaded method. E.g. builtin('pi'). This function is useful if some of your functions/variables have the same names as built-in functions/variables.
class: Create object or return class of object. E.g.
isa: Determine if input is object of given class. E.g. isa(rand(3,4),'double')

assignin: Assign value to variable in specified workspace

try: Attempt to execute block of code, and catch errors
catch: Specify how to respond to error in try statement.
rethrow:Reissue error
lasterror: Return last error message and related information
lasterr: Return last error message
lastwarn: Return last warning message
warning: Display warning message
error: Display error message
warndlg: Display warning dialog box
dialog: Create and display dialog box
errordlg: Create and display an error dialog box
helpdlg: Create and display help dialog box
questdlg: Create and display question dialog box
inputdlg: Create and display input dialog box
msgbox: Create and display message box
pagesetupdlg: Display page setup dialog box
end: Terminate block of code, or indicate last index of array

dbstop: Set breakpoints
printdlg: Display print dialog box
print, printopt: Create hardcopy output
printpreview:Preview figure to be printed
textwrap: Return wrapped string matrix for given uicontrol

break, for, if, return, switch, while

display: Overloaded method to display text or array
disp: Display text or arrayrat
rats:Rational fraction approximation

isnumeric:Determine if input is numeric array
isfloat isinteger

floor
round
ceil

spy: Visualize sparsity pattern
gplot: Plot set of nodes using an adjacency matrix
sparse: Create sparse matrix
diag: Diagonal matrices and diagonals of a matrix
tril: Lower triangular part of a matrix
triu: Upper triangular part of a matrix
spdiags: Extract and create sparse band and diagonal matrices
full: Convert sparse matrix to full matrix
issparse: Determine if input is sparse
nnz: Number of nonzero matrix elements
nonzeros: Nonzero matrix elements
nzmax: Amount of storage allocated for nonzero matrix elements
size: Array dimensions
isempty:Determine if array is empty
numel: Number of elements in array or subscripted array expression
prod: Product of array elements
cumprod: Cumulative product
cumsum: Cumulative sum
sum
diff: Differences and approximate derivatives
length: Length of vector
ndims: Number of array dimensions
find: Find indices and values of nonzero elements

subsasgn:Overloaded method for A(I)=B, A{I}=B, and A.field=B
subsref:Overloaded method for A(I), A{I} and A.field
substruct:Create structure argument for subsasgn or subsref

exist: Check if variables or functions are defined
computer: Return information about computer on which MATLAB is running
getenv ispc isunix isstudent ver version license

lookfor: Search for keyword in all help entries
doc docopt
help helpwin helpbrowser web

regexp, regexpi: Match regular expression
regexprep: Replace string using regular expression

nargin, nargout: Return number of function arguments

strfind: Find one string within another
findstr: Find string within another, longer string
strmatch: Find possible matches for string
strcmp, strcmpi, strncmp, strncmpi, strvcat

DB family
dbtype: List M-file with line numbers

Monday, January 28, 2008

<pre class="languageName:nocontrols" name="code"> code </pre>
indent paragraph: <div class="indentparagraph"> content goes here </div>

A Groovy sample

Sometimes, I use MS visual studio to write programs. MS VS automatically generates additional files and directories which are not necessary when I release my code. For example, debug directory and .ncb file. When I finish my program, I want to delete these unnecessary files/directories. To delete them manually is not a good choice considering number of programs I have. So I decide to write a Groovy script to do this task and following is my code.

/**
 * This Groovy script is used to delete directories named 'debug'.
 * Usually, this directory is generated by MS Visual Studio when
 * you compile your code in debug mode. After you release your 
 * code, debug information can be discarded. Or else, it occupies
 * non-trivial amount of hard disk space.
 * Moreover, MS VS generates .ncb files. 
 * Besides debug directory and .ncb file, you can easily change 
 * the pattern of files/directories you want to delete.
 */
 
def baseDir = 'E:\\my_program'
dirPattern = /[d|D][e|E][b|B][u|U][g|G]/
fileNamePattern = /.*\.ncb$/

/** This closure delete a specified directory or file 
 * Note: here File means a regular file or a directory.
 */
deleteFile= {
 currentObj ->
 if( currentObj.isDirectory() ){
  currentDir.eachFile{
   currentFile ->
   if( currentFile.isFile() ){
    //first file
    if( currentFile.delete() == false )
     println "file " + currentFile + " failed to be deleted"
   }else if( currentFile.isDirectory() ){
    //then recursively delete dirs
    deleteDir( currentFile )
   }
  }
 }
 //delete this dir
 if( currentObj.delete() == false )
  println "dir " + currentDir + " failed to be deleted"
}

/** delele directories corresponding to pattern specified by variable
 *  dirPattern.
 */
deleteDirs ={
 _baseDir ->
 _baseDir.eachDir{
  currentDir ->
  def dirName = currentDir.getName()
  if( dirName ==~ dirPattern){
   //find it, just delete it
   deleteFile(currentDir)
  }else//recursivly look for it
   deleteDirs(currentDir)
 }
}

/** delele files corresponding to pattern specified by variable
 *  fileNamePattern.
 */
deleteFiles ={
 _baseDir ->
 _baseDir.eachFile{
  currentFile ->
  if( currentFile.isFile() ){
   def fileName = currentFile.getName()
   println fileName
   if( fileName ==~ fileNamePattern ){
    //find it, just delete it
    deleteFile(currentFile)
   }
  }else//recursivly look for it
   deleteFiles(currentFile)
 }
}

/** Sample usage */
deleteDirs(new File(baseDir))
deleteFiles(new File(baseDir));

Tuesday, January 22, 2008

Matlab

Some issues in the course of using Matlab:
(1) random number generation
    functions:
        rand:
            generate random numbers in range [0, 1];
        randn:
             Random numbers are drawn from a normal distribution with mean zero and standard deviation one. So generated numbers may be negative.

Usage hints:
    In description above, those functions ouput decimal numbers. If you want to generate integers in range, following usage may be useful:
    output = ceil(max.*rand(n1, n2, ...ni))
    output = min + ceil((max-min).*rand(n1,n2,...ni))

Some key points from Matlab help:
   The sequence of numbers produced by RAND is determined by the internal state of the generator. Setting the generator to the same fixed state allows computations to be repeated.  Setting the generator to different states leads to unique computations, however, it does not improve any statistical properties. Since MATLAB resets the state at start-up, RAND will generate the same sequence of numbers in each session unless the state is changed.
So, it is a better to set the initial state of random number generator before random numbers are generated. This can be done in following format:
    rand('state', sum(100*clock));

More random number generation functions which use specific statistic models:
betarnd 贝塔分布的随机数生成器
binornd 二项分布的随机数生成器
chi2rnd 卡方分布的随机数生成器
exprnd 指数分布的随机数生成器
frnd f分布的随机数生成器
gamrnd 伽玛分布的随机数生成器
geornd 几何分布的随机数生成器
hygernd 超几何分布的随机数生成器
lognrnd 对数正态分布的随机数生成器
nbinrnd 负二项分布的随机数生成器
ncfrnd 非中心f分布的随机数生成器
nctrnd 非中心t分布的随机数生成器
ncx2rnd 非中心卡方分布的随机数生成器
normrnd 正态(高斯)分布的随机数生成器
poissrnd 泊松分布的随机数生成器
raylrnd 瑞利分布的随机数生成器
trnd 学生氏t分布的随机数生成器
unidrnd 离散均匀分布的随机数生成器
unifrnd 连续均匀分布的随机数生成器
weibrnd 威布尔分布的随机数生成器
(2)permutation
This topic is related to how to generate permutations.
functions:
   (1) randperm(n)
        a random permutation of the integers 1:n.
(3) Dimension rearrangement
functions:
    (1) permute(A, dim_order)
        This function is useful when you want to adjust order of different dimensions.
    (2) ipermute(A, dim_order)
        Inverse permute the dimensions of an array.
        If B = ipermute(A, dim_order) then A=permute(B,dim_order).
(4) Matrix metadata retrieval
functions:
    (1) ndims
        Number of array dimensions. It is equal to length(size(array)).
    (2) size
(5) Matrix data retrieval
functions:
    (1) find
    (2) nonzeros
    (3) min
    (4) max
(6) Array index conversion
    (1) sub2ind
    (2) ind2sub
(7) Array generation
    (1) zeros
    (2) ones
    (3) linspace
    (4) logspace
(8) Array transformation
    (1) reshapce
    (2) shiftdim
    (3) circshift
    (4) squeeze
    (5) repmat
(9) Bitwise operations
    (1) bitshift
(10) Image related
    (1) imread, imwrite
(11) color related
    (1) rgb2gray, rgb2hsv, rgb2ind, rgb2ntsc, rgb2ycbcr

Sunday, January 06, 2008

Probabilistic algorithms

Recently, I read some articles which describe probabilistic(randomized) algorithms I have not heard of before. This cluster of algorithms are really interesting. There are four main categories: Monte Carlo algorithms, Las Vegas algorithms, Sherwood algorithms and Numerical approximation algorithms.
This article(http://www.cs.man.ac.uk/~david/courses/advalgorithms/probabilistic.pdf) describes probabilistic algorithms with concrete examples. It is a good tutorial for newbies.
Here, I would like to excerpt part of the original article.
(1) Monte Carlo algorithms
"Algorithms which always return a result, but the result may not always be correct. We attempt to minimise the probability of an incorrect result, and using the random element, multiple runs of the algorithm will reduce the probability of incorrect results."
Examples:
(*)Majority element in an array
(*)Matrix multiplication(whether A*B=C)
(*)Testing the primality of numbers
(*)Deciding set equality
(2) Las Vegas algorithms
"Algorithms that never return an incorrect result, but may not produce results at all on some runs. Again, we wish to minimise the probability of no result, and, because of the random element, multiple runs will reduce the probability of no result. "
Examples:
(*) Eight Queens Problem
(*) Factorization of integers
(3) Sherwood algorithms
"Algorithms which always return a result and the correct result, but where a random element increases the eciency, by avoiding or reducing the probability of worst-case behaviour. Useful for algorithms which have a poor worst-case behaviour but a good average-case behaviour."
Examples:
(*)Quicksort
  choose a random pivot or randomly shuffle the input numbers.
(4)Numerical approximation algorithms
"Here the random element allows us to get approximate numerical results, often much faster than direct methods, and multiple runs will provide increasing approximation."
Examples:
(*) Calculation of integrals

Start to use this blog as well

From now on, some articles will be posted at this blog. Most posts will be related to computer science.