# Survey on MATLAB

Assignment 4 – CIS705 – Spring‟2011 Praveen Kumar Lakkimsetti
praveenl@ksu.edu

LANGUAGE OVERVIEW:
MATLAB: Introduction, History and Application.

MATLAB (MATrix LAboratory) is a high level, dynamically typed language as well as an interactive programming environment which is well suited for numerical computations especially with matrix operations and linear algebra. MATLAB is much faster than traditional programming languages like C, FORTRAN etc in terms of solving technical computing problems. The other properties of MATLAB that makes this a popular language (More than 0ne million users by 2004)[1] are its support for functional , object oriented and event driven paradigms. Cleve Moler who was the chairman of computer science department at the University of New Mexico created MATLAB in 1970s. Later in 1984 he founded MathWorks with Jack Little, an engineer and MATLAB evolved into a commercial package. Even though MATLABs major purpose was numerical computing, it can be useful in many other areas. Some of them are:  It can do complex graphics in 2D and 3D.  It contains an in built high-level programming language ('baby' C) which makes it quite easy to implement complicated algorithms based on vectors and matrices.  Interactive tools for iterative exploration and problem solving.  Provides an environment for managing code, files and data.  Solves differential equations and other mathematical functions in statistics, Fourier analysis, Numerical integration etc.  MATLAB contains a wide variety of toolboxes for Statistics, Bioinformatics, Optimization, or Image Processing, to name just a few, the Matlab environment can be extended for more specialized requirements.

The MATLAB System: The MATLAB system has 5 main parts: 1) Desktop Tools and Development Environment: It consists of a set of tools and facilities that facilitate the users with MATLAB functionalities. Generally the set of tools are GUIs like the MATLAB Desktop, Command Window, code analyser, editor and debugger, browser.etc. 2) Mathematical Function Library: All the computational algorithms from elementary functions like sum, sine etc to complex functions like matrix Eigen values etc is available in this library. 3)The Language: The MATLAB language can be used to program small programs(without reuse) and large programs (reusable) with its data structures, control flow statements, object oriented and other programming features. 4)Graphics: MATLAB provides facilities to display vectors and matrices as graphs as well as provides high level functions for 2D and 3D data visualization, image processing etc and low level functions to customize the graphics. 5) External Interfaces: The C/C++ and FORTRAN programs are allowed to interact with MATLAB with the help of the external interfaces library. The facilities include calling routines from MATLAB, using MATLAB as a computational engine and for reading and writing MAT-files.

Getting Started With the MATLAB Environment: The Figure.1 below is a snapshot of the MATLAB Desktop and Development Environment.

We can manage files with the help of the dropdown (browse) box which shows the current folder. For more detailed information on the Development Environment please refer to the Starter Guide.[2]

LANGUAGE ELEMENTS
MATLAB Grammar: MATLAB offers many challenges during the syntax analysis like a single quote characters, efficiently building uniform colon expression etc. Writing the grammar for MATLAB is a tedious task. But for now, we can go through the broken and simple MATLAB grammar. Let us start off with the M-Files which have programs in them.
Figure.1 (MATLAB Development Environment) [2]

The Start button on the bottom left of the screen provides easy access to tools, demos, shortcuts and the required documentation. The Command Window is the place where we type our programs or commands and execute them. The results for the program are also displayed here. There is the fx button on the left of the prompt which when clicked opens up the function browser which can be used to look for the required inbuilt functions. The Command History takes care of the statements entered in the Command Window by logging the statements along with the timestamp. We can view, copy and execute the logged statements.
Figure 2 MATLAB grammars for M-Files. [9]

The M-Files can be script or function. So, if function file then we have function definition and the function body. For the script file we have the optional delimiter and/or statement list which is nothing but the program. The Workspace Browser and Variable Editor help us by Generally the delimiters are nothing but the ',' and ';'. gives information about each variable. We can add The parse error occurs if there is any error during variables to the workspace by using functions, executing, parsing. and script files. The workspace stores the variables belonging the session and stored in memory or can be loaded form a stored workspace. From the figure 3 we can see that the statement list calls the statement. The Menus are dynamic and they change based on the tool being used. The Help button gives access to all the documentation, demos and examples which help the user to run his programs.

