Basic MATLAB Programming Course

146
Basic MATLAB Programming Course

description

Basic MATLAB Programming Course. What we will learn in this session. The basic MATLAB interface. Basic commands. Declaring & manipulating variables. Plotting graphs. Conditional Operators. Functions. Basic MATLAB Interface. Command window: Type your instructions here and press - PowerPoint PPT Presentation

Transcript of Basic MATLAB Programming Course

Page 1: Basic MATLAB Programming Course

Basic MATLAB Programming Course

Page 2: Basic MATLAB Programming Course

What we will learn in this session

The basic MATLAB interface. Basic commands. Declaring & manipulating variables. Plotting graphs. Conditional Operators. Functions.

Page 3: Basic MATLAB Programming Course

Basic MATLAB Interface

Page 4: Basic MATLAB Programming Course
Page 5: Basic MATLAB Programming Course

Command window: Type your instructions here and press ENTER to execute them.

Page 6: Basic MATLAB Programming Course

Example: Declare a column matrix withvalues 1,2 and 3.

Page 7: Basic MATLAB Programming Course

Command history: a list of instructions executed by MATLAB is shown here.

Page 8: Basic MATLAB Programming Course

Workspace: shows a list of variables created by MATLAB.As you can see, the value of ‘aaa’is shown.

Page 9: Basic MATLAB Programming Course

Another way to create a variable Is to press this button.

Page 10: Basic MATLAB Programming Course

MATLAB will prompt you to enter the variable name.

Page 11: Basic MATLAB Programming Course

As you can see, the variable name has been changed to bbb.

Page 12: Basic MATLAB Programming Course

To assign a value to bbb, you can do it intwo ways: 1) Using the command window.

2) Or by double clicking on bbb.

Page 13: Basic MATLAB Programming Course

When you click on bbb, the variableeditor window appears. You can typein new values into bbb by filling in the cells.

Page 14: Basic MATLAB Programming Course

An example is shown here.Try and do it yourself.

Page 15: Basic MATLAB Programming Course

To display variables at the console, you can type the variable name, or you can type disp(variable_name).

Page 16: Basic MATLAB Programming Course

To clear all variables from memory and close all figures, use the clear, close all command.

Page 17: Basic MATLAB Programming Course

As you can see, all workspace variables are deleted when you execute this command.

Page 18: Basic MATLAB Programming Course

To clear the command window,use the clc (clear console) command.

Page 19: Basic MATLAB Programming Course

As you can see, all console entries are deleted when you execute this command.

Page 20: Basic MATLAB Programming Course

If you want to see help,you can type help at the command window.

Page 21: Basic MATLAB Programming Course

Or you can press F1to display the help window. Click on Open Help Browser to search for a specific function.

Page 22: Basic MATLAB Programming Course

Example: search for function mean

Page 23: Basic MATLAB Programming Course

To create an m-file, 1) type edit at the command window, or 2) Press this button.

Page 24: Basic MATLAB Programming Course

The previous command willdisplay the editor window.The editor creates an m-filethat can be used to write your MATLAB programs.

Page 25: Basic MATLAB Programming Course

To execute a program, pressthe RUN button.

Page 26: Basic MATLAB Programming Course

This window will appear. Press the Change Directory button.

Page 27: Basic MATLAB Programming Course

You can see that the program hascreated two new variables in the Workspace.

Page 28: Basic MATLAB Programming Course

Basic Commands

Page 29: Basic MATLAB Programming Course

Variables

MATLAB can be used to initialize and manipulate many types of variables.Single value.MatrixString

Page 30: Basic MATLAB Programming Course

Declaring Single Variables

To declare single variables, type in a variable name and type in its value.

MATLAB will decide on the data type automatically, so you don’t have to declare its data type.

Example:var1 = 3; thisIsAVariable = 56;

Page 31: Basic MATLAB Programming Course
Page 32: Basic MATLAB Programming Course

Declaring Single Variables

Variables cannot have numbers or symbols in front of them.

Example of illegal variable names:1var#aaa

Page 33: Basic MATLAB Programming Course
Page 34: Basic MATLAB Programming Course

Matrix Variables

Matrix variables are initialized similar to single variables.

The values in a matrix variable is defined in square brackets.

Example:aaa = [1,2,3,4];bbb = [1;2;3;4];

Page 35: Basic MATLAB Programming Course

Row Matrix

