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

Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to MatlabAmr Rashed
 
Brief Introduction to Matlab
Brief  Introduction to MatlabBrief  Introduction to Matlab
Brief Introduction to MatlabTariq kanher
 
Matlab Introduction
Matlab IntroductionMatlab Introduction
Matlab IntroductionDaniel Moore
 
Matlab (Presentation on MATLAB)
Matlab (Presentation on MATLAB)Matlab (Presentation on MATLAB)
Matlab (Presentation on MATLAB)Chetan Allapur
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introductionAmeen San
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersMurshida ck
 
MATLAB Basics-Part1
MATLAB Basics-Part1MATLAB Basics-Part1
MATLAB Basics-Part1Elaf A.Saeed
 
Basic matlab and matrix
Basic matlab and matrixBasic matlab and matrix
Basic matlab and matrixSaidur Rahman
 
Matlab for beginners, Introduction, signal processing
Matlab for beginners, Introduction, signal processingMatlab for beginners, Introduction, signal processing
Matlab for beginners, Introduction, signal processingDr. Manjunatha. P
 
Radial basis function network ppt bySheetal,Samreen and Dhanashri
Radial basis function network ppt bySheetal,Samreen and DhanashriRadial basis function network ppt bySheetal,Samreen and Dhanashri
Radial basis function network ppt bySheetal,Samreen and Dhanashrisheetal katkar
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to Matlabaman gupta
 
Artificial neural network
Artificial neural networkArtificial neural network
Artificial neural networkDEEPASHRI HK
 

What's hot (20)

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
 
Matlab Introduction
Matlab IntroductionMatlab Introduction
Matlab Introduction
 
Matlab (Presentation on MATLAB)
Matlab (Presentation on MATLAB)Matlab (Presentation on MATLAB)
Matlab (Presentation on MATLAB)
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 
Matlab Basic Tutorial
Matlab Basic TutorialMatlab Basic Tutorial
Matlab Basic Tutorial
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
 
Matlab basic and image
Matlab basic and imageMatlab basic and image
Matlab basic and image
 
MATLAB Basics-Part1
MATLAB Basics-Part1MATLAB Basics-Part1
MATLAB Basics-Part1
 
Introduction to-matlab
Introduction to-matlabIntroduction to-matlab
Introduction to-matlab
 
Basic matlab and matrix
Basic matlab and matrixBasic matlab and matrix
Basic matlab and matrix
 
Matlab for beginners, Introduction, signal processing
Matlab for beginners, Introduction, signal processingMatlab for beginners, Introduction, signal processing
Matlab for beginners, Introduction, signal processing
 
Radial basis function network ppt bySheetal,Samreen and Dhanashri
Radial basis function network ppt bySheetal,Samreen and DhanashriRadial basis function network ppt bySheetal,Samreen and Dhanashri
Radial basis function network ppt bySheetal,Samreen and Dhanashri
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to Matlab
 
Learn Matlab
Learn MatlabLearn Matlab
Learn Matlab
 
Matlab intro
Matlab introMatlab intro
Matlab intro
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 
Introduction to Latex
Introduction to LatexIntroduction to Latex
Introduction to Latex
 
Artificial neural network
Artificial neural networkArtificial neural network
Artificial neural network
 
Fundamentals of matlab
Fundamentals of matlabFundamentals of matlab
Fundamentals of matlab
 

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
 

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
 
MATLAB INTRODUCTION
MATLAB INTRODUCTIONMATLAB INTRODUCTION
MATLAB INTRODUCTION
 
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
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Recently uploaded (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

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.