350 likes | 745 Views
Basics of MATLAB 2- Programming in MATLAB. By DR. Wafaa Shabana Email: wrs_coms@yahoo.com. Table of Contents:. 1. Introduction 2. MATLAB m-files. 3. Flow control in MATLAB. 4 . Image Processing using MATLAB 5 . Questions? 6 . References. 1. Introduction:. Recall that:
E N D
Basics of MATLAB 2- Programming in MATLAB By DR. Wafaa Shabana Email: wrs_coms@yahoo.com
Table of Contents: 1. Introduction 2. MATLAB m-files. 3. Flow control in MATLAB. 4. Image Processing using MATLAB 5. Questions? 6. References
1. Introduction: • Recall that: • Everything in MATLAB is a matrix ! • The MATLAB environment is command oriented somewhat like UNIX. • If a statement is terminated with a semicolon ( ; ), no results will be displayed. Otherwise results will appear before the next prompt. • ans Default variable name for results • % start comment which ends at end of line
The colon operator ( : ) to specify range • MATLAB supports six relational operators. Less Than < Less Than or Equal <= Greater Than > Greater Than or Equal >= Equal To == Not Equal To ~=
MATLAB supports three logical operators. not ~ % highest precedence and & % equal precedence with or or | % equal precedence with and
MATLAB is case-sensitive Programming language. • Variable names can contain up to 63 characters (as of MATLAB 6.5 and newer) • Variable names must start with a letter followed by letters, digits, and underscores • Examples: my_name, day2 % valid variable names Invalid variable name: my-name %minus not allowed 2day %must start with letter %x % not allowed character @room %not allowed character
Some of useful MATLAB commands • who List known variables • whos List known variables plus their size • help >> help sqrt Help on using sqrt • lookfor >> lookforsqrt Search for keyword sqrt in m-files • what >> what a: List MATLAB files in a: • clear Clear all variables from work space • clear x y Clear variables x and y from work space • clc Clear the command window (clear the screen) • save saves the workspace load loads a saved workspace or data file
2. MATLAB m-files: • There is no doubt that you can do a lot of work in the command window. However, when the amount of instructions needed to complete a task increases or you need to re-execute a block of instructions several times, the command window is a poor choice. The best choice is to write a MATLAB program.
MATLAB programs are stored as text files. • The files can be loaded into the MATLAB command environment where they are then interpreted and executed. MATLAB supports two types of programs: 1- script files and 2- function files.
Script files consist of sequences of instructions stored in text files. The files are commonly referred to as m-files because of the .m extension used. • An m-file can be created by any text editor or word processor. • If a word processor is used, make sure to save the file as a text file. • MATLAB has its own built-in text editor. • To launch it, type the command edit in the command window
Example (1): %this is our first m.file %saved as first.m %plot a graph of a cos function clear t = 0: 0.001:10; y = cos (2*pi*t); plot(t,y) title(‘My first graph’) xlabel(‘time, sec’) ylabel(‘values of y’)
Remark: 1- Before trying to run your program, make sure that its file is on the MATLAB path. 2- Use the which function to see if your program is on the path: which first 3-You have the choice of operating the debugger from the Editor window that displays your program, from the MATLAB command line, or both.
Function files: • The main difference between a script and a function is that a function accepts input from and returns output to its caller, whereas scripts do not. • You define MATLAB functions in a file that begins with a line containing the function key word. • Question: Can we define a function within a script file or at the command window?
* Functions always begin with a function definition line for example function y = average(x) • The function ends either with the first matching end statement, the occurrence of another function definition line, or the end of the file, whichever comes first.
Example: • function y = area(x1,x2) • %this function computes the area of a rectangle • %input: length x1 and width x2 • %output: area y • x1 =input('Enter the width:'); • x2 =input('Enter the length:'); • y = x1 * x2; • disp(‘The area is %d’, y)
input Request user input Syntax evalResponse = input(prompt) strResponse = input(prompt, 's') disp Display text or array Syntax disp(X)
If the function is supposed to return more than one value, the syntax is: function [output_1,output_2,…]= function_name(input_1, input_2,…) Question: What is the difference between MATLAB functions and C-functions? Note that: • The use of the editor is pretty straight-forward. The advantage of using MATLAB’s editor is that color coding and formatting is built in.
3. Control flow in MATLAB: Decision in MATLAB: 1- if statement: if (logical statement) block of code to execute if logical statement is true end 2- if …………else statement: if (logical statement) block of code to execute if logical statement is true else block of code to execute if logical statement is false end
3- Nested if ------else statement: if (logical statement 1) block of code to execute if logical statement 1 is true elseif (logical statement 2) block of code to execute if logical statement 2 is true elseif(logical statement n) block of code to execute if logical statement n is true else block of code to execute if all logical statements are false end
4- switch statement: switch evaluative expression case value_1 block of code to execute if the evaluative expression is value_1 case value_2 block of code to execute if the evaluative expression is value_2 case value_n block of code to execute if the evaluative expression is value_n otherwise block of code to execute if the evaluative expression is not any of the values end
2- Iteration in MATLAB: 1- for statement: for i = 1:10 % execute these commands end 2- while statement: while x <= 10 % execute these commands end
break statement: Terminate execution of for or while loop Syntax break return statement: Return to invoking function Syntax return continue statement: Pass control to next iteration of for or while loop Syntax continue
4. Image Processing in MATLAB: Image processing toolbox is one of the most useful toolboxes in MATLAB. This toolbox supports a wide range of image processing operations. There are five types of images in MATLAB: 1- Binary image : {0, 1}{black white} 2- Gray-scale image: [0,255] {shades of gray} 3- True color image: m x n x 3 4- Intensity image: [0, 1] or uint8 5- Indexed images: m x 3 color map
1- Reading an image: I = imread(‘image name’) It reads an image from an image file and store it In a matrix I 2- displaying an image: imshow(‘image_name’) 3- image size size(‘image_name’)
Check the Image in Memory < Name, Size, Bytes, Class > whos Name Size Bytes Class ans 291x240 69840 uint8 array Grand total is 69840 elements using 69840 bytes • uint8[0, 255] • uint16 [0, 65535] • double[0, 1]
Resizing Images • B = imresize(A, scale) • B = imresize(A, [mrowsncols])
For example: clear close all y= imread('pic2.jpg'); I1 = imresize(y, 0.5); I2 = imresize(y,[256 256]); figure imshow(y) figure imshow(I1) figure imshow(I2)
Some useful commands: im2bw Convert image to binary image, based on threshold Syntax BW = im2bw(I, level) BW = im2bw(X, map, level) BW = im2bw(RGB, level) rgb2gray Convert RGB image or colormap to grayscale
image Display image object imwrite Write image to graphics file Syntax imwrite(A,filename,fmt) e.g. imwrite(I, ‘wafaa’, ‘gif’)
5. Questions? (Mini project in MATLAB): 1- Encoding step: Write a m-function that hides some information (e.g. : your name) into a given image. (watermarked image) 2- Decoding Step: Write an m-function that receives the watermarked image and extract the water mark from it.
6. References: You can read the following references: • 1- “The Basics of MATLAB” Jeffrey O. Bauer • 2- www.mathworks.com • 3. “MATLAB tutorial for beginners” JyotirmayGadewadikar http://arri.uta.edu/acs/ Need further help? Contact me
Thank you for your attendance and hope you have not wasted your time.