To create a row matrix, use the comma to separate the values.

Example:rowMatrix = [1,2,3,4,5];

Page 36: Basic MATLAB Programming Course

Example

Page 37: Basic MATLAB Programming Course

Try It Yourself

Create a row matrix named var1 with the values of 1, 3, 5 in it.

Create a row matrix named mat1 with the values of 10, 20, 30, 40, 50, 60 in it.

Create a row matrix named var2 with the values of 1, 3, 5, 6, 8, 10, 11 in it.

Page 38: Basic MATLAB Programming Course

Column Matrix

To create a column matrix, use the semicolon to separate the values.

Example:colMatrix = [1;2;3;4;5];

Page 39: Basic MATLAB Programming Course

Example

Page 40: Basic MATLAB Programming Course

Try It Yourself

Clear and close all variables, and clear console. Create a column matrix named col1 with the

values of 2, 6, 9 in it. Create a column matrix named mat3 with the

values of 15, 23, 37, 48, 59, 61 in it. Create a column matrix named colMatrix with

the values of 1, 3, 5, 6, 8, 10, 11 in it.

Page 41: Basic MATLAB Programming Course

Regular Matrix

To create a regular matrix, use the comma to separate each value in a row, and a semicolon to enter the value for a new row.

Example:mat1 = [1,2,3;4,5,6;7,8,9];

Page 42: Basic MATLAB Programming Course

Example

Page 43: Basic MATLAB Programming Course

Try It Yourself

Create this matrix:

43

21A

Page 44: Basic MATLAB Programming Course

Try It Yourself

Create this matrix:

535

542

542

matrixB

Page 45: Basic MATLAB Programming Course

Accessing Matrix Values

To access a specific value inside a matrix, use this command:

matrixName(rowNumber, colNumber) Example: to access a value inside row 3

and column 2.matrixName(3,2)

Page 46: Basic MATLAB Programming Course
Page 47: Basic MATLAB Programming Course

Try It Yourself

Create this matrix:

Try to get values 9, 3 and 1 from the matrix and save it into three variables.

176

1098

543

matrixB

Page 48: Basic MATLAB Programming Course

Accessing Whole Columns and Rows To get a whole column, use this

command: varA = matName(:,colNumber); To get a whole row, use this command: varA = matName(rowNumber,:);

Page 49: Basic MATLAB Programming Course

Example

Page 50: Basic MATLAB Programming Course

Try it Yourself

Create this matrix:

Get all the values from row 3 and save it into a new variable.

Get all the values from column 1 and save it into a new variable.

176

1098

543

matrixB

Page 51: Basic MATLAB Programming Course

Creating a Matrix of Zeros

To create a matrix of zeros, use the zeros command.

Example: create a 6 X 5 matrix of zeros. zeros(6,5)

Page 52: Basic MATLAB Programming Course

Example

Page 53: Basic MATLAB Programming Course

Creating a Matrix of Ones

To create a matrix of ones, use the ones command.

Example: create a 5 X 3 matrix of ones. ones(5,3)

Page 54: Basic MATLAB Programming Course

Example

Page 55: Basic MATLAB Programming Course

Creating a Matrix of Random Numbers To create a matrix of random numbers,

use the rand command. Example: create a 4 X 4 matrix of random

numbers. rand(4,4)

Page 56: Basic MATLAB Programming Course

Example

Page 57: Basic MATLAB Programming Course

Getting the Size of the Matrix

To get the size of the matrix, use the size command.

Example: to get the size of matrix aaa. [numRow, numCol] = size(aaa);

Page 58: Basic MATLAB Programming Course

Example

Page 59: Basic MATLAB Programming Course

Transposing a Matrix

A transpose operation changes the column of a matrix into rows, and rows into columns.

To do a transpose, use the single quote operator.

Page 60: Basic MATLAB Programming Course

Example: Transposing a Row Matrix

Page 61: Basic MATLAB Programming Course

Example: Transposing a Column Matrix

Page 62: Basic MATLAB Programming Course

Example: Transposing a Regular Matrix

Page 63: Basic MATLAB Programming Course

Finding the Maximum Value

To find the maximum value for a matrix, use the max function.

Example: find the maximum value in matrix aaa.

maxVal = max(aaa);

Page 64: Basic MATLAB Programming Course

Example

Max finds the maximum value in each column

When it is run again on the result, it returns the single-largest value in the matrix.