In MATLAB the Expressions are composed as operations on sub expressions; ultimately, they consist of colons, string literals, identifiers and quantities. Let us first see about the matrices. A matrix is formed by surrounding one or more rows of elements with box brackets ([,]). Each row except the last must be terminated either by a semicolon or a LINE token so as to show that they are different columns. The elements in the rows are nothing but the expressions.

Figure 3. MATLAB grammars for Statement List. [9]

The statement in MATLAB can be a command invocation, expression, assignment or a control structure.

Figure 4. MATLAB grammars for Statement. [9]

The commands in MATLAB are of the form identifier followed by a text list. The functions in MATLAB can be invoked by functional form or by the command form.

Figure 6. MATLAB grammars for Matrices. [9]

Figure 5. MATLAB grammars for Command. [9]

Assignments in MATLAB are important as this is the only way in which a variable can be defined and altered. There are three ways in which we can do assignments. The s_assignment_matrix and m_assignment_matrinx are non terminal matrices. For one, semicolon and LINE token delimiters are not allowed among the elements of an m assignee matrix. Second, a comma is not allowed after the last element in an s_assignee_matrix or m_assignee_matrix sentence. Third, the elements in an s_assignee_matrix or m_assignee_matrix sentence can only be variables or array sections. Fourth, any expression may be assigned to an s_assignee_matrix

whereas the same is not true for an m_assignee_matrix. Fifth, assignments to empty matrices are invalid. LD and RD are lexemes [and] respectively.[9]

Figure 9. MATLAB grammars for “if”. [9]

"For" statement has a command list associated with the command list. The “for” command list is executed.
Figure 7. MATLAB grammars for Assignment. [9]

for_command: FOR for_cmd_list END Colon in MATLAB plays an important role in describing row vectors in which the elements are in arithmetic progression. The diagram shows that the colon in followed by an expression and it follows either an expression or a colon-expression. for_cmd_list: identifier ‟=‟ expr delimited_input

In Global statement a list of Global identifiers is followed by GLOBAL. global_command: GLOBAL global_decl_list global_decl_list: IDENTIFIER

Figure 8. MATLAB grammars for Colon. [10]

"While" statement is followed by a command list. while_command: WHILE while_cmd_list END while_cmd_list: expr delimited_input

Control Statements in MATLAB enable conditional (if) and iterative (for, while). Let us consider "if" statement here. There is an expression associated with the “if” statement and command list which needs to be executed if the expression is true. The body may be empty and so represented as delimited input. The conditional statement may have optional multiple elseif statements and else part.

For more detailed information on the syntax analysis please refer to [9], [10]. For a simplified grammar of MATLAB please refer [11].

MATLAB Basics: The "%" symbol is used to comment the reminder of the line. >>1 + 1 % Addition Operation. The "..." is used to extend the line to the next line. >> A = [1,2,3; ... 4,5]

The ";" at the end of statement states that the MATLAB will not display the output. If ";" is not present, then the output is printed. MATLABs Command Line operations: Up Arrow To use the previously typed commands. To come down through previously typed commands. moves to beginning of line moves to end of line moves forward a character moves back deletes a character Deletes the rest of the line to the right of the cursor. Goes back through the command history. goes forward Tries to complete a command.
Table 1.

p_kumar, lpk521 >> 2+3 ans = 5 >> x = 2 >> x = "abc" >> x = 1.5 >> clear >> who

allowed is underscore (_) % correct variable names. % Default assignment to ans.

Down Arrow

Ctrl+a Ctrl+e Ctrl+f Ctrl+b Ctrl+d Ctrl+k Ctrl+p Ctrl+n Tab

