Wednesday, January 04, 2006

 

Matlab usage

  1. Matlab Introduction
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

Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?