SlideShare a Scribd company logo
1 of 94
A Training for Engineers introducingMATLAB
Making you a  better Engineer 1 3 2 Basic MATLAB Programming Advanced MATLAB Engineering Applications Redefine your engineering
Basic MATLAB Programming Design, organize, and collaborate 1
Session 1 MATLAB Overview ,[object Object]
  Various use cases of MATLAB
  MATLAB environment
  OCTAVE Introduction and installation
  MATLAB Vs OCTAVE,[object Object]
MATLAB - Application Domain Numerical computation: linear algebra, statistics, Fourier analysis, filtering, optimization, and numerical integration Signal and Image processing Communication Systems Control Design Test and measurement. Financial Modeling and Analysis Computational Biology. Virtually Any engineering domain.
Developing Algorithm and Applications MATLAB language supports vectors and matrix operations fundamental in engineering No need for low level administrative tasks like variable declaration, specifying data types and allocating data types.  No need for compilation and linking (JIT). Easy design of Graphical user interface (GUI). Development Tools: MATLAB Editor, M-lint Code Checker, MATLAB profile, Directory Report.
Analyzing and accessing data MATLAB supports entire data analysis process - from acquiring data, to preprocessing, visualization, and numerical analysis, to quality output. MATLAB product provides interactive tools and command-line functions for data analysis operations, including interpolation, decimation, correlation, Fourier analysis, statistics functions and matrix analysis.  MATLAB is an efficient platform for accessing data from files, other applications, databases, and external devices through serial ports and sound cards, popular file formats such as Microsoft Excel; ASCII text or binary files; image, sound, and video files; and scientific files, such as HDF and HDF5, web-pages and XML.
Visualizing Data All the graphics features that are required to visualize engineering and scientific data are available in MATLAB®. These include 2-D and 3-D plotting functions, 3-D volume visualization functions.  2-D Plotting: Line, area, bar, and pie chart, histogram, polygon and surface, scatter. 3-D Plotting: Surface, contour, mesh, image, iso-surface. MATLAB lets you read and write common graphical and data file formats, such as GIF, JPEG, BMP, EPS, TIFF, PNG, HDF, AVI, and PCX.
Publishing Results and Deploying Applications Publishing Results: Using the MATLAB Editor, you can automatically publish your MATLAB code in HTML, Word, LaTEX, and other formats. MATLAB provides functions for integrating C and C++ code, Fortran code, COM objects, and Java code with your applications. You can call DLLs, Java classes, and ActiveX controls. Using the MATLAB engine library, you can also call MATLAB from C, C++, or Fortran code. Deploying applications: Create your algorithm in MATLAB and distribute it to other MATLAB users directly as MATLAB code.  Using the MATLAB Compiler (available separately), you can deploy your algorithm, as a stand-alone application or as a software module that you include in your project, to users who do not have MATLAB.
Getting Started to MATLAB An introductory video taken  from MATLAB  Product Page. Curtsey : MATLAB Inc
MATLAB Environment The MATLAB desktop environment consist of four main windows:  Command Window  Command History Current Folder Window	  Workspace Browser
Description Command Window: A place where you type the command and instruction of MATLAB. Command History records all the commands entered in the command window. The Current folder is the directory where you can save your work.  Go to File->Set Path to set the list of folders to be included in the search path.  All the files and folders of the current folder are listed in the current folder browser.  Workspace Browser is a place where all variables in the MATLAB’s current session are stored and accessed.
OCTAVE GNU Octave is a high-level language, primarily intended for numerical computations.  It provides a convenient command line interface for solving linear and nonlinear problems numerically. It is mostly compatible with MATLAB. Interpreter provides convenient CLI.  (using libreadline)
Octave – Continued  GNU Octave is a freely redistributable software.  Octave and Octave-forge  includes a large set of toolbox present in MATLAB.  Easily extendible in C++ using a well designed library. Uses tried and tested FORTRUN routine in backend.  Community support on a very active mailing list.  Well supported on Linux and MacOS.
Octave – The Down Side Windows Platform support is not good (using cygwin) Dependent on volunteers and the quality of their work.   IDE, profiler and GUI Lacking.  Plots using GNUPlot which poses some problems – improvement on the way.  Compiler (Just-in-time?) Domain Specific packages not mature.
Installation (OCTAVE/MATLAB)
Too much information? We will go slow and try to cover important aspects and use cases of MATLAB . End of Session 1 ? Ask Questions for the sake of those sitting around you.
Session 2 MATLAB Programming Basic Data types Matrix and Linear Algebra Programming constructs and M-Files Data Import and export` Plots and Plotting tools MATLAB Control flow
MATLAB is MATrixLABoratory In the MATLAB environment, a matrix is a rectangular array of numbers. Entering Matrix into MATLAB Explicit list of elements. Load from external files. Generate matrix using Built-in functions. By default, MATLAB functions operate directly on matrix and no iteration logic need be implemented.
Hands on Session: S2C1 % MATLAB Workshop For engineers % Author: Mayank Kumar % Company: IDEAS2IGNITE % Date: 20/09/2010 %%Demonstrating MATRIX Manipulations a=[8 1 6;3 5 7;4 9 2] b=sum(a) c=sum(a')' d=sum(diag(a)) e=sum(diag(fliplr(a))) MATLA has a preference of working with column of Matrix.  By default, ,MATLAB stores answer in ans variables.  Transpose of Matrix Diagonal of Matrix
Accessing MATrix Elements The element in row i and column j of A is denoted by A(i,j). It is also possible to refer to the elements of a matrix with a single subscript, A(k). Matrix size is adaptive and increase with assignments outside the limits.  Referring to outside location leads to error.
Colon Operator Colon operator helps in generating Arithmetic Sequences which are used to refer to Matrix elements in bulk.  A:k:B => A sequence starting from A and ending on or before B with separation of K.  A:B => Default separation of 1. : => Sequence range automatically guessed from matrix size. Read as ‘ALL’
Hands on Session: S2C2 %% Understanding Colon Operators A=rand(10,10); B=A(:); stem(B,'.') mean(B) figure hist(B,10) %% More use of Colon Operator % Set all values greater than 0.8 to 0 B(B>0.8)=0; figure hist(B) Smart use of colon operators to avoid for loops decrease program execution times.  Matrix reference can be done using logic matrix.
Basic Programming components Variables Operators MATLAB expression Functions MATrix
Variables and Numbers MATLAB does not require any type declarations or dimension statements. MATLAB uses conventional decimal notation, Scientific notation uses the letter e to specify a power-of-ten scale factor. Imaginary numbers use either I or j as a suffix. MATLAB stores all numbers internally using the long format specified by the IEEE® floating-point standard.
MALAB Data Types
Integers
Floating Point Numbers	 MATLAB construct double precision data type according to IEEE Standard 754. (64-bit) MATLAB construct single precision data type according to IEEE Standard 754. (32-bit) Precision consideration is very important when choosing the data-type for your computation.  If you are aiming for embedded applications, you might have to make your algorithm work in single precisions.
Hands on Session: S2C3
Complex Numbers Complex numbers consist of two separate parts: a real part and an imaginary part. The basic imaginary unit is equal to the square root of -1. This is represented in MATLAB by either of two letters: i or j. Complex, real, imag, isreal
Infinity and NaN MATLAB uses the special values inf, -inf, and NaN to represent values that are positive and negative infinity, and not a number respectively. MATLAB represents infinity by the special value inf. Infinity results from operations like division by zero and overflow, which lead to results too large to represent as conventional floating-point values.  Use the isinf function to verify that x is positive or negative infinity.
Operators
MATLAB Functions	 MATLAB provides a large number of standard elementary mathematical functions and other application domain functions. These functions treat scalar and vectors in similar way. They work both for real and complex data making complex computation very easy.  Some of the functions are built in. Built-in functions are part of the MATLAB core so they are very efficient, but the computational details are not readily accessible. Other functions are implemented in the MATLAB programing language, so their computational details are accessible. help elfun help specfun help elmat
Hands on Session: S2C4 function [roots flag]=quadratic(a,b,c) if nargin==1     roots=[0 0];     flag=1; %Equal roots else     if(a==0) fprintf('a must not be equal to zero')         roots=[NaNNaN];         flag=NaN;     else         alpha=(-b+sqrt(b.^2-4*a.*c))./(2.*a);         beta=(-b-sqrt(b.^2-4*a.*c))./(2.*a);         roots=[alpha beta];         if(b.^2-4*a.*c==0)             flag=1; %equal oots         else             flag=0; %unequall roots         end     end  end How to make a custom MATLAB Functions
Back to MATrixLABoratory Standard Matrix Generation Zeros, Ones, Eye, Rand, randn Load function can be used to read binary files containing matrix from earlier session or text file containing data.  Concatenation Concatenation is the process of joining small matrices to make bigger ones. In fact, you made your first matrix by concatenating its individual elements. The pair of square brackets, [], is the concatenation operator. Rows or column can be deleted using a pair of square brackets.
Linear Algebra Determinant: det(A) reduced row echelon form: rref(A) Matrix Inversion: inv(A) Eigenvalues: eig(A) Coefficient of Characteristic polynomial: poly(A) Matrix Functions are column dominated.
Application: Solving Linear Equations One of the most important problems in technical computing is the solution of simultaneous linear equations. In matrix notation, this problem can be stated as follows. X = A: Denotes the solution to the matrix equation AX = B. X = B/A: Denotes the solution to the matrix equation XA = B.
Hands on Session: S2C5 Solving Linear Equations The coefficient matrix A need not be square. If A is m-by-n, there are three cases:  m = n Square system. Seek an exact solution. m > n Overdetermined system. Find a least squares solution. m < n Underdetermined system. Find a basic solution with at most m nonzero components. %% MATRIX Generations - 1 A=[2 4 5; 1 3 5; 3 1 6]; X=[2 5 7]'; B=A*X; %AX = B  %% Solution -1 Y = A; % Standard Backslash operator used to solve the equation.
Other useful stuffs Logical Subscripting: The logical vectors created from logical and relational operations can be used to reference subarrays. Suppose X is an ordinary matrix and L is a matrix of the same size that is the result of some logical operation. Then X(L) specifies the elements of X where the elements of L are nonzero. Find: The find function determines the indices of array elements that meet a given logical condition. Format: format long, format short e, format bank, format rat, format hex.
Hands on Session S2C6 A=1:1000; B=find(isprime(A))'; A=A(isprime(A)); scatter(B,A);
Plotting Graphs using MATLAB The MATLAB environment provides a wide variety of techniques to display data graphically. Interactive tools enable you to manipulate graphs to achieve results that reveal the most information about your data. You can also annotate and print graphs for presentations, or export graphs to standard graphics formats for presentation in Web browsers or other media
Creating a graph	 The type of graph you choose to create depends on the nature of your data and what you want to reveal about the data. You can choose from many predefined graph types, such as line, bar, histogram, and pie graphs as well as 3-D graphs, such as surfaces, slice planes, and streamlines. There are two basic ways to create MATLAB graphs: Plotting tools to create graph interactively Using CLI
Other Aspects Exploring Data Editing the Graph component Annotating graphs Printing and exporting Graphs Adding and removing figure content Saving graphs for reuse FIG File Generated Codes
Graph Components MATLAB graphs display in a special window known as a figure. Therefore, every graph is placed within axes defining a co-ordinate system, which are contained by the figure. You achieve the actual visual representation of the data with graphics objects like lines and surfaces.
A Basic Graph
GUI for plotting Graphs Type plottoolsin the command window. The plotting tools are made up of three independent GUI components: Figure Palette Plot Browser Property Editor Visibility of these can be controlled from view menu.
GUI for plotting graph
Hands on S2C7 This graph contains two y-axis, one for each plot – a lineseries and a stemseries. Demonstrate Editing basic properties Subplots Various types of graph Editing Plot in depth using property editor Property Inspector Multiple plots Changing current plot types Changing data source Annotating Graph Exporting graph Generating M-Code
Using Basic Plotting functions Creating a Line graph Plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements of y.  Plot(x,y) produces a graph of y versus x.  Plot(x,y,x,y2,x,y3) produces multiple graph in the same figure with different colors.  It is possible to specify color, line-style and using plot command. plot(x,y,'color_style_marker') If Z is complex, plot(z) plots imag(z) vs real(z)
Using basic Plotting functions
Using basic Plotting functions
Figure Use hold on to plot more than 1 plot in same figure  Graphing functions automatically open a new figure window if there are no figure windows already on the screen. To make an existing figure window the current figure, you can click the mouse while the pointer is in that window or you can type Figure(n) Clf reset
Subplots The subplot command enables you to display multiple plots in the same window or print them on the same piece of paper.  subplot(m,n,p) partitions the figure window into an m-by-n matrix of small subplots and selects the pth subplot for the current plot. The plots are numbered along the first row of the figure window, then the second row, and so on.
Controlling the Axis The axis command provides a number of options for setting the scaling, orientation, and aspect ratio of graphs. Setting Axis Limits axis([xminxmaxyminymax]) Setting the Axis Aspect Ratio axis square axis equal axis auto normal
Hands on S2C8
Control Flow Conditional Control — if, else, switch switch and case For While Continu Break Error Control — try - catch – Advanced sessions Program Termination — return
Conditional Statements A==B An error when A and B not of same size.  If(isequal(A,B)) Returns a logical value of 1 (representing true) or 0(representing False), instead of a matrix. Isempty All any
Hands on S2C9 Explains matrix comparison complexities.
Switch and Case switch (rem(n,4)==0) + (rem(n,2)==0) 	case 0 	M = odd_magic(n) 	case 1 	M = single_even_magic(n) 	case 2 	M = double_even_magic(n) 	otherwise 	error('This is impossible') End Break Statements are not required.
For Loops If you can replace for loops with colon operator, this will increase the efficiency of you code in MATLAB.  All for loops cannot be replaced with colon operator.  It depends on whether the functions used in the given scenario accepts and operates on MATRIX data types Efficiency tips: Do not let the size of your matrix grow inside a loop. Better is to pre-allocate the desired size using matrix generator functions like zeros, ones etc
Hands on S2C10
While loops Continue statement Break Statement
Return Statements Return function that enables you to terminate your program before it runs to completion. A called function normally transfers control to the function that invoked it when it reaches the end of the function. You can insert a return statement within the called function to force an early termination and to transfer control to the invoking function.
Other Data Structure Multidimensional Arrays Cell Arrays Structures
Multi-Dimensional Arrays Multidimensional arrays in the MATLAB environment are arrays with more than two subscripts. One way of creating a multidimensional array is by calling zeros, ones, rand, or randn with more than two arguments. A three-dimensional array might represent three-dimensional physical data, say the temperature in a room, sampled on a rectangular grid. Sum(m,d) – computes the sum by varying the dth subscript.
3-D Matrix
Cell Arrays Cell arrays in MATLAB are multidimensional arrays whose elements are copies of other arrays. The cell function But, more often, cell arrays are created by enclosing a miscellaneous collection of things in curly braces, {}. To retrieve the contents of one of the cells, use subscripts in curly braces.  Second, cell arrays contain copies of other arrays, not pointers to those arrays. If you subsequently change A, nothing happens to C.
Hands on S2C11 You can use three-dimensional arrays to store a sequence of matrices of the same size. Cell arrays can be used to store a sequence of matrices of different sizes.
The Magic Cell
Character and Text Strings is stored as character arrays in MATLAB.  The characters are stored as numbers, but not in floating-point format. a=double(‘hello’) B=char(a) F = reshape(32:127,16,6)'; char(F)
Character and string Concatenation  Row wise Column wise using char function As a cell array – cellstr(S)
Structures Structures are multidimensional MATLAB arrays with elements accessed by textual field designators. Field names of structures can be dynamic, and is evaluated during the runtime. Thus you can replace field names with other variables.  structName.(expression)
Hands on S2C12
Scripts and functions Scripts – Collection of CLI commands Declaration of functions Nargin Nargout Eval function
MATLAB Scripts You can enter commands from the language one at a time at the MATLAB command line. Or, you can write a series of commands to a file that you then execute as you would any MATLAB function. All the scripts given to you are actually MATLAB scripts and could be directly called my writing their name of the file in the command window if the folder is included in the path. Use the MATLAB Editor or any other text editor to create your own function files. Call these functions as you would any other MATLAB function or command.
MATLAB Program files There are two kinds of program files: Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace. Functions: which can accept input arguments and return output arguments. Internal variables are local to the function eg quadratic function we created yesterday.  If you duplicate function names, MATLAB executes the one that occurs first in the search path. To view the contents of a program file, for example, myfunction.m, use type myfunction
Functions Functions are files that can accept input arguments and return output arguments. The names of the file and of the function should be the same. Functions operate on variables within their own workspace, separate from the workspace you access at the MATLAB command prompt. type rank
MATLAB Functions The first line of a function starts with the keyword function. It gives the function name and order of arguments. The next several lines, up to the first blank or executable line, are comment lines that provide the help text. These lines are printed when you type help rank
MATLAB Functions MATLAB functions can have variable number of arguments not ordinarily found in other language.  If no output argument is supplied, the result is stored in ans. Within the body of the function, two quantities named nargin and nargout are available that tell you the number of input and output arguments involved in each particular use of the function.
Primary and Subfunctions function file contains a required primary function that appears first, and any number of subfunctions that may follow the primary. Primary functions havea wider scope than subfunctions. That is, primary functions can be called from outside of the file that defines them (e.g., from the MATLAB command line or from functions in other files) while subfunctions cannot.  Subfunctions are visible only to the primary function and other subfunctions within their own file.
Private Functions A private function is a type of primary function. Its unique characteristic is that it is visible only to a limited group of other functions. This type of function can be useful if you want to limit access to a function, or when you choose not to expose the implementation of a function. Private functions reside in subfolders with the special name private. They are visible only to functions in the parent folder. For example, assume the folder newmath is on the MATLAB search path. A subfolder of newmath called private can contain functions that only the functions in newmath can call.
Nested Functions You can define functions within the body of another function. These are said to be nested within the outer function. A nested function contains any or all of the components of any other function. In this example, function B is nested in  function A: function x = A(p1, p2) 	... 	B(p2) 	function y = B(p3) 		... 	end 	... end
Nested Functions Like other functions, a nested function has its own workspace where variables used by the function are stored. But it also has access to the workspaces of all functions in which it is nested. So, for example, a variable that has a value assigned to it by the primary function can be read or overwritten by a function nested at any level within the primary.  Similarly, a variable that is assigned in a nested function can be read or overwritten by any of the functions containing that function.
Function Overloading Overloaded functions are useful when you need to create a function that responds to different types of inputs accordingly. You can make this difference invisible to the user by creating two separate functions having the same name, and designating one to handle double types and one to handle integers. (more details on advanced session)
Global Variables If you want more than one function to share a single copy of a variable, simply declare the variable as global in all the functions. Do the same thing at the command line if you want the base workspace to access the variable. The global declaration must occur before the variable is actually used in a function.
String Arguments to functions You can write MATLAB functions that accept string arguments without the parentheses and quotes. That is, MATLAB interprets foo a b c as foo('a','b','c')
The eval function The eval function works with text variables to implement a powerful text macro facility. The expression or statement. The expression or statement eval(s) uses the MATLAB interpreter to evaluate the expression or execute the statement contained in the text string s.
The Function Handle You can create a handle to any MATLAB function and then use that handle as a means of referencing the function. A function handle is typically passed in an argument list to other functions, which can then execute, or evaluate, the function using the handle. Construct a function handle in MATLAB using the at sign, @, before the function name. fhandle = @sin;
The Function Handle You can call a function by means of its handle in the same way that you would call the function using its name.

More Related Content

What's hot

Basic operators in matlab
Basic operators in matlabBasic operators in matlab
Basic operators in matlabrishiteta
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlabTarun Gehlot
 
Brief Introduction to Matlab
Brief  Introduction to MatlabBrief  Introduction to Matlab
Brief Introduction to MatlabTariq kanher
 
Clipper and clamper circuits
Clipper and clamper circuitsClipper and clamper circuits
Clipper and clamper circuitsUnsa Shakir
 
Z transforms and their applications
Z transforms and their applicationsZ transforms and their applications
Z transforms and their applicationsRam Kumar K R
 
Laplace Transformation & Its Application
Laplace Transformation & Its ApplicationLaplace Transformation & Its Application
Laplace Transformation & Its ApplicationChandra Kundu
 
Eigenvalues and Eigenvector
Eigenvalues and EigenvectorEigenvalues and Eigenvector
Eigenvalues and EigenvectorMuhammad Hamza
 
Introduction to wavelet transform
Introduction to wavelet transformIntroduction to wavelet transform
Introduction to wavelet transformRaj Endiran
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introductionAmeen San
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlabMohan Raj
 
Laplace Transform and its applications
Laplace Transform and its applicationsLaplace Transform and its applications
Laplace Transform and its applicationsDeepRaval7
 
Laplace transform
Laplace  transform   Laplace  transform
Laplace transform 001Abhishek1
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPTShivam Gupta
 
Applications of Z transform
Applications of Z transformApplications of Z transform
Applications of Z transformAakankshaR
 
Decimation in time and frequency
Decimation in time and frequencyDecimation in time and frequency
Decimation in time and frequencySARITHA REDDY
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLABRavikiran A
 

What's hot (20)

Matlab Basic Tutorial
Matlab Basic TutorialMatlab Basic Tutorial
Matlab Basic Tutorial
 
Basic operators in matlab
Basic operators in matlabBasic operators in matlab
Basic operators in matlab
 
What is matlab
What is matlabWhat is matlab
What is matlab
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Brief Introduction to Matlab
Brief  Introduction to MatlabBrief  Introduction to Matlab
Brief Introduction to Matlab
 
Clipper and clamper circuits
Clipper and clamper circuitsClipper and clamper circuits
Clipper and clamper circuits
 
Z transforms and their applications
Z transforms and their applicationsZ transforms and their applications
Z transforms and their applications
 
Laplace Transformation & Its Application
Laplace Transformation & Its ApplicationLaplace Transformation & Its Application
Laplace Transformation & Its Application
 
Eigenvalues and Eigenvector
Eigenvalues and EigenvectorEigenvalues and Eigenvector
Eigenvalues and Eigenvector
 
Introduction to wavelet transform
Introduction to wavelet transformIntroduction to wavelet transform
Introduction to wavelet transform
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Laplace Transform and its applications
Laplace Transform and its applicationsLaplace Transform and its applications
Laplace Transform and its applications
 
Laplace transform
Laplace  transform   Laplace  transform
Laplace transform
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Applications of Z transform
Applications of Z transformApplications of Z transform
Applications of Z transform
 
Decimation in time and frequency
Decimation in time and frequencyDecimation in time and frequency
Decimation in time and frequency
 
Z transfrm ppt
Z transfrm pptZ transfrm ppt
Z transfrm ppt
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Introduction to Latex
Introduction to LatexIntroduction to Latex
Introduction to Latex
 

Similar to Matlab Introduction

Summer training introduction to matlab
Summer training  introduction to matlabSummer training  introduction to matlab
Summer training introduction to matlabArshit Rai
 
Summer training in matlab
Summer training in matlabSummer training in matlab
Summer training in matlabArshit Rai
 
Matlab - Introduction and Basics
Matlab - Introduction and BasicsMatlab - Introduction and Basics
Matlab - Introduction and BasicsTechsparks
 
MATLAB Assignment Help
MATLAB Assignment HelpMATLAB Assignment Help
MATLAB Assignment HelpEssay Corp
 
MATLAB workshop lecture 1MATLAB work.ppt
MATLAB workshop lecture 1MATLAB work.pptMATLAB workshop lecture 1MATLAB work.ppt
MATLAB workshop lecture 1MATLAB work.pptssuserdee4d8
 
Kevin merchantss
Kevin merchantssKevin merchantss
Kevin merchantssdharmesh69
 
KEVIN MERCHANT DOCUMENT
KEVIN MERCHANT DOCUMENTKEVIN MERCHANT DOCUMENT
KEVIN MERCHANT DOCUMENTtejas1235
 
Summer training matlab
Summer training matlab Summer training matlab
Summer training matlab Arshit Rai
 
Matlab for Electrical Engineers
Matlab for Electrical EngineersMatlab for Electrical Engineers
Matlab for Electrical EngineersManish Joshi
 
Summer training matlab
Summer training matlab Summer training matlab
Summer training matlab Arshit Rai
 
Introduction To MATLAB
Introduction To MATLABIntroduction To MATLAB
Introduction To MATLABArmanGupta10
 
Digital image processing - What is digital image processign
Digital image processing - What is digital image processignDigital image processing - What is digital image processign
Digital image processing - What is digital image processignE2MATRIX
 
IEEE Papers on Image Processing
IEEE Papers on Image ProcessingIEEE Papers on Image Processing
IEEE Papers on Image ProcessingE2MATRIX
 
MATLAB_CIS601-03.ppt
MATLAB_CIS601-03.pptMATLAB_CIS601-03.ppt
MATLAB_CIS601-03.pptaboma2hawi
 
INTRODUCTION TO MATLAB for PG students.ppt
INTRODUCTION TO MATLAB for PG students.pptINTRODUCTION TO MATLAB for PG students.ppt
INTRODUCTION TO MATLAB for PG students.pptKarthik537368
 

Similar to Matlab Introduction (20)

Summer training introduction to matlab
Summer training  introduction to matlabSummer training  introduction to matlab
Summer training introduction to matlab
 
Summer training in matlab
Summer training in matlabSummer training in matlab
Summer training in matlab
 
Matlab - Introduction and Basics
Matlab - Introduction and BasicsMatlab - Introduction and Basics
Matlab - Introduction and Basics
 
MATLAB Assignment Help
MATLAB Assignment HelpMATLAB Assignment Help
MATLAB Assignment Help
 
Matlab lecture
Matlab lectureMatlab lecture
Matlab lecture
 
MATLAB workshop lecture 1MATLAB work.ppt
MATLAB workshop lecture 1MATLAB work.pptMATLAB workshop lecture 1MATLAB work.ppt
MATLAB workshop lecture 1MATLAB work.ppt
 
Kevin merchantss
Kevin merchantssKevin merchantss
Kevin merchantss
 
KEVIN MERCHANT DOCUMENT
KEVIN MERCHANT DOCUMENTKEVIN MERCHANT DOCUMENT
KEVIN MERCHANT DOCUMENT
 
All About MATLAB
All About MATLABAll About MATLAB
All About MATLAB
 
Matlab demo
Matlab demoMatlab demo
Matlab demo
 
++Matlab 14 sesiones
++Matlab 14 sesiones++Matlab 14 sesiones
++Matlab 14 sesiones
 
Summer training matlab
Summer training matlab Summer training matlab
Summer training matlab
 
Dsp file
Dsp fileDsp file
Dsp file
 
Matlab for Electrical Engineers
Matlab for Electrical EngineersMatlab for Electrical Engineers
Matlab for Electrical Engineers
 
Summer training matlab
Summer training matlab Summer training matlab
Summer training matlab
 
Introduction To MATLAB
Introduction To MATLABIntroduction To MATLAB
Introduction To MATLAB
 
Digital image processing - What is digital image processign
Digital image processing - What is digital image processignDigital image processing - What is digital image processign
Digital image processing - What is digital image processign
 
IEEE Papers on Image Processing
IEEE Papers on Image ProcessingIEEE Papers on Image Processing
IEEE Papers on Image Processing
 
MATLAB_CIS601-03.ppt
MATLAB_CIS601-03.pptMATLAB_CIS601-03.ppt
MATLAB_CIS601-03.ppt
 
INTRODUCTION TO MATLAB for PG students.ppt
INTRODUCTION TO MATLAB for PG students.pptINTRODUCTION TO MATLAB for PG students.ppt
INTRODUCTION TO MATLAB for PG students.ppt
 

Recently uploaded

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Recently uploaded (20)

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

Matlab Introduction

  • 1. A Training for Engineers introducingMATLAB
  • 2. Making you a better Engineer 1 3 2 Basic MATLAB Programming Advanced MATLAB Engineering Applications Redefine your engineering
  • 3. Basic MATLAB Programming Design, organize, and collaborate 1
  • 4.
  • 5. Various use cases of MATLAB
  • 6. MATLAB environment
  • 7. OCTAVE Introduction and installation
  • 8.
  • 9.
  • 10. MATLAB - Application Domain Numerical computation: linear algebra, statistics, Fourier analysis, filtering, optimization, and numerical integration Signal and Image processing Communication Systems Control Design Test and measurement. Financial Modeling and Analysis Computational Biology. Virtually Any engineering domain.
  • 11. Developing Algorithm and Applications MATLAB language supports vectors and matrix operations fundamental in engineering No need for low level administrative tasks like variable declaration, specifying data types and allocating data types. No need for compilation and linking (JIT). Easy design of Graphical user interface (GUI). Development Tools: MATLAB Editor, M-lint Code Checker, MATLAB profile, Directory Report.
  • 12. Analyzing and accessing data MATLAB supports entire data analysis process - from acquiring data, to preprocessing, visualization, and numerical analysis, to quality output. MATLAB product provides interactive tools and command-line functions for data analysis operations, including interpolation, decimation, correlation, Fourier analysis, statistics functions and matrix analysis. MATLAB is an efficient platform for accessing data from files, other applications, databases, and external devices through serial ports and sound cards, popular file formats such as Microsoft Excel; ASCII text or binary files; image, sound, and video files; and scientific files, such as HDF and HDF5, web-pages and XML.
  • 13. Visualizing Data All the graphics features that are required to visualize engineering and scientific data are available in MATLAB®. These include 2-D and 3-D plotting functions, 3-D volume visualization functions. 2-D Plotting: Line, area, bar, and pie chart, histogram, polygon and surface, scatter. 3-D Plotting: Surface, contour, mesh, image, iso-surface. MATLAB lets you read and write common graphical and data file formats, such as GIF, JPEG, BMP, EPS, TIFF, PNG, HDF, AVI, and PCX.
  • 14. Publishing Results and Deploying Applications Publishing Results: Using the MATLAB Editor, you can automatically publish your MATLAB code in HTML, Word, LaTEX, and other formats. MATLAB provides functions for integrating C and C++ code, Fortran code, COM objects, and Java code with your applications. You can call DLLs, Java classes, and ActiveX controls. Using the MATLAB engine library, you can also call MATLAB from C, C++, or Fortran code. Deploying applications: Create your algorithm in MATLAB and distribute it to other MATLAB users directly as MATLAB code. Using the MATLAB Compiler (available separately), you can deploy your algorithm, as a stand-alone application or as a software module that you include in your project, to users who do not have MATLAB.
  • 15. Getting Started to MATLAB An introductory video taken from MATLAB Product Page. Curtsey : MATLAB Inc
  • 16. MATLAB Environment The MATLAB desktop environment consist of four main windows: Command Window Command History Current Folder Window Workspace Browser
  • 17. Description Command Window: A place where you type the command and instruction of MATLAB. Command History records all the commands entered in the command window. The Current folder is the directory where you can save your work. Go to File->Set Path to set the list of folders to be included in the search path. All the files and folders of the current folder are listed in the current folder browser. Workspace Browser is a place where all variables in the MATLAB’s current session are stored and accessed.
  • 18. OCTAVE GNU Octave is a high-level language, primarily intended for numerical computations. It provides a convenient command line interface for solving linear and nonlinear problems numerically. It is mostly compatible with MATLAB. Interpreter provides convenient CLI. (using libreadline)
  • 19. Octave – Continued GNU Octave is a freely redistributable software. Octave and Octave-forge includes a large set of toolbox present in MATLAB. Easily extendible in C++ using a well designed library. Uses tried and tested FORTRUN routine in backend. Community support on a very active mailing list. Well supported on Linux and MacOS.
  • 20. Octave – The Down Side Windows Platform support is not good (using cygwin) Dependent on volunteers and the quality of their work. IDE, profiler and GUI Lacking. Plots using GNUPlot which poses some problems – improvement on the way. Compiler (Just-in-time?) Domain Specific packages not mature.
  • 22. Too much information? We will go slow and try to cover important aspects and use cases of MATLAB . End of Session 1 ? Ask Questions for the sake of those sitting around you.
  • 23. Session 2 MATLAB Programming Basic Data types Matrix and Linear Algebra Programming constructs and M-Files Data Import and export` Plots and Plotting tools MATLAB Control flow
  • 24. MATLAB is MATrixLABoratory In the MATLAB environment, a matrix is a rectangular array of numbers. Entering Matrix into MATLAB Explicit list of elements. Load from external files. Generate matrix using Built-in functions. By default, MATLAB functions operate directly on matrix and no iteration logic need be implemented.
  • 25. Hands on Session: S2C1 % MATLAB Workshop For engineers % Author: Mayank Kumar % Company: IDEAS2IGNITE % Date: 20/09/2010 %%Demonstrating MATRIX Manipulations a=[8 1 6;3 5 7;4 9 2] b=sum(a) c=sum(a')' d=sum(diag(a)) e=sum(diag(fliplr(a))) MATLA has a preference of working with column of Matrix. By default, ,MATLAB stores answer in ans variables. Transpose of Matrix Diagonal of Matrix
  • 26. Accessing MATrix Elements The element in row i and column j of A is denoted by A(i,j). It is also possible to refer to the elements of a matrix with a single subscript, A(k). Matrix size is adaptive and increase with assignments outside the limits. Referring to outside location leads to error.
  • 27. Colon Operator Colon operator helps in generating Arithmetic Sequences which are used to refer to Matrix elements in bulk. A:k:B => A sequence starting from A and ending on or before B with separation of K. A:B => Default separation of 1. : => Sequence range automatically guessed from matrix size. Read as ‘ALL’
  • 28. Hands on Session: S2C2 %% Understanding Colon Operators A=rand(10,10); B=A(:); stem(B,'.') mean(B) figure hist(B,10) %% More use of Colon Operator % Set all values greater than 0.8 to 0 B(B>0.8)=0; figure hist(B) Smart use of colon operators to avoid for loops decrease program execution times. Matrix reference can be done using logic matrix.
  • 29. Basic Programming components Variables Operators MATLAB expression Functions MATrix
  • 30. Variables and Numbers MATLAB does not require any type declarations or dimension statements. MATLAB uses conventional decimal notation, Scientific notation uses the letter e to specify a power-of-ten scale factor. Imaginary numbers use either I or j as a suffix. MATLAB stores all numbers internally using the long format specified by the IEEE® floating-point standard.
  • 33. Floating Point Numbers MATLAB construct double precision data type according to IEEE Standard 754. (64-bit) MATLAB construct single precision data type according to IEEE Standard 754. (32-bit) Precision consideration is very important when choosing the data-type for your computation. If you are aiming for embedded applications, you might have to make your algorithm work in single precisions.
  • 35. Complex Numbers Complex numbers consist of two separate parts: a real part and an imaginary part. The basic imaginary unit is equal to the square root of -1. This is represented in MATLAB by either of two letters: i or j. Complex, real, imag, isreal
  • 36. Infinity and NaN MATLAB uses the special values inf, -inf, and NaN to represent values that are positive and negative infinity, and not a number respectively. MATLAB represents infinity by the special value inf. Infinity results from operations like division by zero and overflow, which lead to results too large to represent as conventional floating-point values. Use the isinf function to verify that x is positive or negative infinity.
  • 38. MATLAB Functions MATLAB provides a large number of standard elementary mathematical functions and other application domain functions. These functions treat scalar and vectors in similar way. They work both for real and complex data making complex computation very easy. Some of the functions are built in. Built-in functions are part of the MATLAB core so they are very efficient, but the computational details are not readily accessible. Other functions are implemented in the MATLAB programing language, so their computational details are accessible. help elfun help specfun help elmat
  • 39. Hands on Session: S2C4 function [roots flag]=quadratic(a,b,c) if nargin==1 roots=[0 0]; flag=1; %Equal roots else if(a==0) fprintf('a must not be equal to zero') roots=[NaNNaN]; flag=NaN; else alpha=(-b+sqrt(b.^2-4*a.*c))./(2.*a); beta=(-b-sqrt(b.^2-4*a.*c))./(2.*a); roots=[alpha beta]; if(b.^2-4*a.*c==0) flag=1; %equal oots else flag=0; %unequall roots end end end How to make a custom MATLAB Functions
  • 40. Back to MATrixLABoratory Standard Matrix Generation Zeros, Ones, Eye, Rand, randn Load function can be used to read binary files containing matrix from earlier session or text file containing data. Concatenation Concatenation is the process of joining small matrices to make bigger ones. In fact, you made your first matrix by concatenating its individual elements. The pair of square brackets, [], is the concatenation operator. Rows or column can be deleted using a pair of square brackets.
  • 41. Linear Algebra Determinant: det(A) reduced row echelon form: rref(A) Matrix Inversion: inv(A) Eigenvalues: eig(A) Coefficient of Characteristic polynomial: poly(A) Matrix Functions are column dominated.
  • 42. Application: Solving Linear Equations One of the most important problems in technical computing is the solution of simultaneous linear equations. In matrix notation, this problem can be stated as follows. X = A: Denotes the solution to the matrix equation AX = B. X = B/A: Denotes the solution to the matrix equation XA = B.
  • 43. Hands on Session: S2C5 Solving Linear Equations The coefficient matrix A need not be square. If A is m-by-n, there are three cases: m = n Square system. Seek an exact solution. m > n Overdetermined system. Find a least squares solution. m < n Underdetermined system. Find a basic solution with at most m nonzero components. %% MATRIX Generations - 1 A=[2 4 5; 1 3 5; 3 1 6]; X=[2 5 7]'; B=A*X; %AX = B %% Solution -1 Y = A; % Standard Backslash operator used to solve the equation.
  • 44. Other useful stuffs Logical Subscripting: The logical vectors created from logical and relational operations can be used to reference subarrays. Suppose X is an ordinary matrix and L is a matrix of the same size that is the result of some logical operation. Then X(L) specifies the elements of X where the elements of L are nonzero. Find: The find function determines the indices of array elements that meet a given logical condition. Format: format long, format short e, format bank, format rat, format hex.
  • 45. Hands on Session S2C6 A=1:1000; B=find(isprime(A))'; A=A(isprime(A)); scatter(B,A);
  • 46. Plotting Graphs using MATLAB The MATLAB environment provides a wide variety of techniques to display data graphically. Interactive tools enable you to manipulate graphs to achieve results that reveal the most information about your data. You can also annotate and print graphs for presentations, or export graphs to standard graphics formats for presentation in Web browsers or other media
  • 47. Creating a graph The type of graph you choose to create depends on the nature of your data and what you want to reveal about the data. You can choose from many predefined graph types, such as line, bar, histogram, and pie graphs as well as 3-D graphs, such as surfaces, slice planes, and streamlines. There are two basic ways to create MATLAB graphs: Plotting tools to create graph interactively Using CLI
  • 48. Other Aspects Exploring Data Editing the Graph component Annotating graphs Printing and exporting Graphs Adding and removing figure content Saving graphs for reuse FIG File Generated Codes
  • 49. Graph Components MATLAB graphs display in a special window known as a figure. Therefore, every graph is placed within axes defining a co-ordinate system, which are contained by the figure. You achieve the actual visual representation of the data with graphics objects like lines and surfaces.
  • 51. GUI for plotting Graphs Type plottoolsin the command window. The plotting tools are made up of three independent GUI components: Figure Palette Plot Browser Property Editor Visibility of these can be controlled from view menu.
  • 53. Hands on S2C7 This graph contains two y-axis, one for each plot – a lineseries and a stemseries. Demonstrate Editing basic properties Subplots Various types of graph Editing Plot in depth using property editor Property Inspector Multiple plots Changing current plot types Changing data source Annotating Graph Exporting graph Generating M-Code
  • 54. Using Basic Plotting functions Creating a Line graph Plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements of y. Plot(x,y) produces a graph of y versus x. Plot(x,y,x,y2,x,y3) produces multiple graph in the same figure with different colors. It is possible to specify color, line-style and using plot command. plot(x,y,'color_style_marker') If Z is complex, plot(z) plots imag(z) vs real(z)
  • 55. Using basic Plotting functions
  • 56. Using basic Plotting functions
  • 57. Figure Use hold on to plot more than 1 plot in same figure Graphing functions automatically open a new figure window if there are no figure windows already on the screen. To make an existing figure window the current figure, you can click the mouse while the pointer is in that window or you can type Figure(n) Clf reset
  • 58. Subplots The subplot command enables you to display multiple plots in the same window or print them on the same piece of paper. subplot(m,n,p) partitions the figure window into an m-by-n matrix of small subplots and selects the pth subplot for the current plot. The plots are numbered along the first row of the figure window, then the second row, and so on.
  • 59. Controlling the Axis The axis command provides a number of options for setting the scaling, orientation, and aspect ratio of graphs. Setting Axis Limits axis([xminxmaxyminymax]) Setting the Axis Aspect Ratio axis square axis equal axis auto normal
  • 61. Control Flow Conditional Control — if, else, switch switch and case For While Continu Break Error Control — try - catch – Advanced sessions Program Termination — return
  • 62. Conditional Statements A==B An error when A and B not of same size. If(isequal(A,B)) Returns a logical value of 1 (representing true) or 0(representing False), instead of a matrix. Isempty All any
  • 63. Hands on S2C9 Explains matrix comparison complexities.
  • 64. Switch and Case switch (rem(n,4)==0) + (rem(n,2)==0) case 0 M = odd_magic(n) case 1 M = single_even_magic(n) case 2 M = double_even_magic(n) otherwise error('This is impossible') End Break Statements are not required.
  • 65. For Loops If you can replace for loops with colon operator, this will increase the efficiency of you code in MATLAB. All for loops cannot be replaced with colon operator. It depends on whether the functions used in the given scenario accepts and operates on MATRIX data types Efficiency tips: Do not let the size of your matrix grow inside a loop. Better is to pre-allocate the desired size using matrix generator functions like zeros, ones etc
  • 67. While loops Continue statement Break Statement
  • 68. Return Statements Return function that enables you to terminate your program before it runs to completion. A called function normally transfers control to the function that invoked it when it reaches the end of the function. You can insert a return statement within the called function to force an early termination and to transfer control to the invoking function.
  • 69. Other Data Structure Multidimensional Arrays Cell Arrays Structures
  • 70. Multi-Dimensional Arrays Multidimensional arrays in the MATLAB environment are arrays with more than two subscripts. One way of creating a multidimensional array is by calling zeros, ones, rand, or randn with more than two arguments. A three-dimensional array might represent three-dimensional physical data, say the temperature in a room, sampled on a rectangular grid. Sum(m,d) – computes the sum by varying the dth subscript.
  • 72. Cell Arrays Cell arrays in MATLAB are multidimensional arrays whose elements are copies of other arrays. The cell function But, more often, cell arrays are created by enclosing a miscellaneous collection of things in curly braces, {}. To retrieve the contents of one of the cells, use subscripts in curly braces. Second, cell arrays contain copies of other arrays, not pointers to those arrays. If you subsequently change A, nothing happens to C.
  • 73. Hands on S2C11 You can use three-dimensional arrays to store a sequence of matrices of the same size. Cell arrays can be used to store a sequence of matrices of different sizes.
  • 75. Character and Text Strings is stored as character arrays in MATLAB. The characters are stored as numbers, but not in floating-point format. a=double(‘hello’) B=char(a) F = reshape(32:127,16,6)'; char(F)
  • 76. Character and string Concatenation Row wise Column wise using char function As a cell array – cellstr(S)
  • 77. Structures Structures are multidimensional MATLAB arrays with elements accessed by textual field designators. Field names of structures can be dynamic, and is evaluated during the runtime. Thus you can replace field names with other variables. structName.(expression)
  • 79. Scripts and functions Scripts – Collection of CLI commands Declaration of functions Nargin Nargout Eval function
  • 80. MATLAB Scripts You can enter commands from the language one at a time at the MATLAB command line. Or, you can write a series of commands to a file that you then execute as you would any MATLAB function. All the scripts given to you are actually MATLAB scripts and could be directly called my writing their name of the file in the command window if the folder is included in the path. Use the MATLAB Editor or any other text editor to create your own function files. Call these functions as you would any other MATLAB function or command.
  • 81. MATLAB Program files There are two kinds of program files: Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace. Functions: which can accept input arguments and return output arguments. Internal variables are local to the function eg quadratic function we created yesterday. If you duplicate function names, MATLAB executes the one that occurs first in the search path. To view the contents of a program file, for example, myfunction.m, use type myfunction
  • 82. Functions Functions are files that can accept input arguments and return output arguments. The names of the file and of the function should be the same. Functions operate on variables within their own workspace, separate from the workspace you access at the MATLAB command prompt. type rank
  • 83. MATLAB Functions The first line of a function starts with the keyword function. It gives the function name and order of arguments. The next several lines, up to the first blank or executable line, are comment lines that provide the help text. These lines are printed when you type help rank
  • 84. MATLAB Functions MATLAB functions can have variable number of arguments not ordinarily found in other language. If no output argument is supplied, the result is stored in ans. Within the body of the function, two quantities named nargin and nargout are available that tell you the number of input and output arguments involved in each particular use of the function.
  • 85. Primary and Subfunctions function file contains a required primary function that appears first, and any number of subfunctions that may follow the primary. Primary functions havea wider scope than subfunctions. That is, primary functions can be called from outside of the file that defines them (e.g., from the MATLAB command line or from functions in other files) while subfunctions cannot. Subfunctions are visible only to the primary function and other subfunctions within their own file.
  • 86. Private Functions A private function is a type of primary function. Its unique characteristic is that it is visible only to a limited group of other functions. This type of function can be useful if you want to limit access to a function, or when you choose not to expose the implementation of a function. Private functions reside in subfolders with the special name private. They are visible only to functions in the parent folder. For example, assume the folder newmath is on the MATLAB search path. A subfolder of newmath called private can contain functions that only the functions in newmath can call.
  • 87. Nested Functions You can define functions within the body of another function. These are said to be nested within the outer function. A nested function contains any or all of the components of any other function. In this example, function B is nested in function A: function x = A(p1, p2) ... B(p2) function y = B(p3) ... end ... end
  • 88. Nested Functions Like other functions, a nested function has its own workspace where variables used by the function are stored. But it also has access to the workspaces of all functions in which it is nested. So, for example, a variable that has a value assigned to it by the primary function can be read or overwritten by a function nested at any level within the primary. Similarly, a variable that is assigned in a nested function can be read or overwritten by any of the functions containing that function.
  • 89. Function Overloading Overloaded functions are useful when you need to create a function that responds to different types of inputs accordingly. You can make this difference invisible to the user by creating two separate functions having the same name, and designating one to handle double types and one to handle integers. (more details on advanced session)
  • 90. Global Variables If you want more than one function to share a single copy of a variable, simply declare the variable as global in all the functions. Do the same thing at the command line if you want the base workspace to access the variable. The global declaration must occur before the variable is actually used in a function.
  • 91. String Arguments to functions You can write MATLAB functions that accept string arguments without the parentheses and quotes. That is, MATLAB interprets foo a b c as foo('a','b','c')
  • 92. The eval function The eval function works with text variables to implement a powerful text macro facility. The expression or statement. The expression or statement eval(s) uses the MATLAB interpreter to evaluate the expression or execute the statement contained in the text string s.
  • 93. The Function Handle You can create a handle to any MATLAB function and then use that handle as a means of referencing the function. A function handle is typically passed in an argument list to other functions, which can then execute, or evaluate, the function using the handle. Construct a function handle in MATLAB using the at sign, @, before the function name. fhandle = @sin;
  • 94. The Function Handle You can call a function by means of its handle in the same way that you would call the function using its name.
  • 95. Hands on Session S2C13 – fun_plot
  • 96. We have covered bases We will now move on to some engineering application of MATLAB before covering some advanced topics. End of Session 2 ? Ask Questions for the sake of those sitting around you.
  • 97. MayankKumar Contact the author at mayank [at] ideas2ignite [dot] com for more Tutorials on MATLAB for Electrical Engineers. Attribution-Non Commercial-ShareAlike3.0 Unported (CC BY-NC-SA 3.0) IDEAS2IGNITE

Editor's Notes

  1. This presentation demonstrates the new capabilities of PowerPoint and it is best viewed in Slide Show. These slides are designed to give you great ideas for the presentations you’ll create in PowerPoint 2010!For more sample templates, click the File tab, and then on the New tab, click Sample Templates.
  2. Special meaning is sometimes attached to 1-by-1 matrices, which are scalars, and to matrices with only one row or column, which are vectors. MATLAB has other ways of storing both numeric and nonnumeric data, but in the beginning, it is usually best to think of everything as a matrix.Magic Squares are special matrix whose row, column and diagonal sum are all equal. Considered to be very auspecious.
  3. Colon operator replaces the much used for loops for array referencing used in conventional programming language.