Page 65: Basic MATLAB Programming Course

Finding the Minimum Value

To find the minimum value for a matrix, use the min function.

Example: find the minimum value in matrix aaa.

minVal = min(aaa);

Page 66: Basic MATLAB Programming Course

Example

Min finds the minimum value in each column

When it is run again on the result, it returns the minimum value in the matrix.

Page 67: Basic MATLAB Programming Course

Finding the Sum of Columns

To find the sum of each column, use the sum command.

Example: find the sum for each column in matrix aaa.

colSum = sum(aaa);

Page 68: Basic MATLAB Programming Course

Example

Page 69: Basic MATLAB Programming Course

Adding Matrices

To add matrices, use the + operator. Example: add matrices A and B.

A + B. Make sure that the matrices are the same

size.

Page 70: Basic MATLAB Programming Course

Example

Page 71: Basic MATLAB Programming Course

Subtracting Matrices

To subtract matrices, use the - operator. Example: subtract matrix B from A.

A - B. Make sure that the matrices are the same

size.

Page 72: Basic MATLAB Programming Course

Example

Page 73: Basic MATLAB Programming Course

Multiplying Matrices

To multiply matrices, use the .* operator. Example: multiply matrices A and B.

A .* B. Make sure that the matrices are the same

size.

Page 74: Basic MATLAB Programming Course

Example

Page 75: Basic MATLAB Programming Course

Dividing Matrices

To divide matrices, use the ./ operator. Example: divide matrices A with B.

A ./ B. Make sure that the matrices are the same

size.

Page 76: Basic MATLAB Programming Course

Example

Page 77: Basic MATLAB Programming Course

Sorting Matrices

To sort a matrix, use the sort command. Example: sort matrix A in ascending order.

B = sort(A,’ascend/descend’)Default is ascending mode.

Page 78: Basic MATLAB Programming Course

Example: Sorting a Row Matrix

Page 79: Basic MATLAB Programming Course

Example: Sorting a Column Matrix

Page 80: Basic MATLAB Programming Course

Example: Sorting a Regular Matrix

Page 81: Basic MATLAB Programming Course

Example: Sorting a Row Matrix in Descend Mode

Page 82: Basic MATLAB Programming Course

Flipping a Matrix

A matrix can be flipped using the flipud or fliplr commands.

Command flipud flips the matrix in UP/DOWN direction.

Command fliplr flips the matrix in LEFT/RIGHT direction.

Page 83: Basic MATLAB Programming Course

Example: flipud

Page 84: Basic MATLAB Programming Course

Example: fliplr

Page 85: Basic MATLAB Programming Course

Strings

MATLAB also can accept and manipulate string variables.

A string is defined by enclosing it in single quotes.

Example: aString = ‘Hello World!’

Page 86: Basic MATLAB Programming Course

Example: Initializing a String

Page 87: Basic MATLAB Programming Course

Converting a String to Lowercase

To convert a string to lowercase, use the lower command.

Example: change string in matrix A to lowercase:B = lower(A)

Page 88: Basic MATLAB Programming Course

Example: Change String to Lowercase

Page 89: Basic MATLAB Programming Course

Converting a String to Uppercase

To convert a string to uppercase, use the upper command.

Example: change string in matrix A to uppercase:B = upper(A)

Page 90: Basic MATLAB Programming Course

Example: Change String to Uppercase

Page 91: Basic MATLAB Programming Course

Concatenate Strings

Concatenating string means merging two or more strings together.

To concatenate strings, use the strcat command.

Example: to concatenate str1 and str2:newStr = strcat(str1,str2)

Page 92: Basic MATLAB Programming Course

Example: Concatenate String

Page 93: Basic MATLAB Programming Course

Replace String

To replace part of the string with a new value, use the strrep command.

Example: replace the word ‘lama’ with the word ‘baru’ in the string str1.strrep(str1,’lama’,’baru’)

Page 94: Basic MATLAB Programming Course

Example: Replace String

Page 95: Basic MATLAB Programming Course

Plot

Page 96: Basic MATLAB Programming Course

Plot Function

The plot function can be used to draw the relationship between two variables.

Format:plot(x,y,lineParameters)

Page 97: Basic MATLAB Programming Course

Example: Plot the values of a random matrixclear, close allclc xxx = 1:100 yyy = rand(1,100) plot(xxx,yyy)

Page 98: Basic MATLAB Programming Course

