Download presentation
Presentation is loading. Please wait.
1
Introduction to MATLAB
Dr. Hiren D. Joshi Department of Computer Science Rollwala Computer Centre Gujarat University
2
What is MATLAB? MATLAB (short for MATrix LABoratory) is a special-purpose computer program optimized to perform engineering and scientific calculations. MATLAB is a sophisticated mathematical computation and visualization (graphing, image processing and display) tool. MATLAB is widely used across all disciplines of mathematics, scientific research & engineering.
3
What is MATLAB? The name MATLAB is short for Matrix Laboratory and sets the stage for how the software operates. MATLAB is designed and optimized to perform mathematical operations on matrices. You can choose to not take advantage of the matrix format, but your calculation time will suffer. MATLAB also contains a high level scripting language for controlling MATLAB programatically.
4
The Advantages of MATLAB
Ease of Use Platform Independence Predefined Functions Device-Independent Plotting Graphical User Interface MATLAB Complier Compile MATLAB programs into a device independent p-code, and then interpreting the p-code instruction at run-time.
5
Disadvantages of MATLAB
It is an interpreted language and therefore can execute more slowly than complied languages. A full copy of MATLAB is 5 to 10 times more expensive than a conventional C or Fortran complier.
6
MATLAB Interface
7
MATLAB Interface MATLAB gives you a series of windows that allow you to control functions: Command window Current directory Workspace Command history Additional windows appear as needed: Document windows Figure windows Editing windows
8
The Command Window The R.H.S. of the default MATLAB desktop contains the Command Window. A user can enter interactive commands at the command prompt (>>) in the command window. >> Area = pi * 2.5 ^ 2 Stores answer in variable area. If a statement is too long to type on a single line, it may be continued on successive lines by typing an elllipsis(…) at the end of the first line and then continue on the second line.
9
Command Window >> X1 = 1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6
Instead of typing commands directly in the command window, a series of commands can be placed into a file and the entire file can be executed by typing its name in the command window. Such files are called script files. Script files also known as M-files, because they have a file-extension “.m”
10
Getting Going – Command Window
Try It! To perform calculations in MATLAB, you type your command in the Command Window at the Command Prompt ( >> ) You can type mathematical expressions just like with a scientific calculator You can write simple programs. You can tell MATLAB to run a program you have written in the MATLAB scripting language and have stored on the computer. At the Command Prompt, type the following commands (press Enter after each): >> 25/5 >> 5^2 >> >> sqrt(25) MATLAB uses the standard order of operations: - Parentheses - Exponentiation - Division / Multiplication - Addition / Subtraction Tip: use your up-arrow key to bring back lines you have already typed. Press ESC to quit the edit.
11
Getting Going – Command Window
If things went well, you should have a window that looks like the one at left (but with more spacing). When MATLAB performs a calculation, it wants to “name” the result of that calculation. Unless you give it a name, it will use “ans”. If you reuse a name, MATLAB will “throw-out” the previously stored calculation. Be careful!
12
Getting Going – Command Window
Try It! To see this, at the Command Prompt (>>), type the following: >> ans [press Enter] >> x [press Enter] The variable “ans” contains the last calculated value – 25, and “x” contains the defined value 100.
13
Getting Going – Command Window
It is very easy to “clutter” up your Command Window. Use the command “clc” to erase it (but not get rid of any defined variables). Try It! At the Command Prompt (>>), type the following: >> clc [press Enter] Nice and clean!
14
Getting Going – Command Window
Sometimes you would like to stop MATLAB from repeating what you typed into the Command Window. To stop display, add a ; to the end of a command. When first learning MATLAB unexpected results can happen, so a good way to learn is to leave the data display on. Try It! At the Command Prompt (>>), type the following: >> matrix = ones(1000) [press Enter] >> matrix = ones(1000);
15
Getting Going – Workspace Window
The Workspace Window keeps track of the variables you have defined as you execute commands in the Command Window Right now in our session we have three variables defined: “ans”, “matrix” and “x”
16
Getting Going – Workspace Window
A list of the variables and arrays in the current workspace can be generated with the whos command. >> whos Name Size Bytes Class X x double array ans x double array area x double array circum x double array radius x double array string x char array x x double array y x double array
17
Getting Going – Workspace Window
The contents of any variable or array may be determined by typing the appropriate name in the command window. >> string The area of the circle is A variable can be deleted from the workspace with the clear command. Clear var1 var2 …. The command clear [or clear variables] deletes all variables from the current workspace.
18
Getting Going – Workspace Window
You can view and change the contents of a variable by double-clicking on it in the Workspace Window. Try It! Perform the following steps: Double-click on the variable “x” in the Workspace Window Type “200” (no quotes) into the second column and press enter. Check out the change in the Workspace Window. Back at the Command Prompt, type “x” (no quotes) and press Enter. Press the X at the top right of the Variable Editor to close the window
19
Getting Going – Command History Window
The Command History Window keeps a running list of the commands you have entered at the Command Prompt. Two ways you can execute a command that you see in the History Window: Click and drag it to the Command Window. This allows you to edit the command if desired. Select it in the History window and press ENTER. It automatically evaluates. Try It! Perform the following: Scroll through the Command History until you find sqrt(25) Click and drag this line to the Command Window. Press ENTER to evaluate the command.
20
Getting Going – Current Directory Window
The Current Directory Window shows all the files in the location defined in the current directory path. This is the location MATLAB uses when accessing or saving files.
21
Getting Going – Edit Window
An Edit Window is used to create new M-files or to modify existing ones. The Edit Window allows you to write a series of commands (a program) and save those commands to your computer The Edit Window is essentially a programming text editor with the MATLAB languages features highlighted in different colors. Comments in an M-file appear in green Variable and numbers appear in black Complete character string appear in Magenta Incomplete character string appear in red Language keywords appear in Blue Try It! Perform the following: On the menu at the top of the screen, click on File > New > M-File
23
Getting Going – Edit Window
After an M-file is saved, it may be executed by typing its name in the command window. >>carea
24
Figure Windows A figure window is used to display MATLAB graphics.
A figure can be a 2-D or 3-D plot of data, an image or a GUI.
26
Docking and Undocking Windows
When a window is docked, it appears as a pane within the MATLAB desktop. When it is undocked it appears as an independent window separate from the desktop. Dock (up arrow) Undock (down arrow)
27
Getting Help Select ? From desktop toolbar
Type helpdesk in command window or Type helpwin in the command window Type Help at the command prompt, MATLAB will display a list of possible help topics in the command window. Type Help FunctionName display help for perticular function Lookfor FunctionName Ex. Lookfor inverse
28
Getting Help Help command searches for exact function name match, while lookfor command searches the quick summary information in each function for a match. Lookfor slower than Help but improve chances of getting back useful information.
29
A Few Important Command
Demo Display Demo Clc Clear Command Window Clf Clear Figure Window Clear Cleared variables in the workspace ^C Abort program execution ! Any character after the ! Will be sent to the OS and executed as though they had been typed at the OS command prompt. Diary Keep track of everything done during a MATLAB session. Diary off & Diary on
30
The MATLAB Search Path MATLAB has a search path that it uses to find M-files. It looks for the same name as a variable. If it is a variable, MATLAB displays the current contents of the variable. It checks to see if the name is an M-file in the current directory. If it is, MATLAB executes the function or command. It checks to see if the name is an M-file in any directory in the search path. If it is, MATLAB executes the function or command
31
Which filename/function name >> which sinX
It will display the path of your file >> which sinX C:\MATLAB7\work\sinX.m
32
Variables and Arrays The fundamental unit of data in any MATLAB program is the array. Array can be classified as either vectors or matrices. Vector is used to describe an array with only one dimension, while the term matrix is usually used to describe an array with 2 or more dimensions. The size of an array is specified by the number of rows and the number of columns in the array, with the number of rows mentioned first.
33
Variables and Arrays A =
1 2 3 4 5 6 A = This is a 3 X 2 matrix containing 6 elements B = [ ] This is a 1 X 4 array containing 4 elements, known as a row vector C = 1 2 3 This is a 3 X 1 array containing 3 elements, known as a Column vector A(2,1) = 3 and C(2) = 2
34
Variables and Arrays a = [1 2;3 4;5 6] b = [ ] c = [1;2;3]
35
Variables and Arrays Variables name must begin with a letter followed by any combination of letters, numbers and underscore(_) character. Only the first 63 characters are significant; if more than 63 are used, the remaining characters will be ignored. The MATLAB language is case-sensitive.
36
Variables and Arrays The most common types of MATLAB variables are double and char. Double can hold real, imaginary or complex values. Variables of type char consist of scalar or arrays of 16-bit values, each representing a single character MATLAB is a weakly typed language. Variables may be created at any time by simply assigning values to them, and the type of data assigned to the variable determines the type of variable that is created.
37
Initializing Variables in MATLAB
MATLAB variables are automatically created when they are initialized. Assign data to the variable. Input data into the variable from the keyboard. Read data from a file. Var = expresssion Eg. Var = 40i; Var2 = var/5; Array = [ ]; X = 1; y = 2;
38
Initializing Variables in MATLAB
2 3 [1,2,3;4,5,6] = 2 3 [1,2,3 4,5,6] = [ ] This expression contains an empty array, which contains no rows and no columns. Note that this is not the same as an array containing zeros. The number of elements in every row of an array must be the same, and the number of elements in every column must be the same.
39
Initializing Variables in MATLAB
B = [A(2) 7 A] C(2,3) = 5 D = [1 2] D(4) = 4 then D=[ ] If a ; added at the end of the statement, the echoing disapperas.
40
Initializing with Shortcut Expression
Colon operator specifies a whole series of values by specifying the first value, the stepping increment and the last value. First:Incr:Last Ex. a1 =1:2:10 A1 = angles = (0.01:0.01:1.00)
41
Initializing with Shortcut Expression
Shortcut expression can be combined with transpose operator(‘). f=[1:4]’ G = 1:4; H = [G’ G’]
42
Initializing with Built-In Functions
z1 = zeros(2) Z2 = zeros(2,3) Z3 = [1 2;3 4] Z4 = zeros(size(z3)) Ones(3) eye
43
MATLAB functions useful for Initializing Variables
Zeros(n) Generate an n X n matrix of zeros Zeros(n,m) Generate an n X n matrix of zeros Zeros(size(arr)) Generate a matrix of the zeros the same size as arr ones(n) Generate an n X n matrix of ones ones(n,m) Generate an n X n matrix of ones ones(size(arr)) Generate a matrix of the ones the same size as arr
44
MATLAB functions useful for Initializing Variables
Eye(n) Generate an n X n identity matrix Eye(n,m) Generate an n X m identity matrix Length(arr) Returns the length of a vector or the longest dimension of a 2-D array. Size(arr) Returns two values specifying the number of rows and columns in arr.
45
Initializing variables with Keyboard Input
Use input function Single number or array Array must be enclosed in brackets Input function use ‘s’ as a second argument, then the input data is returned to user as a character string.
46
Initializing variables with Keyboard Input
In1 = Input(‘Enter Data: ‘); In2 = input(‘Enter Data: ‘,’s’); In3 = input(‘Enter value: ‘) - only press enter
47
Multidimensional Array
c(:,:,1) = [1,2,3;4,5,6]; c(:,:,2) = [7 8 9;10,11,12]; >> whos c Name Size Bytes Class c x3x double array
48
Multidimensional Array
>> c c(:,:,1) = c(:,:,2) =
49
Storing Multidimensional Arrays in Memory
1 2 3 4 5 6 7 8 9 10 11 12 b a Layout of values In memory for Array a. Data Values for array a.
50
Multidimensional Array
Always use the proper number of dimension when addressing a multidimensional number.
51
Subarrays Arr1 = [ ] Arr1(3) Arr1([1 4]) Arr1(1:2:5) Arr2 = [1 2 3; ;3 4 5]; Arr2(1,:) Arr2(:,1:2:3) Arr2(:,1:3) Arr2(:,2:3)
52
End Function Arr3=[ ]; Arr3(5:end) Arr3(end) Arr4 = [ ; ; ] Arr4(2:end,2:end) The value returned by end is always the highest value of a given subscript.
53
Using Subarrays on the LHS of an assignment
If values are assigned to a subarray, only those values are updated while all other values in the array remain unchanged. If values are assigned to an array the entire contents of the array are deleted and replaced by the new values. Arr5 = [20 21;22 23]
54
Assigning a Scalar to a Subarray
55
Deleting a row or column
Any row(s) or column(s) of a matrix can be deleted by setting the row column to null vector. A(2,:) = [ ] delete the 2nd row of a matrix A a(4,:)=[ ] add a 4th row of a matrix a a(:,4)=[4] add the forth column with each value is 4 a(:,5) = [ ] add 5th column with value A(:,3:5) = [ ] deletes the 3rd to 5th columns of A A([1 3],:) = [ ] deletes the 1st and 3rd row of A
56
Reshaping matrices Matrices can be reshaped into a vector or any other appropriately sized matrix All the elements of matrix A can be strung into a single column vector B by the command B=A(:) If matrix A is an m x n matrix, it can be reshaped into a p x q matrix, as long as m x n = p x q with the command reshape(A,p,q). If A is a 6x6 matrix then Reshape(A,9,4) transforms A into 9 x4 matrix Reshape(A,3,12) transform A into 3x12 matrix
57
Functions used in matrix manipulation
Transpose of a matrix A is obtained by typing A’ DET(X) is the determinant of the square matrix X. INV(X) is the inverse of the square matrix X. Rot90(x) rotate a matrix by 90 Fliplr(x) Flips a matrix from left to right Flipud(x) Flips a matrix from up to down Tril(x) Extracts the lower triangle part of a matrix Triu(x) Extract the upper triangle part of matrix
58
Linspace, Logspace Linspace(a,b,n) generates a linearly spaced vector of length n from a to b. U=linspace(0,20,5) Logspace(a,b,n) generates a linearly spaced vector of length n from 10a to 10b V=logspace(0,3,4) Logspace(a,b,n) is the same as 10.^(linspace(a,b,n))
59
Utility Matrices eye(m,n) returns an m by n matrix with 1’s on the main diagonal zeros(m,n) returns an m by n matrix of 0s ones(m,n) returns an m x n matrix of ones rand(m,n) returns an m x n matrix of random numbers randn(m,n) returns an m x n matrix of normally distributed random numbers diag(v) generates a diagonal matrix with vector v on the diagonal e.g.diag(-5:5) diag(a) extracts the diagonal of matrix a as a vector diag(a,1) extracts the first upper off-diagonal vector of matrix a
60
Linear Equation solution
5x-3y+2z = 10 -3x+8y+4z = 20 2x+4y-9z = 9 Ax = B A=[5 -3 2;-3 8 4;2 4 -9] X=[x;y;z] B=[10;20;9]
61
Linear Equation solution
B=[10;20;9]; X=A\B; [or x = inv(A)*B] C = A*X; CC=[A B]; CR=rref(CC)
62
Solution 5* – 3* *1.1868
63
Special Values Function Purpose Pi
Constant pi to 15 significant digits i,j Contain the value i,j (Complex Number) Inf Infinity Nan Not a Number (0/0) Clock Current date and time Date Current date Eps Epsilon Ans A special variable used to store the result of an expression. If the result is not explicitly assigned to some other variables
64
Displaying Output Data
Format Command ( ) Format Short (Default) 4 digit after decimal point Format Long Format Short e Format Short g Format long e Format long g Format bank Format hex Format rat Format compact Format loose Format only signs are printed
65
Disp Function Disp function accepts an array argument, and displays the value of the array in the command window. If the array is of type char, then the character string contained in the array is printed out. Num2str Int2str Str = [‘The value of pi = ‘ num2str(pi)]; Disp(str)
66
Fprintf function The fprintf function displays one or more values together with related text and lets the programmer control the way the displayed values appear. Fprintf(format,data) %d, %e, %f, %g and \n are format. Fprintf(‘The value of pi is %f \n’, pi)
67
Data Files The save command saves data from the current MATLAB workspace into a disk file. Save filename var1 var2 var3 where filename is the name of a file in which variables are saved. By default the file extension is .mat If no variables are specified then the entire contents of the workspace are worked.
68
Data Files MATLAB saves MAT-files in special format that preserves many details including the name and the type of each variable, the size of each array, and all data values. A MAT-file created on any platform (PC, Mac, Unix or Linux) can be read on any other platform, so MAT-files are a good way to exchange data between computers if both computers run MATLAB. The MAT-file is in format that cannot be read by other programs. If data must be shared with other programs, then the –ascii option should be specified, and the data values will be written to the file as ASCII character string separated by spaces. However, the special information (eg. Varibale names and types) is lost when the data is saved in ASCII format, and the resulting data file much larger.
69
Data Files x = [ ; ]; save x.dat x –ascii
70
Data Files The load command loads data from a disk file into current workspace Load filename MATLAB can load data created by other programs in space-separated ASCII format. If the filename has any extension other than .mat, then the load command will treat the file as an ASCII file.
71
Data Files X. dat having 1.23 3.14 6.28 -5.1 7 0
load x.dat will create 2X3 array named X in the current workspace. The load statement can be forced to treat a file as a MAT-file by specifying the –mat option. load –mat x.dat
72
Image Processing A digital image is composed of pixels which can be thought of as small dots on the screen. A digital image is an instruction of how to color each pixel. A typical size of an image is 512 x 512 pixels. It is convenient to let the dimensions of image to be power of 2. [29 = 512] An image is of size m x n if it is composed of m pixels in the vertical dimensions and n pixels in the horizontal direction.
73
Image Processing We have an image on the format 512 x 512 pixels that means the data for the image must contain information about pixels which requires a lot of memory. Hence, compressing image is essential for efficient image processing.
74
Image formats supported by MATLAB
jpeg tiff gif bmp png hdf Pcx xwd
75
Working formats in MATLAB
If an image is stored as a JPEG-image on the disk we first read it into MATLAB. However, in order to start working with an image, for example perform a wavelet transform on the image, we must convert it into different format.
76
Intensity image This is equivalent to a gray scale image.
It represents an image as a matrix where every element has a value corresponding to how bright/dark the pixel at the corresponding position should be colored. There are 2 ways to represent the number that represents the brightness of the pixel: 1. the double class (data type). This assigning a floating number between 0 and 1 to each pixel. The value 0 corresponds to black and the value 1 corresponds to white.
77
Intensity image 2. The class is called uint8 which assigns an integer between 0 and 255 to represent the brightness of a pixel. The value 0 corresponds to black and value 255 corresponds to white. The class uint8 only requires roughly 1/8 of the storage compared to the class double. On the other hand, many mathematical functions can only be applied to the double class.
78
Binary Image This image format also stores an image as a matrix but can only color a pixel black or white (and nothing in between). It assigns a 0 for black and a 1 for white.
79
Indexed image This is a practical way of representing color images.
An indexed image stores an image as 2 matrices. The first matrix has the same size as the image and one number for each pixel. The second matrix is called the color map and its size may be different from the image. The numbers in the first matrix is an instruction of what number to use in the color map matrix.
80
RGB image This is another format for color images.
It represents an image with three matrices of size matching the image format. Each matrix corresponds to one of the colors Red, Green or Blue and gives an instruction of how much of each of these colors a certain pixel should use.
81
Multiframe image This is very common in biological and medical imaging where you might study a sequence of slices of a cell. For these cases, the multiframe format is a convenient way of working with a sequence of images.
82
How to convert between different formats
Operation Command Convert between intensity/indexed/RGB format to binary format dither() Convert between intensity format to indexed format gray2ind() Convert between indexed format to intensity format ind2gray() Convert between indexed format to RGB format ind2rgb() Convert a regular matrix to intensity format by scaling mat2gray() Convert a RGB format to intensity format rgb2gray() Convert a RGB format to indexed format rgb2ind()
83
The command mat2gray is useful if we have a matrix representing an image but the values representing the grey scale range between 0 and 1.0 The command mat2gray automatically re-scales all entries so that they fall within 0 and 255(if we use the uint8 class) or 0 and 1 (if we use the double class)
84
How to convert between double and uint8
When you store an image, you should store it as a uint8 image since this requires far less memory than double. When you are processing an image you should convert it into a double. Im2double function Convert image to double precision. Im2unit8 function Convert image to eight-bit unsigned integers.
85
How to read files When you encounter an image you want to work with, it is usually in form of a file. Once we are done processing on an image, we want to write back to a JPEG-file. This is done using the imread and imwrite functions. These commands require the Image Processing Toolbox.
86
IMREAD IMREAD Read image from graphics file.
A = IMREAD(FILENAME,FMT) reads a grayscale or color image from the file specified by the string FILENAME, where the string FMT specifies the format of the file. i=imread('pout.tif') imread('C:\Users\Public\Pictures\Sample Pictures\Autumn Leaves.jpg','jpg')
87
imshow To show image use imshow command IMSHOW Display image.
IMSHOW(I,N) displays the intensity image I with N discrete levels of gray. If you omit N, IMSHOW uses 256 gray levels on 24-bit displays, or 64 gray levels on other systems. imshow(i) Whos command is used to show how I is stored in memory
88
imhist IMHIST Display histogram of image data.
IMHIST(I) displays a histogram for the intensity image I whose number of bins are specified by the image type. If I is a grayscale image, IMHIST uses 256 bins as a default value. If I is a binary image, IMHIST uses only 2 bins. imhist(i) i2=imhist(i)
89
IMWrite IMWRITE Write image to graphics file.
IMWRITE(A,FILENAME,FMT) writes the image A to the file specified by FILENAME in the format specified by FMT. imwrite(i,'myimg','jpg'); imwrite(i2,'myimg.png')
90
imfinfo Imfinfo function to see what was the image return to the disk
IMFINFO Information about graphics file. INFO = IMFINFO(FILENAME,FMT) returns a structure whose fields contain information about an image in a graphics file. FILENAME is a string that specifies the name of the graphics file, and FMT is a string that specifies the format of the file. The file must be in the current directory or in a directory on the MATLAB path. If IMFINFO cannot find a file named FILENAME, it looks for a file named FILENAME.FMT. imfinfo('myimg.png')
91
blkproc Blkproc function is used to find a rough estimation of the background illumination. I = imread('liftingbody.png'); fun = inline('std2(x)*ones(size(x))'); I2 = blkproc(I,[32 32],fun); imview(I),imview(I2,[]) Surf command is used to create a surface display of the block processing approximation backapprox = double(I2/255); surf(backapprox)
92
Imresize Imresize function is used to resize the image.
backapprox256 = imresize(backapprox,[ ],'bilinear'); imshow(backapprox256)
93
Subtract the background image from the Original Image
Change the storage class of I to double because subtraction can only be performed on double arrays. i = im2double(i) Subtract backapprox256 from I and store it in a new array i2 I2= 1 – backapprox256 i=im2double(i); i2= 1-backapprox256; imshow(i2)
94
Adjust the image intensity values
IMADJUST Adjust image intensity values or colormap. J = IMADJUST(I) maps the values in intensity image I to new values in J such that 1% of data is saturated at low and high intensities of I. This increases the contrast of the output image J. I = imread('pout.tif'); J = imadjust(I); imview(I), imview(J) K = imadjust(I,[ ],[]); imview(K)
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.