- 71 Views
- Uploaded on
- Presentation posted in: General

Introduction to MATLAB

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Introduction to MATLAB

Introduction to MATLAB

Dr. Hiren D. Joshi

Department of Computer Science

Rollwala Computer Centre

Gujarat University

- 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.

- 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.

- 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.

- 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.

- 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

- 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.

- >> X1 = 1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6
- >> 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”

Try It!

At the Command Prompt, type the following commands (press Enter after each):

>> 25/5

>> 5^2

>> 25 + 5

>> sqrt(25)

- 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.

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.

- 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!

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.

- 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!

- 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);

- 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”

- A list of the variables and arrays in the current workspace can be generated with the whos command.
>> whos

- Name Size Bytes Class
- X1 1x1 8 double array
- ans 1x1 8 double array
- area 1x1 8 double array
- circum 1x1 8 double array
- radius 1x1 8 double array
- string 1x33 66 char array
- x 1x61 488 double array
- y 1x61 488 double array

- 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 19.635

- 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.

- 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

- 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.

- 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.

- 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

- After an M-file is saved, it may be executed by typing its name in the command window.
- >>carea

- 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.

- 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)

- 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

- 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.

- Demo Display Demo
- ClcClear Command Window
- ClfClear Figure Window
- ClearCleared 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.
- DiaryKeep track of everything done during a MATLAB session. Diary off & Diary on

- 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

- Which filename/function name
- It will display the path of your file
>> which sinX

- C:\MATLAB7\work\sinX.m

- It will display the path of your file

- 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.

1 2

3 4

5 6

This is a 3 X 2 matrix containing 6 elements

- A =

B = [1 2 3 4]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

- a = [1 2;3 4;5 6]
- b = [1 2 3 4]
- c = [1;2;3]

- 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.

- 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.

- 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 = [1 2 3 4];
- X = 1; y = 2;

- 2 3
- 4 5 6

- [1,2,3;4,5,6] =

- 2 3
- 4 5 6

[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.

- A = [0 1+7]
- B = [A(2) 7 A]
- C(2,3) = 5
- D = [1 2]
- D(4) = 4 then D=[1 2 0 4]
- If a ; added at the end of the statement, the echoing disapperas.

- 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 = 1 3 5 7 9

- angles = (0.01:0.01:1.00)

- Shortcut expression can be combined with transpose operator(‘).
- f=[1:4]’
- G = 1:4;
- H = [G’ G’]

- z1 = zeros(2)
- Z2 = zeros(2,3)
- Z3 = [1 2;3 4]
- Z4 = zeros(size(z3))
- Ones(3)
- eye

- 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

- 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.

- 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.

- In1 = Input(‘Enter Data: ‘);
- In2 = input(‘Enter Data: ‘,’s’);
- In3 = input(‘Enter value: ‘) - only press enter

- c(:,:,1) = [1,2,3;4,5,6];
- c(:,:,2) = [7 8 9;10,11,12];
>> whos c

- Name Size Bytes Class
- c 2x3x2 96 double array

>> c

- c(:,:,1) =
1 2 3

4 5 6

- c(:,:,2) =
7 8 9

10 11 12

b

a

Layout of values

In memory for

Array a.

Data Values for array a.

- A = [1 2 3;4 5 6;7 8 9;10 11 12]
- A(5) = 2
- Always use the proper number of dimension when addressing a multidimensional number.

- Arr1 = [1.1 -2.2 3.3 -4.4 5.5]
- Arr1(3)
- Arr1([1 4])
- Arr1(1:2:5)

- Arr2 = [1 2 3;-2 -3 -4;3 4 5];
- Arr2(1,:)
- Arr2(:,1:2:3)
- Arr2(:,1:3)
- Arr2(:,2:3)

- Arr3=[1 2 3 4 5 6 7 8];
- Arr3(5:end)
- Arr3(end)

- Arr4 = [1 2 3 4;5 6 7 8;9 10 11 12]
- Arr4(2:end,2:end)

- The value returned by end is always the highest value of a given subscript.

- Arr5 = [1 2 3 4;5 6 7 8;9 10 11 12]
- Arr5(1:2,[1 4]) = [20 21;22 23]
- 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]

- Arr4 = [1 2 3 4;5 6 7 8;9 10 11 12];
- Arr4(1:2,1:2) = 1

- 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,:)=[13 14 15] add a 4th row of a matrix a
- a(:,4)=[4] add the forth column with each value is 4
- a(:,5) = [1 2 3 4 5] add 5th column with value 1 2 3 4 5
- A(:,3:5) = [ ] deletes the 3rd to 5th columns of A
- A([1 3],:) = [ ] deletes the 1st and 3rd row of A

- 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

- 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

- 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))

- 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

- 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]

- A=[5 -3 2;-3 8 4;2 4 -9];
- B=[10;20;9];
- X=A\B; [or x = inv(A)*B]
- C = A*X;
- CC=[A B];
- CR=rref(CC)

- 5*3.4442 – 3*3.1982+2*1.1868
17.221 -9.5946 +2.3736

- 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)

- 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)

- 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.

- 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.

- x = [1.23 3.14 6.28; -5.1 7.00 0];
- save x.dat x –ascii

- 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.

- X. dat having
1.233.146.28

-5.170

- 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

- 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.

- We have an image on the format 512 x 512 pixels that means the data for the image must contain information about 262144 pixels which requires a lot of memory.
- Hence, compressing image is essential for efficient image processing.

- jpeg
- tiff
- gif
- bmp
- png
- hdf
- Pcx
- xwd

- 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.

- 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.

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.

- 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.

- 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.

- 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.

- 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.

- 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)

- 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.

- 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.

- 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')

- 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

- 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)

- 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')

- 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')

- 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)

- Imresize function is used to resize the image.
- backapprox256 = imresize(backapprox,[256 256],'bilinear');
- imshow(backapprox256)

- 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)

- 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,[0.3 0.7],[]);

imview(K)