Example

Page 99: Basic MATLAB Programming Course

Example: Draw sin(x)

clear, close allclc x = 0:pi/36:10*piy = sin(x) plot(x,y,‘m')

Page 100: Basic MATLAB Programming Course

Example

Page 101: Basic MATLAB Programming Course

Plot Styles

Page 102: Basic MATLAB Programming Course

Plot Styles

Page 103: Basic MATLAB Programming Course

Example: Plotting the lines using line parametersclear, close allclc xxx = 1:100 yyy = rand(1,100) plot(xxx,yyy)figure, plot(xxx,yyy,'g:') % the command figure is figure, plot(xxx,yyy,'r--')% used to create a newfigure, plot(xxx,yyy,':mo')% figure each time a plot

% is made.

Page 104: Basic MATLAB Programming Course

Example: Drawing two plots in the same figureclear, close allclc xxx = 1:100yyy = rand(1,100) aaa = 1:100bbb = rand(1,100) plot(xxx,yyy,'r')hold onplot(aaa,bbb,'-.gv')hold off

Page 105: Basic MATLAB Programming Course

Example: Drawing Bar Graphs

clear, close all

clc

x = 0:pi/36:2*pi

y = cos(x)

bar(x,y,'b')

Page 106: Basic MATLAB Programming Course

Example

Page 107: Basic MATLAB Programming Course

Example: Drawing a Stair-Step Plot

clear, close all

clc

x = -10:0.5:10

y = x.^2 + 2.*x + 2

stairs(x,y,'b')

Page 108: Basic MATLAB Programming Course

Example

Page 109: Basic MATLAB Programming Course

Image Manipulation

Page 110: Basic MATLAB Programming Course

Reading and Displaying an Image

To read an image, use the imread command.

Example: read an image file named ‘c:\aaa.jpg’ and store it in matrix A.A = imread(‘c:\aaa.jpg’)

To display an image, use the imshow(A) command.

Page 111: Basic MATLAB Programming Course

Example: Read and Display Image

Page 112: Basic MATLAB Programming Course

Manipulating an Image: Convert to Grayscale To convert an RGB image to grayscale,

use the rgb2gray command. Example: convert image A to grayscale:

B = rgb2gray(A)

Page 113: Basic MATLAB Programming Course

Example: Convert to Grayscale

clear, close allclc aaa = imread('d:\My Documents\My Pictures\50294.jpg');figure, imshow(aaa)bbb = rgb2gray(aaa)figure, imshow(bbb)

Page 114: Basic MATLAB Programming Course
Page 115: Basic MATLAB Programming Course

Saving an Image

To save an image, use the imwrite command.

Example: write image a into file xxx.jpg: imwrite(A,’xxx.jpg’,’jpg’)

Page 116: Basic MATLAB Programming Course

Conditional Operators

Page 117: Basic MATLAB Programming Course

If…else Operator

The if…else operator tests a condition. If the condition is true, then execute the if

block. If the condition is false, execute the else

block.

Page 118: Basic MATLAB Programming Course

If…else Operator

if (condition) % if blockelse % else blockend

% conditions that can be tested% == : is equal to% ~= : is not equal to% > : larger than% >= : larger than or equal% <= : less than or equal% < : less than

Page 119: Basic MATLAB Programming Course

Example

clear, close allclc aaa = rand(1,100);bbb = 1:1:100 color = 1; if (color == 1) % if block figure, plot(bbb,aaa,':r');else % else block figure, plot(bbb,aaa,'b');end

Page 120: Basic MATLAB Programming Course

Example

clear, close allclc x = 3; if (x > 5) disp('The number is more than 5.')elseif (x == 5) disp('The number is equal to 5.')else disp('The number is less than 5.')end

Page 121: Basic MATLAB Programming Course

For loop

Used to repeat a set of statements multiple times.

The for loop format is: for(startingvalue:increment:endingvalue)

Page 122: Basic MATLAB Programming Course

For Loop

clear, close allclc % i is the value of the counterfor i = initial_value:increment:ending_value % statements in this block will be executed

until i % reaches the ending_value end

Page 123: Basic MATLAB Programming Course

Example: Display value inside for loopclear, close allclc for i = 1:1:15 st1 = strcat('The value of i inside the loop is: ',int2str(i));

disp(st1)end

Page 124: Basic MATLAB Programming Course

Example: Display “Hello World” 10 Times

st1 = 'Hello World!';

for i = 1:1:10

disp(st1)

end

Page 125: Basic MATLAB Programming Course

Example: Check Value Inside Matrixclear, close allclc matA = [1.4,4.2,6.7,7.0; 5.5,6.7,8.9,3.0; 0.6,6.12,5.44,8.94][row,col] = size(matA) for i = 1:1:row for j = 1:1:col currNo = matA(i,j); st1 = strcat('The value being tested is: ', num2str(currNo),'.'); disp(st1) if (currNo > 3) disp('The current value is larger than 3.') else disp('The current value is less or equal than 3.') end endend

Page 126: Basic MATLAB Programming Course

While loop

Used to repeat a set of statements while the tested condition is true.

The while loop format is:while(condition)

The tested condition is the same as if…else

Page 127: Basic MATLAB Programming Course

Conditions that can be tested

% conditions that can be tested% == : is equal to% ~= : is not equal to% > : larger than% >= : larger than or equal% <= : less than or equal% < : less than

Page 128: Basic MATLAB Programming Course

Example: Display value inside for loopclear, close allclc counter = 1; while(counter <= 15) st1 = strcat('The value of i inside the loop is:

',int2str(counter)); disp(st1) counter = counter + 1;end

Page 129: Basic MATLAB Programming Course

Example: Display “Hello World” 10 Times clear, close allclc st1 = 'Hello World!';counter = 1; while(counter <= 10) disp(st1) counter = counter + 1;end

Page 130: Basic MATLAB Programming Course

Functions

Page 131: Basic MATLAB Programming Course

Functions

A complex program may be divided into several functions.

These functions can improve readability of the code, as well as promote re-usability of the code.

Each function must be saved into a different file, with the filename similar to the function.

Page 132: Basic MATLAB Programming Course

Function

The format of a function is: function returnValue = fcnName(inputValue)

Page 133: Basic MATLAB Programming Course

Example

function hasil = addFcn(number1, number2)

hasil = number1 + number2;

% to call this function, call the fcn name

% using your own parameters.

% e.g. c = addFcn(3,4)

% e.g. c = addFcn(a,b)

Page 134: Basic MATLAB Programming Course

Example: Using Functions clear, close allclc number1 = 4;number2 = 5;selection = 1; if selection == 1 hasil = addFcn(number1,number2);elseif selection == 2 hasil = subFcn(number1,number2);elseif selection == 3 hasil = mulFcn(number1,number2);elseif selection == 4 hasil = divFcn(number1,number2);else disp('The selection is invalid.')end disp(strcat('The result is:', num2str(hasil)));

Page 135: Basic MATLAB Programming Course

addFcn

function hasil = addFcn(number1, number2)

hasil = number1 + number2;

Page 136: Basic MATLAB Programming Course

subFcn

function hasil = subFcn(number1, number2)

hasil = number1 - number2;

Page 137: Basic MATLAB Programming Course

mulFcn

function hasil = mulFcn(number1, number2)

hasil = number1 * number2;

Page 138: Basic MATLAB Programming Course

divFcn

function hasil = divFcn(number1, number2)

hasil = number1 / number2;

Page 139: Basic MATLAB Programming Course

Sample Problems

Page 140: Basic MATLAB Programming Course

Problem 1

Write a program that calculates and displays the volume of a sphere when given the radius. The volume calculation must be performed in a function called calcSphereVolume.

The formula for volume is:

3

3

4jV

Page 141: Basic MATLAB Programming Course

Problem 2

Write a program that plots the function:

for values of x = -50 to 50

6323 xxxy

Page 142: Basic MATLAB Programming Course

Problem 3

Generate a 100x50 matrix of random numbers called A.

For each value inside the matrix, if the value is above 0.5, change its value to 1. If it is below 0.5, change its value to zero.

Then, count and display how many ones inside the matrix.

Page 143: Basic MATLAB Programming Course

Problem 4

Use the plot function to draw this figure:

Page 144: Basic MATLAB Programming Course

Problem 5

Write a program that reads an image and converts the image into its negative.

To convert to a negative image, for each pixel value: If the current pixel value is black (0), then change it to

white (255). If the current pixel value is white (255), then change it

to black (0). Show the original image and the changed

image.

Page 145: Basic MATLAB Programming Course

White = 255, Black = 0

Page 146: Basic MATLAB Programming Course

The End