You are on page 1of 8

Fundamentals on MATLAB

The name MATLAB stands for MATrix LABoratory. MATLAB was written originally to provide easy access to matrix software developed by the LINPACK (linear system package) and EISPACK (Eigen system package) projects. MATLAB [1] is a high-performance language for technical computing. It integrates computation, visualization, and programming environment. Furthermore, MATLAB is a modern programming language environment: it has sophisticated data structures, contains built-in editing and debugging tools, and supports objectoriented programming. These factors make MATLAB an excellent tool for teaching and research. MATLAB has many advantages compared to conventional computer languages (e.g., C, FORTRAN) for solving technical problems. It has powerful built-in routines that enable a very wide variety of computations. It also has easy to use graphics commands that make the visualization of results immediately available. Specifc applications are collected in packages referred to as toolbox. There are toolboxes for signal processing, symbolic computation, control theory, simulation, optimization, and several other felds of applied science and engineering. Getting started: Double click on MATLAB shortcut icon (MATLAB 7.0.4) on your Windows desktop. When you start MATLAB, a special window called the MATLAB desktop appears. The desktop is a window that contains other windows. The major
VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 1

tools within or accessible from the desktop such as: 1. 2. 3. 4. The Command Window The Command History The Workspace The Current Directory

Command window:- It works as the interface for the users to exeute the required commands. Here, commands can be entered, and programs can output results and messages. Warnings, error messages and the like are also shown here. Command history:- It keeps a track of all commands executed on the command window in a current session. Workspace:- It holds the details(such as name, size, min value and max value) about the variables used in the programms. Current Directory:- It shows the current working directory or all the files under the current working directory.

Fundamentals on MATLAB

To execute the single command it can be written on the command window.But the program is having multiple commands to be executed so at a time all commands can be execyted by writting them all in a file and executing that file.To write the commands inro a file an editor is required so the matlab editor is there. open the matlab editor by using the file newm-file/script file write the required command for the task. save the written commands by a file name with matlab extension(.m).

Getting the output of a program: open the saved .m file for which the output is to be calculated. select the run from the debug menu to execute the program and to get the output. If the output is a text output then it will be in the command window, if the output is a figure or waveform then it will be there as a separate figure window. MATLAB variables MATLAB variables supports only one type of data i.e MATRIX. All the input or output variables are in the form of a matrix only. MATLAB variables are created with an assignment statement.
2

VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Fundamentals on MATLAB
A variable is identified by a unique name. The name has to begin with a letter, after that it can contain further letters, numbers, or the underscore. Variable names are casesensitive. According to the terminology used in linear algebra, some special cases of matrices in terms of their number of dimensions are referred to as: Scalar: matrix, having only one element Vector: one-dimensional matrix Matrix: matrix with two or more dimensions. To create a variable it can be written:The syntax of variable isVariable_name = a value (or an expression) For example, >> x = expression where expression is a combination of numerical values, mathematical operators, variables, and function calls. When defining matrices and vectors, the elements have to be enclosed in square brackets [ ]. For scalars, the brackets are optional. Example, >>x=5 x is a scalar having the value 5. >>x=[ 1 2 3] x is vector having one row of data. >>x=[1 2 3;4 5 6] x is a matrix having 2 rows and 3 columns The elements of matrices and vectors that belong to the same row are separated with a space or comma. The semicolon separates rows. Number sequences (= vectors) can be produced with the help of : - notation, e.g. >>x=1:10 assign a vector 1,2,3...10 as value of x. >>x=1:2:10 2,4,6,8,10 as value of x assign a vector

>>Variable_name=Start value:Separation between two values:End value Mathematical Operators and Functions In this section, mathematical operators and functions are explained. Mathematical operators are mathematical operation symbols such as: addition +, subtraction -, sign, etc. multiplication * and division / exponential functions such as square ^2 Example addition: x=20; y=30; z=x+y; disp(z);

subtraction: x=7; y=3; z=x-y; disp(z);

Other mathematical manipulations are realised as functions, e.g.

VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Fundamentals on MATLAB
trigonometrical functions: sine, cosine, tangent, etc. descriptive functions such as minimum, maximum, mean values and the like basic mathematical functions such as: square root, logarithm, sum, rounding, etc. Example t=45; x=121; y=sin(t); y=sqrt(x); Addition and subtraction of whole matrices is performed element-by-element. Element-by-element mulitplication and division of matrices require a special syntax: a.*b and a./b All the mathematical operations are carried between same order matrices only. Program Control Structures: Loops It is often necessary to repeat a sequence of statements. This is achieved by using loops. There are two kinds of loops: the for-loop the while-loop For loop: It is used if it is pre-determined how many times the statements have to be repeated. The syntax of the for loop: for index_variable = range statement 1 ... statement n end While loop: It allows for making the number of repetitions dependent on a comparison within the loop. The syntax of the while loop in pseudo code: while condition statement 1 ... statement n end The execution of any code can also be controlled by using the conditional control of flow by using the if condtion. Which can be written as if elseif switch case use of if:if conditional_statement Statement1 .... Statement1N else statements.... end use of elseif:if conditional_statement1 Statements1 elseif if conditional_statement2 Statements2 elseif if conditional_statement3 Statements3 .... statementN else Statements end use of switch:switch option case ch1
4

VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Fundamentals on MATLAB
statement1; case ch2 statement2; ........ Otherwise statementN; end; Program lines: Usually, for better readability, only one statement is written on a single program line. A semicolon after the statement prevents that the calculated values are printed to the Command Window. However, it is possible to write more than one statement on a line. In this case, the statements are separated by a comma, or by a semicolon which separates the statements and prevents output to the Command Window at the same time. Comments are marked by a percent sign %. Everything on a line that follows this sign will not be interpreted by Matlab. . Writing scripts Writing a script subsumes several steps: Starting the Editor: an empty file is opened. Writing the statements in the Editor window Saving the script as an M-file with a new name Executing a script A script is executed by typing the script name (i.e. the file name without the extension .m) in the Command Window, or by calling it from within another script or a function. The script file can also be executed by using the Run from the debug menu. Example A = [1 2 3; 4 5 6; 7 8 9] B = A'; Pause; A^3/B^2; Pause; Clc;

M-Files: Scripts and Functions All programs written in Matlab are stored as so-called M-files with the file name extension .m. There are two kinds of program or M-files: scripts and functions. Scripts A script contains a sequence of statements that works in the same way as if you entered these statements one after the other in the Command Window. Accordingly, scripts can access all variables in the Workspace, and variables created by scripts are stored in the Workspace. Functions A function is characterised by the fact that (in most cases) values are passed to it to be processed, and the function returns the calculated results to the caller(i.e. to the statement entered in the Command Window, or another script or function). Thus, this is the same as - for instance - with standard functions, e.g. computation of a mean value with a = mean(b). The data to be processed are passed to the function in matrix b, and the calculated mean value is returned in variable a. Structure of a Script

VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Fundamentals on MATLAB
Structure of a function A function only differs from a script in its first line. It contains the so-called function definition. This definition specifies: the function name. It has to be identical with the file name under which the function is saved (i.e. the M-file name). the input parameters: They specify what values can be passed to the function. the output parameters: They specify the values in which the function returns the results. Syntax of function: function [return parameters] = function_name(variables for input parameters) example: function out1 = myfunc( x ) %body or logic out1 = sqrt( 1 + (cos(x))^2 ); end * Semicolon in the program after the statement supreses the echo on the command window.

VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Fundamentals on MATLAB
SOME COMMONLY USED COMMAMDS Basic Plots and Graphs bar Vertical bar chart barh Horizontal bar chart hist Plot histograms hold Hold current graph pie Pie plot plot,stem Plot vectors or matrices. polar Polar coordinate plot semilogy Semi-log scale plot subplot Create axes in tiled positions figure Open a new figure window legend Legend for multiple curves print Send to printer. sound soundsc wavplay wavread wavrecord Convert vector into sound Scale data and play as sound Play recorded sound on a PCbased audio output device Read Microsoft WAVE (.wav) sound file Record sound using a PCbased audio input device

Matrix Manipulation cat Concatenate arrays diag Diagonal matrices and diagonals of a matrix fliplr Flip matrices left-right flipud Flip matrices up -down General Purpose Commands help Display M-file help for MATLAB functions in the Command Window clc Clear Command Window echo Echo M-files during execution clear Remove items from the workspace disp Display text or array length Length of vector date Current date string now Current date and time tic, toc Stopwatch timer Elementary Math Functions abs Absolute value and complex magnitude angle Phase angle ceil Round toward infinity complex Construct complex data from real and imaginary components conj Complex conjugate
7

Plot Annotation and Grids datetick Date formatted tick labels grid Grid lines for 2-D and 3-D plots gtext Place text on a 2-D graph using a mouse legend Graph legend for lines and patches plotyy Plot graphs with Y tick labels on the left and right title Titles for 2-D and 3-D plots xlabel X-axis labels for 2-D and 3-D plots ylabel Y-axis labels for 2-D and 3-D plots zlabel Z-axis labels for 3-D plots Sound Processing Functions in2mu Convert linear audio signal to mu-law mu2lin Convert mu-law audio signal to linear

VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Fundamentals on MATLAB
fix floor log mod real rem round sqrt Round towards zero Round towards minus infinity Natural logarithm Modulus (signed remainder after division) Real part of complex number Remainder after division Round to nearest integer Square root return switch try warning while Return to the invoking function Switch among several cases based on expression Begin try block Display warning message Repeat statements an indefinite number of times

Elementary Matrices and Arrays eye Identity matrix linspace Generate linearly spaced vectors ones Create an array of all ones rand Uniformly distributed random numbers and arrays zeros Create an array of all zeros Control flow break Terminate execution of for loop or while loop case Case switch catch Begin catch block continue Pass control to the next iteration of for or while loop if Conditionally execute statements else Conditionally execute statements elseif Conditionally execute statements end Terminate for, while, switch, try, and if statements or indicate last index error Display error messages for Repeat statements a specific number of times otherwise Default part of switch statement

String Manipulation findstr Find one string within another lower Convert string to lower case strcat String concatenation strcmp Compare strings strcmpi Compare strings, ignoring case strncmp Compare the first n characters of strings strrep String search and replace strtok First token in string strvcat Vertical concatenation of strings upper Convert string to upper case Image processing Imread Read an image Imwrite Write an image to a file Imshow Display an image Imfinfo Information about an image file may be found by

VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT

You might also like