What Is Matlab
What Is Matlab
o o o
It stands for MATrix LABoratory It is developed by The Mathworks, Inc. (http://www.mathworks.com) It is an interactive, integrated, environment for numerical computations for symbolic computations (via Maple) for scientific visualizations It is a high-level programming language Program runs in interpreted, as opposed to compiled, mode
MATLAB Characteristics
Programming language based (principally) on matrices. Slow (compared with fortran or C) because it is an interpreted language, i.e. not precompiled. Avoid for loops; instead use vector form (see section on vector technique below)
whenever possible.
o o o o
Automatic memory management, i.e., you dont have to declare arrays in advance. Intuitive, easy to use. Compact (array handling is fortran90-like). Shorter program development time than traditional programming languages such as
Fortran and C. o Can be converted into C code via MATLAB compiler for better efficiency (may be ).
Many application-specific toolboxes available. Coupled with Maple for symbolic computations. On multicore computers, certain operations may be processed in parallel autonomously when
MATLAB Preliminaries
Latest version is MATLAB 7.12.0 (The IBM Twister runs version 5.3.1) Invoke by typing matlab at system prompt (% matlab). If MATLAB is successfully invoked, prompt becomes >>. Enter quit at MATLAB prompt to exit ( >> quit). Online help.
help % lists available packages/toolboxes on system. help package_name % lists available functions in named package. help function_name % instructions on named function. lookfor keywords % search for keywords that best describe the function. helpdesk % html format docs.
More online help If you cant find what you need with the above help commands, you can go to the Mathworks website to search further.
MATLAB Functions
Rules on Variable and Function Names
Variable/Function name o begins with a LETTER, e.g., A2z. o can be a mix of letters, digits, and underscores (e.g., vector_A, but not vector-A (since - is a reserved char). o is case sensitive, e.g., NAME, Name, name are 3 distinct variables. o must not be longer than 31 characters. Suggestion: Since MATLAB distinguishes one function from the next by their file names, name files the same as function names to avoid confusion. Use only lowercase letter to be consistent with MATLABs convention.
File name Files that contain MATLAB commands should be named with a suffix of .m, e.g., something.m. These include, but not restricted to, script m-files and function m-files. (See Files Types for details) Note: To use it, just refer to it by name, without the suffix, e.g.,
>> something
Special Characters
There are a number of special reserved characters used in MATLAB for various purposes. Some of these are used asarithmetic operators, namely, +, -, *, / and . While others perform a multitude of purposes: % anything after % (and until end of line) is treated as comments, e.g.,
>> !ls -l
; delimits statements; suppresses screen output, e.g.,
>> x = [1:2:9]'; % x changed from row vector to column vector If the vector/matrix is complex, "'" results in complex conjugation and matrix transposition.
, command delimiter, e.g.,
>> x = 3:3:9
x=
>> y = 3*ones(3,1)'
y= 3 3 3
>> z =x./y
z= 1 2 3
Note that many of these characters have multiple functionalities (function overloading) depending on the context, e.g., * is used for scalar multiply, matrix multiply and wild card as seen above.
performs matrix transposition; when applied to a complex matrix, it includes elemental conjugations followed by a matrix transposition and . perform matrix and elemental left division
x=45*pi/180; % convert degrees to radians a=sin(x); % compute sine 45 degrees b=cos(x); % compute cosine 45 degrees disp('sin(45*pi/180)') % print header disp(a) % print result
o
function m-files ( variables are local unless appear on function declaration line).
function mean=avg(x) % Usage: >> mean=avg(x); % x - input matrix of which an average is sought % mean - output; the average of x (sum(x)/n) n = size(x); % find out the size of the matrix N = prod(n); % number of elements in x mean = sum(x)/N; % the average
o o
mat-file mex-file
A = B + C;
For sufficiently large matrix operations, this latter method is vastly superior in performance. More examples
A=
8 3 4
1 5 9
6 7 2
>> b = 1:3
b=
ans =
3 4
5 9
7 2
2 3
>> [A; b]
ans =
8 3 4 1
1 5 9 2
6 7 2 3
>> x = 1:5
x=
>> A = 2*ones(3,3)
A=
2 2 2
2 2 2
2 2 2
>> y = x'; >> n = 3; >> B = y(:,ones(n,1)) % more general than B = y(:,[1 1 1]) >> % or B=[y y y];
B=
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
>> A = magic(3)
A=
8 3 4
1 5 9
6 7 2
B=
8 3 4
6 7 2
1 5 9
>> A(:,2) = []
A=
3 4
7 2
MATLAB Graphics
MATLAB is an interactive environment in which you can program as well as visualize your computations. It includes a set of high-level graphical functions for: Line plots (plot, plot3, polar) Bar graphs (bar, barh, bar3, bar3h, hist, rose, pie, pie3) Surface plots (surf, surfc) Mesh plots (mesh, meshc, meshgrid) Contour plots(contour, contourc, contourf) Animation (moviein, movie) MATLAB also provides for low-level control in the event that the user wishes to have better control of the graphical output. In addition, MATLAB also provides a Graphical User Interface (GUI) toolbox called Guide for the creation of push buttons, text boxes, etc. for more user-friendly input to your m-files.
Line Plots
>> t = 0:pi/100:2*pi; >> y = sin(t); >> plot(t,y)
>> y2 = sin(t-0.25); >> y3 = sin(t+0.25); >> hold on; % <== to keep previously defined stuff % why not just plot only the 2nd and 3 curves?
>> plot(t,y,t,y2,t,y3)
>> legend('sin(t)','sin(t-0.25)','sin(t+0.25',1)
Bar Graphs
>> x = magic(3)
x=
8 3 4
1 5 9
6 7 2
Surface Plots
>> Z = peaks; >> surf(Z)
Animations
To create animation, first plot each frame and save the data in a corresponding column of a movie matrix, say, M.
>> axis equal >> M = moviein(16); % allocate/initialize the matrix to have 16 frames
Once M is defined for all 16 frames, its time to run the animation.
>> movie(M,30)
% run 30 times
handle = gca -- get current axes handle handle = gcf -- get current figure handle set(handle,'SomeProperty','SomeValue') -- set specific axes figure properties (of axes/figure handle)
>> get(handle) -- gets a list of current property settings of handle >> set(handle) -- gives a list of default property settings of handle
Here is an example:
>> figure >> t = 0:pi/100:2*pi; >> y = sin(t); >> y2 = sin(t-0.5); >> hold on >> h1 = plot(t,y)
h1 =
2.0015
>> h2 = plot(t,y2) >> get(h2) Color = [0 0 1] EraseMode = normal LineStyle = LineWidth = [0.5] Marker = none MarkerSize = [6] MarkerEdgeColor = auto MarkerFaceColor = none XData = [ (1 by 201) double array] YData = [ (1 by 201) double array] ZData = []
BusyAction = queue HandleVisibility = on HitTest = on Interruptible = on Parent = [1.00293] Selected = off SelectionHighlight = on Tag = Type = line UIContextMenu = [] UserData = [] Visible = on
>> set(h2,'color',[1 0 0]) >> >> set(h2,'color',[1 0 0]) >> h3 = title('Low level graphic commands demo')
h3 =
4.0016 >> set(h3) Color EraseMode: [ {normal} | background | xor | none ] Editing: [ on | off ] FontAngle: [ {normal} | italic | oblique ] FontName FontSize FontUnits: [ inches | centimeters | normalized | {points} | pixels ] FontWeight: [ light | {normal} | demi | bold ] HorizontalAlignment: [ {left} | center | right ] Position Rotation String Units: [ inches | centimeters | normalized | points | pixels | characters | {data} ] Interpreter: [ {tex} | none ] VerticalAlignment: [ top | cap | {middle} | baseline | bottom ]
ButtonDownFcn
Children Clipping: [ {on} | off ] CreateFcn DeleteFcn BusyAction: [ {queue} | cancel ] HandleVisibility: [ {on} | callback | off ] HitTest: [ {on} | off ] Interruptible: [ {on} | off ] Parent Selected: [ on | off ] SelectionHighlight: [ {on} | off ] Tag UIContextMenu UserData Visible: [ {on} | off ]
Extent = [1.87097 1.01754 3.20968 0.0994152] FontAngle = normal FontName = Helvetica FontSize = [10] FontUnits = points FontWeight = normal HorizontalAlignment = center Position = [3.49192 1.03519 17.3205] Rotation = [0] String = Low level graphic commands demo Units = data Interpreter = tex VerticalAlignment = bottom
HandleVisibility = off HitTest = on Interruptible = on Parent = [1.00293] Selected = off SelectionHighlight = on Tag = Type = text UIContextMenu = [] UserData = [] Visible = on
>> set(h3,'fontsize',15)
Without the !, output will not be permitted if the output file already exists. cootie% chmod +x mbatch Insert exit at the end of your m-file.
cootie% mbatch infile outfile The above runs the job in the background. infile is your m-file (be sure to include the suffix .m). outfile is the name of the output file.
To run batch:
In the above, queue-name is the queue name. You can find out about queue-name by typing, at prompt:
% bqueues -l
To find out the status of your jobs:
% bjobs
If you have access to SCVs computer systems, please note that the Linux Cluster is the recommended system for MATLAB applications. It currently runs MATLAB 7.4 (2007a). The IBM pSeries (for which twister is the login node) runs the outdated MATLAB 5.3 since newer MATLAB no longer runs on the AIX operating system. Also, MATLAB is not available on the IBM Bluegene as it is dedicated to parallel processing only. For more details on the Linux Clusters batch scheduler, please see this.
>> diary filename all subsequent text appearing on screen will be copied to
filename
>> diary off when done. The text in between are saved in filename. >> help diary for additional detail
o
To save graphical output to a file
>> print -dps filename saves current figure in postscript format to filename >> print -djpeg filename saves current figure in jpeg format to filename >> help print for additional options
o
To print a hard copy of your graphical output
>> print -dps -Pcasps make hard copy of plot in postscript format to CAS Labs
B&W printer
>> tic % starts a stopwatch timer >> % your MATLAB operations ... >> toc % reads a stopwatch timer
The above sequence prints the elapsed (wallclock) time, in seconds, for processing the operations between tic andtoc. There are other timers: etime, cputime, clock. For more details:
The situation will be further exacerbated if you plan to run multiple instances of
matlab in a cluster environment. In this case, you would be checking out multiple MATLAB licenses one license per instance of MATLAB. o Protects source code Since the executable is in binary form, the source code is not revealed and hence may be attractive for some code developers from a proprietary standpoint. o Improves computational performance In the MATLAB environment, m-files are executed in interpreted mode. While this mode is desirable for interactive environment, it usually carry a speed performance penalty compared with a pre-compiled C code. For long-running production codes, interactivity is generally not pervasive while computational performance is highly desirable. The MATLAB compiler converts m-files into C codes which are then compiled to produce an executable. Often, the executable yields significant speedup in runtime compared with running it in interpreted mode. To Generate MEX gateway function Users with code modules ( e.g., functions) that are computationally intensive may see significant speedup in runtime if these functions can be made to run in a pre-compiled mode. On the other hand, these users may still prefer to retain the interactive feature of the MATLAB environment for on-the-fly computation or graphical rendering after the compute-intensive functions are called. To enable the m-file to call an external C or fortran file, an interface is necessary. In MATLAB, this is called a gateway function. The gateway function must conform to certain requirement and you can write this gateway
function in C or fortran that reflect your specific applications. An example that apply this method to compute the solutions of an algebraic linear system of equations (via LU) in parallel was given here. Note that while the example is given for a parallel solve, it is applicable to serial processing as well. See MATLAB Compiler Users Guide