% Assigning integer % Assigning string % Assigning Floating values % removes all the variables % List all the variables Table 2

Data types in MATLAB: Variables: Variable names in MATLAB are case sensitive but as MATLAB is a weakly dynamically typed language, the variables can be assigned without declaring their type. All the variable names should start with an alphabet and can be continued with an underscore (_) or numbers. The variable names can contain upto 63 characters (MATLAB 6.5 or newer). In MATLAB we have special variables like pi, eps, inf, realmin, realmax etc. The default variable name is ans, if any variable name is not mentioned. So, care should be taken when choosing a variable name. variable = expression sum != suM _lpk, 5plk praveen-lak %Syntax % Case sentitive. % variable name should start with a letter % only special character In the above example the x value is stored and then used to calculate the y value. Suppressing the output can be done by using the ";". We can see that the x value can be reassigned and used.

Vectors: They can be considered as a single dimensional Transposing of a vector. We can make a row vector into array in other languages. They can be of the form (m x 1) a column vector and vice versa with the help of or (1 x m) where m is the number of rows in the first and transpose operator ('). the number of columns in the latter. The entries in the vector are enclosing in square brackets "[]". There are actually few ways of creating a vector. Let us see a couple of important ways here: Using colon notation. The general syntax for assigning a vector is init: increment: terminator, where the default increment value is 1. So, init: terminator is equivalent to init: 1: terminator. Eg, Matrices: They can be considered like arrays in other programming languages. Vectors are a special case of matrices. In fact in MATLAB it treats all variables as matrices. A vector is a matrix with either only rows or columns and a scalar (variable) is nothing but a matrix with one row and one column. Defining a matrix is similar to that of a vector. There are several ways of doing so. Let us see a few.

Using the built-in functions ones, zeros, linspace and logspace To create a row vector of length 4, filled with ones use >> a = ones(1,4) To create a column vector of length 4, filled with zeros use >> b = zeros(4,1)

Direct Assignment (Here the spaces are mandatory):

Another method is to consider it like a row of column vectors:

The other way of creating matrices is:

The length of the vector is nothing but the number of elements present in the vector. A vector can be added, subtracted and other operations can be performed by a scalar. But to perform addition, subtraction and other operations with a vector then both the vectors should be of same length.

The Matrix and Vector operations will be discussed in the later sections.

OTHERWISE statements END Eg.

Flow Control in MATLAB: MATLAB supports several flow control constructs. They are very similar to that of C. IF Statement: Its operation is similar to that of C. It starts with an If and ends with END. The structure is given as: IF expression statements ELSEIF expression statements ELSE statements END
Eg

For loop: Repeats a group of statements for a fixed and predetermined number of times. FOR variable = expression statements statements END Eg

Continue statement: Passes the control to the next iteration in for or while loops skipping the remaining statements in the loop. Break statement: Helps to exit the “for” or while loops. Switch and Case: The switch statement executes groups of statements based on the value of a variable or expression. The keywords case and otherwise delineate the groups. There must always be an end to match the switch. Here we don‟t require a break statement after the case statement as only the first matching case is executed. SWITCH expression CASE expression statements CASE expression statements

While loop: Repeats a group of statements till the logical condition is false. WHILE expression Statements END Eg

FUNCTIONS: Functions make programming easier with their reusability. To create the functions in MATLAB, the general syntax is as follows; function[output1, output2, output3] = myfunction(input1,input2) To create the function we need to open a new file (m-file) with the function name. Example: The below function is saved in a file called summation.m function [X1, X2] = summation(A,B,C) X1 = A+C; X2 = B+C; end Function call is as follows: [a,b] = summation(1,2,5)

Try/Catch: Gives some control over MATLAB error handling. Syntax : try statements Catch ME statements end Ex: a = rand; b = a*(a< 0.5); try c = a / b; assert(true); % set to false to have code throw an error catch ME % disaster recovery, cleanup, inform user, etc... display('Something went wrong'); warning('WARNING:ID','my own warning message'); display(ME.message); % ME is a structure with info on the error %error('my own error message'); % stops execution %rethrow(ME); % rethrows the original error and stops execution end

a= 6 b= 7 You can have multiple functions per file but only the function whose name corresponds to the filename is accessible from outside the file. The other functions can be used, however, from within this main function just as they would be if they were saved elsewhere. Each function must end with the end keyword.

PLOT MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as annotating and printing these graphs. The plot function has different forms, depending on the input arguments. If a is a vector, plot(a) produces a piecewise linear graph of the elements of a versus the index of the elements of a. If you specify two vectors as arguments, plot(a,b) produces a graph of b versus a.

Figure 12 – Drawing multiple data and multiple line plots Figure 10 – Drawing plot

To add labels to the axis and the plot you are plotting we can use xlabel(), ylabel(), title().

3D Graphs are also possible. Here we need to use plot3(x,y,z) to draw a 3D plot and to see the grid we need to use grid on..

Figure 11 – Labelling plots

Figure 13 – Drawing 3D plots.

Multiple data sets with different line styles, then we can use this notation shown in the figure

There can be many other modifications for the visualization of the data, but as of now we will concentrate on the implementations of the above topics in plotting.

MATLAB Programming: Data types We can use various types of data in MATLAB. For that we can build matrices, array of floating point, character and strings etc. Structures and cell arrays are the two MATLAB data types that can store dissimilar types. There are 15 different data types in MATLAB. All of the fundamental data types are shown in lowercase text in the diagram below. Additional data types are userdefined, object-oriented user classes (a subclass of structure), and java classes, that you can use with the MATLAB interface to Java.

including referencing itself recursively. The M-Files are of two types, Script files and function files. We have already discussed about the function files under functions section. The major difference between the function files and script files is that, for script files are called without arguments whereas the functional M-files may be called with arguments. Script M-Files: A script file consists of a sequence of normal MATLAB statements. If the file has the filename, say, rotate.m, then the MATLAB command rotate will cause the statements in the file to be executed. Variables in a script file are global and will change the value of variables of the same name in the environment of the current MATLAB session.

SAMPLE PROGRAMS:
Vector Operations in Figure 16 : vector*2 Element wise multiplication vector.^2 Element wise exponentiation vector* vector2 Vector multiplication Sum(vector) Sum of elements in the vector Max(vector) Max element in the vector
Figure14- Datatypes in MATLAB.[8]

FILE INPUT/OUTPUT: It is similar to C. The below given figure shows the various file operations.

Figure 15. File Operations in MATLAB.[5]

M-files : MATLAB can execute a sequence of statements stored in disk files. Such files are called M-files because they must have the file type of ".m" as the last part of their filename. A M-File can reference other M-files,

Figure 16 – Vector Operations

There are many other in-built functions in MATLAB for vector operations.

Matrix Operations:

and replicates it once (Because of the 2 in the function argument). The other operation in the figure is that of reshape matrix. Here reshape (matrix, m, n) where m is the number of rows and n is the number of columns

Figure 17 – Matrix Operations

In the above figure 17, the first operation that we are doing is to access an element from the matrix. matrix (1,3) gives us the element from the first row and the third column. The second operation matrix (3,:) gives us the whole of the third row and matrix (:,3) gives us the whole of the third column. size (matrix) gives the size of matrix in the form m n. In figure 18, we can see that the matrix inversion and finding Eigen values are done using the built in functions of MATLAB. There are many other functions available to operate on matrices. Here in the figure, we can see the creation of a 3X3 matrix of ones using ones function. Matrix multiplication is done using matrix * matrix2. Along with this using the “.” Operator matrix.*matrix2 does the element wise multiplication. Figure 19 shows how to replicate a matrix. Here in the function repmat (matrix,1,2) takes the matrix

Figure 18 – Matrix Operations (cont..)

Figure 19 – Matrix Operations (cont..)

PLOT Implementation: We had already seen how to draw the plot and few implementations like multiple data, multiple lines, naming the axis, title and 3D. Let us see here a few plot implementations in mesh and 2D plot.

In Figure 21, the meshgrid function fills out the values into x and y. Then the mesh (x, y, z) draws the mesh graph on the plot. Polynomial Implementation:

Figure 20 – Plot Implementation

In the Figure 20 we can see that the plot function plots the a and b values on the plot. Here a matrix is the x value and the b matrix acts as the y value. If there are no elements for y, it uses the index of each element of vector to plot.

Figure 22 – Polynomial Implementation

The above figure 22 is the solution for: [5] Here we will give the vectors t and scalar a with the values and the compute z = (1/2) a*t^2 + 100 Now let f(t) = 0 So, the polynomial equation becomes:

Figure 21 – Mesh Implementation

[5] So p = [a/2 0 100] Now to find root of p we have r = roots(p) Min and max of roots c =min(r) , d = max(r) Now, we plot the graph by the time and the position, by plot (t, z, „r-‟) and the remaining of the program is the basic plot functions. So, from the above example we can see that the polynomial equations can be converted into matrices and then use Matlab to find the solutions.

PRAGMATICS:
REFERENCES:

Learning MATLAB was a good experience. Matlab's main strength is that it includes cutting edge algorithms along with enormous data handling abilities and powerful programming tools. The interesting part in MATLAB is its support for the graphics. I found that plotting using MATLAB is very simple and quick. We can plot the required plots in many possible visualization methods. The Desktop and the Development Environment provides a good interface to work on. The demos, help files and documentation that were available proved to be very useful in learning and implementing MATLAB. Installing MATLAB is quite simple if we follow the well documented starter guide. But the software is really big (~2GB). MATLAB is so huge that a person cannot learn all the features of it. The original concept of a small and handy tool has evolved to become an very useful engineering tool. It is now accepted that MATLAB and its numerous Toolboxes can replace and/or enhance the usage of traditional simulation tools for advanced engineering applications. The major advantages of MATLAB is that it is easy to use and the platform independence. MATLAB support to the toolbox and the predefined inbuilt functions makes it easy to program and get the results. On the graphics side, the ability of MATLAB to do device independent plotting makes it suitable for users who do a lot of plotting. So, because of the above advantages MATLAB has gained this popularity in various fields including but not limited to bio informatics, FPGA simulations, Image Processing, Electronic circuits etc. On the downside, MATLAB is relatively expensive (510 times)[8] than conventional C or FORTRAN. The other major disadvantage of MATLAB is that it is a interpreted language. Even though the MATLAB programs are compiled into device independent p-code. The p-code has to be interpreted during run time. Loops run very slowly in Matlab, because of interpretation overhead. There is so much more about MATLAB. But the overview of the basics should serve the requirement as of now.

[1] http://en.wikipedia.org/wiki/MATLAB [2] http://www.mathworks.com/help/pdf_doc/matlab/matlab_env. pdf [3] http://www.mathworks.com/help/techdoc/ [4] http://www.eecs.umich.edu/~aey/eecs451/matlab.pdf [5] http://www.math.osu.edu/~overman/matlab.pdf [6] http://www.math.toronto.edu/mpugh/primer.pdf [7] http://web.cecs.pdx.edu/~gerry/MATLAB/plotting/loadingPlo tData.html [8] http://staff.iiu.edu.my/azami/MATLAB%20tutorial%20of%20 fundamental%20programming.pdf [9] http://www.ece.northwestern.edu/cpdc/pjoisha/Publications/C PDC-TR-9909-017.pdf [10] Handling Context-Sensitive Syntactic issues in the Design of a Front-end for a MATLAB Compiler,Pramod G..loisha, Abhay Kanhere, Prithviraj Banerjee,U. Nagaraj Shenoy, and Alok Choudhary, Supplement to the APL Berlin 2000 Proceedings. [11] http://www.cyberwizzard.nl/site/blog-programming/88matlab-grammar.html