0% found this document useful (0 votes)
82 views

What Is Matlab

This document provides an overview of MATLAB, including what it is, its characteristics, functions, file types, vector techniques, and graphics capabilities. MATLAB stands for MATrix LABoratory and is an interactive program for numerical computations, simulations, and data analysis. It uses matrix operations and functions to perform tasks such as data visualization, algorithm development, data analysis, and numeric computation.

Uploaded by

Neetu Goel
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

What Is Matlab

This document provides an overview of MATLAB, including what it is, its characteristics, functions, file types, vector techniques, and graphics capabilities. MATLAB stands for MATrix LABoratory and is an interactive program for numerical computations, simulations, and data analysis. It uses matrix operations and functions to perform tasks such as data visualization, algorithm development, data analysis, and numeric computation.

Uploaded by

Neetu Goel
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 25

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

computational load warrants.

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 help % instructions on how to get 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.,

>> x = 1:2:9; % x = [1 3 5 7 9];


! prepend it to a unix command to execute, e.g.,

>> !ls -l
; delimits statements; suppresses screen output, e.g.,

>> x = 1:2:9; y = 2:10; % two statements on the same line


statement continuation, e.g.,

>> x = [ 1 3 5 ... 7 9]; % x = [1 3 5 7 9] split into 2 lines


: range delimiter, e.g.,

>> x = [1:2:9]; % x=[1,3,5,7,9]

matrix transposition, 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 = [1:2:9], y = [1:9] % two statements on the same line


. precede an arithmetic operator to perform an elemental operation, instead of matrix operation, e.g.,

>> x = 3:3:9

x=

>> y = 3*ones(3,1)'

y= 3 3 3

>> z =x./y

z= 1 2 3

* wild card, e.g.,

>> clear A* % clears all variables that start with A.

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.

Basic Arithmetic Operators


+ * / ^ (algebraic/matrix definitions) .+ .- .* ./ .^ (element by element operation)
Additionally,

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

Elementary Math Intrinsic Functions


>> abs(x) >> exp(x) >> fix(x) >> log10(x) >> rem(x,y) >> sqrt(x) >> sin(x) >> acoth(x) % absolute value of x % e to the x-th power % rounds x to integer towards 0 % common logarithm of x to the base 10 % remainder of x/y % square root of x % sine of x; x in radians % inversion hyperbolic cotangent of x

>> help elfun % get a list of all available elementary functions

MATLAB File Types


o
script m-files ( variables global). Create a file by the name, say, mytest.m. Contents of mytest.m :

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

Defining Matrices via the Vector Technique


Using the for loop in MATLAB is relatively expensive. It is much more efficient to perform the same task using the vector method. For example, the following task

for j=1:n for i=1:m A(i,j) = B(i,j) + C(i,j); end end


can be more compactly and efficiently represented (and computed) by the vector method as follows:

A(1:m,1:n) = B(1:m,1:n) + C(1:m,1:n);


If the matrices are all of the same size (as is the case here), then the above can be more succinctly written as

A = B + C;
For sufficiently large matrix operations, this latter method is vastly superior in performance. More examples

Vector Technique Examples


>> A = magic(3) % define a 3x3 matrix A

A=

8 3 4

1 5 9

6 7 2

>> b = 1:3

% define b as a 1x3 row vector

b=

>> [A, b']

% Add b transpose as a 4th column to A

ans =

3 4

5 9

7 2

2 3

>> [A; b]

% Add b as a 4th row to A

ans =

8 3 4 1

1 5 9 2

6 7 2 3

>> x = 1:5

x=

>> A = 2*ones(3,3)

% yes, there is a zeros m-file too

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 = A(:,[1 3 2])

% switch 2nd and third columns of A

B=

8 3 4

6 7 2

1 5 9

>> A(:,2) = []

% delete second column of A

A=

3 4

7 2

Examples on logical indexing

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)

>> xlabel('t') >> ylabel('sin(t)') >> title('The plot of t vs sin(t)')

>> 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

>> bar(x) >> grid

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

>> set(gca,'NextPlot','replacechildren') >> for j=1:16 plot(fft(eye(j+16))) M(:,j) = getframe; end

Once M is defined for all 16 frames, its time to run the animation.

>> movie(M,30)

% run 30 times

Low-level Graphic Commands


Typically, MATLABs high-level graphic commands are sufficient to produce graphs to the users requirements. However, there are circumstances in which the user may find it necessary to modify MATLABs settings to achieve desired results. The key commands that you will find useful to this end are:

>> >> >> or

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)

A list of the properties of axes or figure is produced by:

>> 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 = []

ButtonDownFcn = Children = [] Clipping = on CreateFcn = DeleteFcn =

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 ]

>> get(h3) Color = [0 0 0] EraseMode = normal Editing = 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

ButtonDownFcn = Children = [] Clipping = off CreateFcn = DeleteFcn = BusyAction = queue

HandleVisibility = off HitTest = on Interruptible = on Parent = [1.00293] Selected = off SelectionHighlight = on Tag = Type = text UIContextMenu = [] UserData = [] Visible = on

>> set(h3,'fontsize',15)

How to Run MATLAB Via Batch on SCV Linux Cluster


Create a script, say, mbatch, with the following line:

matlab -nodisplay -nosplash < $1 >! $2


Notes:

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.

To run mbatch, issue the following command at the system prompt:

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:

cootie% bsub -q queue-name "mbatch infile outfile"

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.

How to Save or Print Your Work


o
To save text of your MATLAB interactive session

>> 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

>> help print for additional options

How to Time Your Work

>> 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:

>> help tic >> help toc

Why MATLAB Compiler?


o
To generate Standalone Executables Can execute without MATLAB The executable can run on specific type of machines for which it is compiled (e.g., Windows, Linux) even if the target machine does not have MATLAB installed. o Needs no MATLAB license Even on machines with MATLAB installed, running a standalone requires NO MATLAB licenses. On systems with more users than available licenses, running job with a standalone executable is most convenient and effective as there is no wait for a license to become available.

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

You might also like