Sunday, January 29, 2006
subs Usage
>> help subs
SUBS Symbolic substitution.
SUBS(S) replaces all the variables in the symbolic expression S with
values obtained from the calling function, or the MATLAB workspace.
SUBS(S,NEW) replaces the free symbolic variable in S with NEW.
SUBS(S,OLD,NEW) replaces OLD with NEW in the symbolic expression S.
OLD is a symbolic variable, a string representing a variable name, or
a string (quoted) expression. NEW is a symbolic or numeric variable
or expression.
If OLD and NEW are cell arrays of the same size, each element of OLD is
replaced by the corresponding element of NEW. If S and OLD are scalars
and NEW is an array or cell array, the scalars are expanded to produce
an array result. If NEW is a cell array of numeric matrices, the
substitutions are performed elementwise (i.e., subs(x*y,{x,y},{A,B})
returns A.*B when A and B are numeric).
If SUBS(S,OLD,NEW) does not change S, then SUBS(S,NEW,OLD) is tried.
This provides backwards compatibility with previous versions and
eliminates the need to remember the order of the arguments.
SUBS(S,OLD,NEW,0) does not switch the arguments if S does not change.
Examples:
Single input:
Suppose a = 980 and C1 = 3 exist in the workspace.
The statement
y = dsolve('Dy = -a*y')
produces
y = exp(-a*t)*C1
Then the statement
subs(y)
produces
ans = 3*exp(-980*t)
Single Substitution:
subs(a+b,a,4) returns 4+b.
Multiple Substitutions:
subs(cos(a)+sin(b),{a,b},{sym('alpha'),2}) returns
cos(alpha)+sin(2)
Scalar Expansion Case:
subs(exp(a*t),'a',-magic(2)) returns
[ exp(-t), exp(-3*t)]
[ exp(-4*t), exp(-2*t)]
Multiple Scalar Expansion:
subs(x*y,{x,y},{[0 1;-1 0],[1 -1;-2 1]}) returns
[ 0, -1]
[ 2, 0]
See also SUBEXPR
Overloaded methods
help sym/subs.m
Saturday, January 28, 2006
Hydrogen Molecules Energy
syms r R a positive; syms u; for iter=1:1:5 Pl=simplify(1/2^iter/factorial(iter)*diff((u*u-1)^iter, u, iter)); lPHIr=simplify(int(exp(-sqrt(4*a*r*u-r*r-4*a*a))*Pl, u, -1, 1)/2); %PHI=simplify(int(exp(-r)*r^(1-iter)*PHIr, r, 0, inf)) lPHI_R1=simplify(int(exp(-r)*lPHIr*r^(iter+2), r, 0, R)) lPHI_R1=simplify(lPHI_R1/R^(iter+1)) lPHI_R2=simplify(int(exp(-r)*lPHIr/r^(iter-1), r, R, inf)) lPHI_R2=simplify(lPHI_R2*R^iter) lPsiR=lPHI_R1+lPHI_R2 lPhiR=simplify(int(exp(-sqrt(4*a*R*u-R*R-4*a*a))*Pl, u, -1, 1)/2); PsiR=int(exp(-sqrt(4*R*a*mu-R*R-4*a*a)), mu, -1, 1)/2; Vabab=int(PHIl*R^(iter+2)*PsiR, R, 0, inf) end
Friday, January 27, 2006
Legendre Polynomials
>> help legendre
LEGENDRE Associated Legendre function.
P = LEGENDRE(N,X) computes the associated Legendre functions
of degree N and order M = 0, 1, ..., N, evaluated for each element
of X. N must be a scalar integer and X must contain real values
between -1 <= X <= 1.
If X is a vector, P is an (N+1)-by-L matrix, where L = length(X).
The P(M+1,i) entry corresponds to the associated Legendre function
of degree N and order M evaluated at X(i).
In general, the returned array has one more dimension than X.
Each element P(M+1,i,j,k,...) contains the associated Legendre
function of degree N and order M evaluated at X(i,j,k,...).
There are three possible normalizations, LEGENDRE(N,X,normalize)
where normalize is 'unnorm','sch' or 'norm'.
The default, unnormalized associated Legendre functions are:
P(N,M;X) = (-1)^M * (1-X^2)^(M/2) * (d/dX)^M { P(N,X) },
where P(N,X) is the Legendre polynomial of degree N. Note that
the first row of P is the Legendre polynomial evaluated at X
(the M == 0 case).
SP = LEGENDRE(N,X,'sch') computes the Schmidt semi-normalized
associated Legendre functions SP(N,M;X). These functions are
related to the unnormalized associated Legendre functions
P(N,M;X) by:
SP(N,M;X) = P(N,X), M = 0
= (-1)^M * sqrt(2*(N-M)!/(N+M)!) * P(N,M;X), M > 0
NP = LEGENDRE(N,X,'norm') computes the fully-normalized
associated Legendre functions NP(N,M;X). These functions are
normalized such that
/1
|
| [NP(N,M;X)]^2 dX = 1 ,
|
/-1
and are related to the unnormalized associated Legendre
functions P(N,M;X) by:
NP(N,M;X) = (-1)^M * sqrt((N+1/2)*(N-M)!/(N+M)!) * P(N,M;X)
Examples:
1. legendre(2, 0.0:0.1:0.2) returns the matrix:
| x = 0 x = 0.1 x = 0.2
------|---------------------------------------------
m = 0 | -0.5000 -0.4850 -0.4400
m = 1 | 0 -0.2985 -0.5879
m = 2 | 3.0000 2.9700 2.8800
2. X = rand(2,4,5); N = 2;
P = legendre(N,X);
so that size(P) is 3x2x4x5 and
P(:,1,2,3) is the same as legendre(N,X(1,2,3)).
Thursday, January 05, 2006
Spherical Harmonics@Matlab
Wednesday, January 04, 2006
Matlab usage
vector 1. index從1開始: v(1), v(100) 2. v = [1:8] 3. v = [2:.25:4] 4. v(1:3)-v(2:4) 5. u = [0:-1:-4] 也可以遞減 decrement 6. 可以將變數的命名空間 存成檔案但是附檔名一定是要為.mat save uv.mat clear "var" load uv.mat 7. diary save.txt ... enter commands here... diary 可以儲存命令列
8.C Style Read/Write
In addition to the high level read/write commands detailed above, Matlab allows C style file access. This is extremely helpful since the output generated by many home grown programs is in binary format due to disk space considerations. This is an advanced subject, and we do not go into great detail here. Instead we look at the basic commands. After looking at this overview we highly recommend that you look through the relevant help files. This will help fill in the missing blanks.
The basic idea is that you open a file, execute the relevant reads and writes on a file, and then close a file. One other common task is to move the file pointer to point to a particular place in the file, and there are two commands, fseek and ftell to help.
Here we give a very simple example. In the example, a file called "laser.dat" is opened. The file identifier is kept track of using a variable called fp. Once the file is opened the file position is moved to a particular place in the file, denoted pos, and two double precision numbers are read. Once that is done the position within the file is stored, and the file is closed.
fp = fopen('laser.dat','r');
fseek(fp,pos,'bof');
tmp = fread(fp,2,'double');
pos = ftell(fp);
fclose(fp);
>> help fileformats Readable file formats. Data formats Command Returns MAT - MATLAB workspace load Variables in file. CSV - Comma separated numbers csvread Double array. DAT - Formatted text importdata Double array. DLM - Delimited text dlmread Double array. TAB - Tab separated text dlmread Double array. Spreadsheet formats XLS - Excel worksheet xlsread Double array and cell array. WK1 - Lotus 123 worksheet wk1read Double array and cell array. Scientific data formats CDF - Common Data Format cdfread Cell array of CDF records FITS - Flexible Image Transport System fitsread Primary or extension table data HDF - Hierarchical Data Format hdfread HDF or HDF-EOS data set Movie formats AVI - Movie aviread MATLAB movie. Image formats TIFF - TIFF image imread Truecolor, grayscale or indexed image(s). PNG - PNG image imread Truecolor, grayscale or indexed image. HDF - HDF image imread Truecolor or indexed image(s). BMP - BMP image imread Truecolor or indexed image. JPEG - JPEG image imread Truecolor or grayscale image. GIF - GIF image imread Indexed image. PCX - PCX image imread Indexed image. XWD - XWD image imread Indexed image. CUR - Cursor image imread Indexed image. ICO - Icon image imread Indexed image. RAS - Sun raster image imread Truecolor or indexed. PBM - PBM image imread Grayscale image. PGM - PGM image imread Grayscale image. PPM - PPM image imread Truecolor image. Audio formats AU - NeXT/Sun sound auread Sound data and sample rate. SND - NeXT/Sun sound auread Sound data and sample rate. WAV - Microsoft Wave sound wavread Sound data and sample rate. See also IOFUN
>> help clear
CLEAR Clear variables and functions from memory.
CLEAR removes all variables from the workspace.
CLEAR VARIABLES does the same thing.
CLEAR GLOBAL removes all global variables.
CLEAR FUNCTIONS removes all compiled M- and MEX-functions.
CLEAR ALL removes all variables, globals, functions and MEX links.
CLEAR ALL at the command prompt also removes the Java packages
import list.
CLEAR IMPORT removes the Java packages import list at the command
prompt. It cannot be used in a function.
CLEAR CLASSES is the same as CLEAR ALL except that class definitions
are also cleared. If any objects exist outside the workspace (say in
userdata or persistent in a locked m-file) a warning will be issued
and the class definition will not be cleared. CLEAR CLASSES must be
used if the number or names of fields in a class are changed.
CLEAR VAR1 VAR2 ... clears the variables specified. The wildcard
character '*' can be used to clear variables that match a pattern.
For instance, CLEAR X* clears all the variables in the current
workspace that start with X.
If X is global, CLEAR X removes X from the current workspace,
but leaves it accessible to any functions declaring it global.
CLEAR GLOBAL X completely removes the global variable X.
CLEAR FUN clears the function specified. If FUN has been locked
by MLOCK it will remain in memory. Use a partial path (see
PARTIALPATH) to distinguish between different overloaded versions of
FUN. For instance, 'clear inline/display' clears only the INLINE
method for DISPLAY, leaving any other implementations in memory.
CLEAR ALL, CLEAR FUN, or CLEAR FUNCTIONS also have the side effect of
removing debugging breakpoints and reinitializing persistent variables
since the breakpoints for a function and persistent variables are
cleared whenever the m-file changes or is cleared.
Use the functional form of CLEAR, such as CLEAR('name'),
when the variable name or function name is stored in a string.
See also WHO, WHOS, MLOCK, MUNLOCK, PERSISTENT.
>> help plot
PLOT Linear plot.
PLOT(X,Y) plots vector Y versus vector X. If X or Y is a matrix,
then the vector is plotted versus the rows or columns of the matrix,
whichever line up. If X is a scalar and Y is a vector, length(Y)
disconnected points are plotted.
PLOT(Y) plots the columns of Y versus their index.
If Y is complex, PLOT(Y) is equivalent to PLOT(real(Y),imag(Y)).
In all other uses of PLOT, the imaginary part is ignored.
Various line types, plot symbols and colors may be obtained with
PLOT(X,Y,S) where S is a character string made from one element
from any or all the following 3 columns:
b blue . point - solid
g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star
y yellow s square
k black d diamond
v triangle (down)
^ triangle (up)
<> triangle (right)
p pentagram
h hexagram
For example, PLOT(X,Y,'c+:') plots a cyan dotted line with a plus
at each data point; PLOT(X,Y,'bd') plots blue diamond at each data
point but does not draw any line.
PLOT(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,...) combines the plots defined by
the (X,Y,S) triples, where the X's and Y's are vectors or matrices
and the S's are strings.
For example, PLOT(X,Y,'y-',X,Y,'go') plots the data twice, with a
solid yellow line interpolating green circles at the data points.
The PLOT command, if no color is specified, makes automatic use of
the colors specified by the axes ColorOrder property. The default
ColorOrder is listed in the table above for color systems where the
default is blue for one line, and for multiple lines, to cycle
through the first six colors in the table. For monochrome systems,
PLOT cycles over the axes LineStyleOrder property.
PLOT returns a column vector of handles to LINE objects, one
handle per line.
The X,Y pairs, or X,Y,S triples, can be followed by
parameter/value pairs to specify additional properties
of the lines.
See also SEMILOGX, SEMILOGY, LOGLOG, PLOTYY, GRID, CLF, CLC, TITLE,
XLABEL, YLABEL, AXIS, AXES, HOLD, COLORDEF, LEGEND, SUBPLOT, STEM.
Overloaded methods
help ntree/plot.m
help dtree/plot.m
help wvtree/plot.m
help rwvtree/plot.m
help edwttree/plot.m
>> help repmat
REPMAT Replicate and tile an array.
B = repmat(A,M,N) creates a large matrix B consisting of an M-by-N
tiling of copies of A.
B = REPMAT(A,[M N]) accomplishes the same result as repmat(A,M,N).
B = REPMAT(A,[M N P ...]) tiles the array A to produce a
M-by-N-by-P-by-... block array. A can be N-D.
REPMAT(A,M,N) when A is a scalar is commonly used to produce
an M-by-N matrix filled with A's value. This can be much faster
than A*ONES(M,N) when M and/or N are large.
Example:
repmat(magic(2),2,3)
repmat(NaN,2,3)
See also MESHGRID.
>> help rand
RAND Uniformly distributed random numbers.
RAND(N) is an N-by-N matrix with random entries, chosen from
a uniform distribution on the interval (0.0,1.0).
RAND(M,N) and RAND([M,N]) are M-by-N matrices with random entries.
RAND(M,N,P,...) or RAND([M,N,P,...]) generate random arrays.
RAND with no arguments is a scalar whose value changes each time it
is referenced. RAND(SIZE(A)) is the same size as A.
RAND produces pseudo-random numbers. The sequence of numbers
generated is determined by the state of the generator. Since MATLAB
resets the state at start-up, the sequence of numbers generated will
be the same unless the state is changed.
S = RAND('state') is a 35-element vector containing the current state
of the uniform generator. RAND('state',S) resets the state to S.
RAND('state',0) resets the generator to its initial state.
RAND('state',J), for integer J, resets the generator to its J-th state.
RAND('state',sum(100*clock)) resets it to a different state each time.
This generator can generate all the floating point numbers in the
closed interval [2^(-53), 1-2^(-53)]. Theoretically, it can generate
over 2^1492 values before repeating itself.
MATLAB Version 4.x used random number generators with a single seed.
RAND('seed',0) and RAND('seed',J) cause the MATLAB 4 generator to be used.
RAND('seed') returns the current seed of the MATLAB 4 uniform generator.
RAND('state',J) and RAND('state',S) cause the MATLAB 5 generator to be used.
See also RANDN, SPRAND, SPRANDN, RANDPERM.
>> help function
FUNCTION Add new function.
New functions may be added to MATLAB's vocabulary if they
are expressed in terms of other existing functions. The
commands and functions that comprise the new function must
be put in a file whose name defines the name of the new
function, with a filename extension of '.m'. At the top of
the file must be a line that contains the syntax definition
for the new function. For example, the existence of a file
on disk called STAT.M with:
function [mean,stdev] = stat(x)
%STAT Interesting statistics.
n = length(x);
mean = sum(x) / n;
stdev = sqrt(sum((x - mean).^2)/n);
defines a new function called STAT that calculates the
mean and standard deviation of a vector. The variables
within the body of the function are all local variables.
See SCRIPT for procedures that work globally on the work-
space.
A subfunction that is visible to the other functions in the
same file is created by defining a new function with the FUNCTION
keyword after the body of the preceding function or subfunction.
For example, avg is a subfunction within the file STAT.M:
function [mean,stdev] = stat(x)
%STAT Interesting statistics.
n = length(x);
mean = avg(x,n);
stdev = sqrt(sum((x-avg(x,n)).^2)/n);
%-------------------------
function mean = avg(x,n)
%MEAN subfunction
mean = sum(x)/n;
Subfunctions are not visible outside the file where they are defined.
Normally functions return when the end of the function is reached.
A RETURN statement can be used to force an early return.
See also SCRIPT, RETURN, VARARGIN, VARARGOUT, NARGIN, NARGOUT,
INPUTNAME, MFILENAME.
SVD
p = poly(A) where {A}nxn is an nxn matrix returns an n+1 element row vector whose elements are the coefficients of the characteristic polynomial, det(lambda-A). The coefficients are ordered in descending powers: lambda^n+C2*lambda^(n-1)+...Cn*lambda+Cn+1, where a vector c has n+1 components.
p = poly(r) where r is a vector returns a row vector whose elements are the coefficients of the polynomial whose roots are the elements of r.
Expansion of (lambda-lambda1)(lambda-lambda2)...(lambda-lambdan):
z = eig(A); c = zeros(n+1,1); c(1) = 1; for j = 1:n c(2:j+1) = c(2:j+1)-z(j)*c(1:j); end