Anda di halaman 1dari 82

MATLAB WORKSHOP FOR BEGINNER

Postgraduate Excellence Event


School of Electrical Systems Engineering
Universiti Malaysia Perlis (UniMAP)
Malaysia

INTRODUCTION
SPEAKER

LEARNING OUTCOMES
At the end of the workshop:
1. Participants should be able to use MATLAB in research, data
analysis, creating functions, and mathematical presentations.
2. Participants should be able to solve scientific/research
problems using MATLAB
3. Participants should be able to model the data using MATLAB.
4. Participants should be able to create professional
graphs/plots for peer reviewed journals and international
conferences.

BASICS AND INTRODUCTION.


Installation.
The basic features.
Data formats and assignments
VECTOR AND MATRICES.
Creating vectors and matrices.
Accessing rows/columns for large data set.
Mathematical operations.
Special arrays and functions.

EXCEL SPREADSHEETS.
Importing excel spread sheet.
Plotting data.
GRAPHICS.
Two dimensional plotting functions.
Sub-plots.
Bar and 3-D bar graphs.
Polygons graphs.
Pie graphs.
Three dimensional plotting functions.

MATLAB PROGRAMMING.
Loops.
Branching with if.
Switch statement.
Branching with while.

Introduction: What is MATLAB?

Stands for MATrix LABoratory.


It is an interactive program for numerical computation and
data visualization.
MATLAB Deals mainly with matrices.
Using MATLAB, you can analyze data, develop algorithms,
and create models and applications..
The language, tools, and built in math functions enable you
to explore multiple approaches and reach a solution faster
than with spreadsheets or traditional programming languages,
such as C\C++ or Java.

MATLAB Workshop

Command Window - to
main window, enter
variables, run programs
Current Folder - purpose
as a shows the files in the
current directory
Command History window & logs commands
entered in the command
window
Workspace Window - to
provides information
about the variables that
are used
Editor Window - creates
and debugs script and
function files

Introduction
Type a valid expression, for example:
>> 5 + 5
When you click the Execute button, the result returned is:
ans = 10
Let us take up few more examples:
>> 3^2
ans = 9
>> 7/0
ans = Inf
>> 732 * 20.3
ans = 1.4860e+04

MATLAB Workshop

Introduction
Use of Semicolon (;) in MATLAB: indicates end of
statement. However, if you want to suppress and hide the
MATLAB output for an expression, add a semicolon after the
expression. For example,
>> x = 3;
>> y = x + 5
ans = 8
Adding comments: The percent symbol (%) is used for
indicating a comment line. For example,
>> x = 9

% assign the value 9 to x

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Introduction
MATLAB supports the following commonly used operators
and special characters:
+
*
.*

.
\
/
.\
./
:
()
[]

Plus; addition operator


Minus; subtraction operator
Scalar and matrix multiplication operator
Array multiplication operator
Scalar and matrix exponential operator
Array exponential operator
Left-division operator
Right-division operator
Array left-division operator
Array right-division operator
Colon; generates regularly spaced elements and represents an entire row or column
Parentheses; encloses function arguments and array indices; overrides precedence
Brackets; enclosures array elements
Decimal point
Ellipsis; line-continuation operator
, Comma; separates statements and elements in a row
; Semicolon; separates columns and suppresses display
% Percent signl designates a comment and specifies formatting
- Quote sign and trspose operator
Nonconjugated transpose operator
=
Assignment opertor

MATLAB Workshop

Introduction

The exist checks for existence file or variable


The clear command deletes all (or the specified) variable(s)
from the memory. For example:
>> clear x
>> clear

% it will delete x, wont display anything


% it will delete all variables in the
% workspace peacefully and unobtrusively

The clc command clears command window.


The Quit command stops MATLAB.

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Introduction

You can use MATLAB to do arithmetic as you would a


calculator. You can use + to add, - to subtract, * to
multiply, / to divide, and to exponentiate. For example:
>> 3^2 - (5+4)/2 + 6 * 3
ans =
22.5000
MATLAB prints the answer and assigns the value to a variable
called ans. If you want to perform further calculations with
the answer, you can use the variable ans rather than retype
the answer.

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Introduction

For example, you can compute the sum of the square and the
square root of the previous answer as follows:
>> ans^2 + sqrt(ans)
ans =
510.9934
Observe that MATLAB assigns a new value to ans with each
calculations.

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Introduction
Multiple Assignments: You can have multiple assignments
on the same line. For example,

>> a = 2; b = 7; c = a * b
c=
14
I have forgotten the variables!: The who command
displays all the variable names you have used.
>> who
MATLAB will execute the above statement and return the
following result:
Your variables are:
a

ans b

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Introduction
The format command: By default, MATLAB displays
numbers with four decimal place values. This is known as
short format. However, if you want more precision, you need
to use the format command.
The format long command displays 16 digits after decimal.
For example,
>> format long
>> x = 7 + 10/3+5^1.2
x=
17.231981640639408
Another example,
>> format short
>> x = 7 + 10/3+5^1.2
x=
17.2320

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Vectors and Matrices

Suppose you want to create a vector of values running from 1


to 9. Heres how to do it without typing each number:

>> X = 1:9
The increment can be specified as the second of three
arguments:
>> X = 0:2:10

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Vectors and Matrices

You can also use fractional or negative increments, for


example 0:0.1:1 or 100:-1:0.
To change the vector X from a row to a column vector, put a
prime() after X:
>> X

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Vectors and Matrices

You can perform mathematical operations on vectors. For


example, to square the elements of the vector X, type
>> X.^2
Typing X^2 would tell MATLAB to use matrix multiplication
to multiply X by itself and would produce an error message in
this case. Similarly, you must type .* or ./if you want to
multiply or divide vectors element-by-element. For example,
to multiply the elements of the vector X by the corresponding
elements of the vector Y, type
>> Y = [4 -3 5 -2 8 1]
>> X.*Y

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Vectors and Matrices

Creating arrays:
1

Row vector:
array = [1 5 7 9];

Column vector:
array = [1; 5; 7; 9];

Use a space to separate each element.


Use a semi-colon (;) to go down to the next row.
Column vector can also be created as:

array = [1 5 7 9];
After, MATLAB creates an array automatically, with the value
you specified, stored in MATLAB as array.

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Vectors and Matrices

Accessing elements in an array:


1
2

Use the name of the array; with round brackets ().


Inside the round brackets, specify the position of where you
want to access.

Examples:
1. array = [1 5 8 7];
2. num = array(2);
3. num = array(4);
to copy an entire array over, simply set another variable equal to the
1
array you
want to copy.
2

array2 = array

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Vectors and Matrices

Lets move onto matrices:


1
2
3
4

To create a matrix, very much like creating arrays


Use square braces [], then use the numbers you want
Use spaces to separate between the columns
Use semicolons (;) to go to each row

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Vectors and Matrices

A matrix is a rectangular array of numbers. Row and column


vectors, which we discussed above, are examples of matrices.
It can be entered in MATLAB, for example,

>> A = [16 2 3 13; 5 11 10 8; 9 7 6 12;4 14 15 1]

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Vectors and Matrices

Every variable in MATLAB is an array that can hold many


numbers. When you want to access selected elements of an
array, use indexing.
For example, consider the matrix A:
>> A = [16 2 3 13; 5 11 10 8; 9 7 6 12;4 14 15 1]
>> A(4,2)
>> A(8)

If you attempt to refer to elements outside an array on the


right side of an assignment statement, MATLAB throws an
error

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Vectors and Matrices

To access a range of values, use the colon operator just like


we did for arrays, but now use them for each dimension.
Examples:
1

To access rows 1-3 and columns 3-4,


B = M(1:3,3:4)

To access row 1 and columns 1-3,


B = M(1,1:3)

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Vectors and Matrices


Now on to modifying elements in arrays and matrices:
1

Do same thing with accessing elements or in groups


Flip the order of whats on which side of the equals sign

Example:
A = [1 2 3 4;
5 6 7 8;
9 6 4 3;
2 3 5 9]
A(3,4) = 27;
A(1:2,3:4) = [5 6; 99 22];
A(2,:) = [8 19 2 20];
A(:,3) = [5;4;3;2];
A(1:2,:) = 5;

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Vectors and Matrices

These functions return information about the shape and size


of a matrix:
length: Return the length of the longest dimension
size: Return the length of each dimension

Example: Using the numel function, find the average of all


values in matrix A:
>> [a b] = size(A)
>> c = length(A)

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Vectors and Matrices

The sort function sorts matrix elements along a specified


dimension. The syntax for the function is sort(matrix,
dimension)
To sort the columns of a matrix, specify 1 as the dimension
argument. To sort along rows, specify dimension as 2.

Example:
>> r = sort(A, 2, descend)
>> d = sort (A, ascend) % ascend is the default

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Vectors and Matrices - Special Arrays in MATLAB

In this section, we will discuss some functions that create


some special arrays. For all these functions, a single argument
creates a square array, double arguments create rectangular
array.
1
2

zeros(): function creates an array of all zeros.


ones(): function creates an array of all ones.
rand(): function creates an array of uniformly distributed
randome numbers on (0,1).

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Vectors and Matrices - Special Arrays in MATLAB

Example:
>> zeros(3)
>> zeros(2,3)
>> ones(3)
>> ones(2,3)
>> rand(3)
>> rand(2,3)

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Importing Excel Spreadsheets

Selecting the spreadsheet and variables interactively:


Select File > Import data

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Importing Excel Spreadsheets


Reading a specific worksheet and range of data. For example:
Consider the file climate.xls has been created.
To import the numeric data into a matrix, use xlsread with a
single return argument. xlsread ignores any leading row or
column of text in the numeric result:
ndata = xlsread(climate.xls, Temperatures)
To import both numeric data and text data, specify two return
values for xlsread:
[ndata, headertext] = xlsread(climate.xls,Temperatures)

To read an exact row of data, specify the range:


firstrow = xlsread('climate.xls', 'Temperatures', 'A2:B2')
secondrow = xlsread('climate.xls', 'Temperatures', 'A3:B3')

thirdrow = xlsread('climate.xls', 'Temperatures', 'A4:B4')


Dr. Mahmoud A. M. Albreem

MATLAB Workshop

M-Files

For complicated problems, the simple editing tools provided


by the Command Window and its history mechanism are
insufficient. A much better approach is to create an M-file.
There are two different kinds of M-files: script M-files and
function M-files.

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Script M-Files

We now show how to construct a script M-file to solve the


mathematical problem using Scrip M-files. Create a file
containing the following lines:
format long
x = [0.1 0.01 0.001];
y = sin(x)./x
We will assume that you have saved this file with the name
task1.m in your working directory, or in some director on your
path. You can name the file any way you like, but the .m
suffix is mandatory.
You can tell MATLAB to run (or execute) this script by typing
task1 in the Command Window.

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Function M-Files

You often need to repeat a process several times for different


input values of a parameter. For example, you can provide
different inputs to a built-in function to find an output that
meets a given criterion.
As you have already seen, you can use inline to define your
own functions.
In many situations, however, it is more convenient to define a
function using an M-file instead of an inline function.
Let us give a simple example:
function [a] = log3(x)
a = log(abs(x))./log(3);

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Graphics

In this section, we are going to talk about:


1
2

Two-Dimensional Plotting Functions.


Three-Dimensional Plotting Functions.

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Graphics - Two-Dimensional Plotting Functions

This table shows MATLAB 2-D plotting funcitons:

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Graphics - Two-Dimensional Plotting Functions

Lets start with 2-D plotting


1

Assuming that we have two variables, x and y and are both the
same size
To produce the most basic graph in MATLAB that plots y vs.
x, you just do:
plot(x,y)

Lets start off with a basic example: y = x


x = [1 2 3 4 5];
y = [1 2 3 4 5];
plot(x,y)

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Graphics - plot

What if we want to generated a large set of numbers? use the


following syntax:
array = first : increment : last;
OR
array = first : last; % Leaving increment
out defaults to a

step size of 1

To plot x2 + x + 1 on the interval from -2 to 2, we first make


a list of x values, and then type plot(x, x2 + x + 1).

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Graphics - linspace

Can also perform this using the linspace command


array = linspace(X1, X2, N)
array = linspace(X1, X2)
1

The first style generates an array of size N, with equally spaced


point between X1 and X2
The second style generates an array of the default size of 100
equally spaced points between X1 and X2

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Plots and Plotting Tools - linspace

Create 2-D Line Graph: this example shows how to create a


simply line graph. Use the linspace function to define x as a
vector of 100 linearly spaced values between 0 and 2.
>> x = linspace(0,2*pi,100);
>> y = sin(x);
>> plot(x,y)

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Plots and Plotting Tools - Two-Dimensional


Plotting Functions
Create Graph in New Figure Window: this example shows
how to create a new figure window, instead of plotting into
the current figure.
>> x = linspace(0,2*pi,25);
>> y = sin(x);
>> figure % Open a new figure window using the
% figure command
>> stairs(x,y) % Create a stairstep plot of
% y versus x.
figure(h): where h is an integer, creates a new figure window,
or makes figure h the current figure.
clf: clears the current figure window.
cla: deletes all plots and text from the current axes, i.e.
leaves only the x- and y-axes and their associated information.
Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Plots and Plotting Tools - Two-Dimensional


Plotting Functions

Plot Multiple Lines: this example shows how to plot more


than one line by passing multiple x, y pairs to the plot
function.
>> x = linspace(0,2*pi,25);
>> y1 = sin(x);
>> y2 = sin(x-pi/4);
>> figure
>> plot(x,y1,x,y2)

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Plots and Plotting Tools - Two-Dimensional


Plotting Functions

Specify Line Style: this example shows how to create a plot


using a dashed line. Add the optional line specification
string-, to the x,y pair.
>> x = linspace(0,2*pi,25);
>> y = sin(x);
>> plot(x,y,--)

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Plots and Plotting Tools - Two-Dimensional


Plotting Functions

Specify Line Style and Color: this example shows how to


specify the line styles and line colors for a plot.
>> x = linspace(0,2*pi,100);
>> y1 = sin(x);
>> y2 = sin(x-pi/4);
>> plot(x,y1,--g,x,y2,:r)

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Plots and Plotting Tools - Two-Dimensional


Plotting Functions

Specify Line Style, Color, and Markers: this example


shows how to specify the line style, color and markers for two
sine waves.
>> x = linspace(0,2*pi,25);
>> y1 = sin(x);
>> y2 = sin(x-pi/4);
>> plot(x,y1,--go,x,y2,:r*)

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Graphics with plot

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Plots and Plotting Tools - Two-Dimensional


Plotting Functions

Add Title, Axis Labels, and Legend to Graph: this


example shows how to add a title, axis labels and a legend to
a graph using the title, xlabel, ylabel, and legend
functions.
>> x = linspace(-2*pi,2*pi,100);
>> y1 = sin(x);
>> y2 = cos(x);
>> plot(x,y1,x,y2)
>> title(Graph of Sine and Cosine Between -2\pi and 2\pi)
>> xlabel(-2\pi < x < 2\pi) % x-axis label
>> ylabel(since and cosine values) % y-axis label
>> legend(y = sin(x), y = cos(x))

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Plots and Plotting Tools - Two-Dimensional


Plotting Functions
One Legend Entry for Group of Objects: this example
shows how to group a set of lines together into one legend
entry. For example, plot four sine waves and four cosine
waves.
>> figure
>> hold on
>> t = linspace(0,2*pi,100);
>> p(1) = plot(t,sin(t),b);
>> p(2) = plot(t,sin(t+1/7),b);
>> p(3) = plot(t,sin(t+2/7),b);
>> p(4) = plot(t,sin(t+3/7),b);
>> p(5) = plot(t,cos(t),g);
>> p(6) = plot(t,cos(t+1/7),g);
>> p(7) = plot(t,cos(t+2/7),g);
>> p(8) = plot(t,cos(t+3/7),g);
>> hold off
>> g1 = hggroup;
>> g2 = hggroup;
>> set(p(1:4),Parent,g1)
>> set(p(5:8),Parent,g2)
>> legend([g1,g2],sine,cosine)

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Graphics with plot

Example:
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
hold on
y2 = cos(x);
plot(x,y2,r:)
legend(sin(x),cos(x))
grid

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Plots and Plotting Tools - Two-Dimensional


Plotting Functions
Lets say we want to plot multiple graphs in separate plots on
the same window. We should use the command subplot.
This command treats the window as having multiple slots.
Each slot takes in a graph
How do we use the command?
subplot(m,n,p);
These determine the number of rows (m) and columns (n) for
the amount of graphs you want. p chooses which location in
the window the plot should go to
h = subplot(m,n,p) or subplot(mnp) breaks the figure
window into an m-by-n matrix of small axes, selects the pth
axes object for the current plot, and returns the axes handle.
The axes are counted along the top row of the figure window,
then the second row, etc.
Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Plots and Plotting Tools - Two-Dimensional


Plotting Functions

Example:
To make a window that has 4 plots: 2 rows and columns
1 Do subplot(2,2,1): Specify the top left corner
2 Do subplot(2,2,2): Specify the top right corner
3 Do subplot(2,2,3): Specify the bottom left corner
4 Do subplot(2,2,4): Specify the bottom right corner

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Plots and Plotting Tools - Two-Dimensional


Plotting Functions
Use subplot to create a figure containing a2-by-2grid of
graphs:
>> x = linspace(-5,5); % define x
>> y1 = sin(x); % define y1
>> figure % create new figure
>> subplot(2,2,1) % first subplot
>> plot(x,y1)
>> title(First subplot)
>> y2 = sin(2*x); % define y2
>> subplot(2,2,2) % second subplot
>> plot(x,y2)
>> title(Second subplot)
>> y3 = sin(4*x); % define y3
>> y4 = sin(6*x); % define y4
>> subplot(2,2,3); % third subplot
>> plot(x,y3)
>> title(Third subplot)
>> subplot(2,2,4) % fourth subplot
>> plot(x,y4)
>> title(Fourth subplot)

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Bar Graphs

Lets move to bar plot: Creating a bar graph of an m-by-n


matrix creates m groups of n barseries objects. Each barseries
object contains the data for corresponding x values of each
bar group (as indicated by the coloring of the bars).

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Bar Graphs
The bar function distributes bars along the x-axis. Elements
in the same row of a matrix are grouped together.
For example, if a matrix has five row and three columns, the
bar displays five groups of three bars along the x-axis. The
first cluster of bars represents the elements in the first row of
Y.
>> Y = [5,2,1
8,7,3
8,8,6
5,5,5
4,3,2];
>> figure
>> bar(Y)

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

3-D Bar Graph


The bar3 function draws each element as a separate 3-D
block and distributes the elements of each column along the
y-axis.
>> Y = [5,2,1
8,7,3
9,8,6
5,5,5
4,3,2];
>> bar3(Y)
To stack the elements in a row, specify the stacked option
for the bar3 function.
>> figure
>> bar3(Y,stacked)

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Polygons
patch: create one or more filled polygons. For example,
>> xdata = [1;5;3];
>> ydata = [3;2;5];
>> patch(xdata,ydata,w)

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Pie Graph

Define x and create a pie chart.

>> x = [1,2,3];
>> figure
>> pie(x)
>> legend(Product A,Product B,Product C)
% OR
>> labels = {Product A,Product B,Product C}
>> legend(labels,Location,Southoutside,...
Orientation,horizontal)

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Graphs

Lets move onto 3-D plots!


Here are the steps:
1
2

Create a function header of two variables


Figure out the range of x and y values you want, then create a
grid of these x and y points
Use the function handler to create the output points in the
third dimension (Z)
Use a function that plots this triplet of arrays in 3-D

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Graphs
How do we generate a grid of x and y values?
1

Use the meshgrid function. This function will output two


matrices, X and Y
X contains what the x co-ordinates are in the grid of points we
want
Y contains what the y co-ordinates are in the grid of points we
want
You need to specify the range of x and y values we want to plot
[X,Y] = meshgrid(x1:x2,y1:y2)
[X,Y] = meshgrid(x1:inc:x2,y1:inc:y2)
x1,x2 determine the beginning and ending x values
respectively. y1, y2 determine the beginning and ending y
values respectively. We can optionally specify inc which
specifies the step size, just like what we have seen earlier

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Graphs

Now, how do we create 3-D plots? Use either the surf or


mesh commands:
1

surf(x,y,z): the z values all have different colors assigned to


them and is a closed plot
mesh(x,y,z): the z values all have different colors assigned to
them, but only draws lines through the points
For each function, you specify a triplet of x, y, and z values of
all the same size

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Graphs

Example: Lets plot the following function


f(x , y ) = xex2y2
f = @(x,y) x.*exp(-x.^2 - y.^2);
[X Y] = meshgrid(-2:0.2:2, -2:0.2:2);
Z = f(X,Y);
surf(X,Y,Z);
xlabel(x); ylabel(y); zlabel(z);
figure;
mesh(X,Y,Z)
xlabel(x); ylabel(y); zlabel(z);

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

MATLAB Programming

Every time you create an M-file, you are writing a computer


program using the MATLAB programming language. You can
do quite a lot in MATLAB using no more than the most basic
programming techniques that we have already introduced.

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

MATLAB Programming (Loops)


The for loop allows us to repeat certain commands. If you
want to repeat some action in a predetermined way, you can
use the for loop. The for loop will loop around some
statement, and you must tell MATLAB where to start and
where to end. For example,
>> for j = 1 : 4
j+2
end
ans =
3
ans =
4
ans =
5
ans =
6
Dr. Mahmoud A. M. Albreem

MATLAB Workshop

MATLAB Programming (Loops)

Another example:
>> x = 1:10;
>> for i = 1 : 10
x2(i) = x(i)^2;
end
>> x2
x2 =
1 4 9 16

25

Dr. Mahmoud A. M. Albreem

36

49

64

MATLAB Workshop

81

100

MATLAB Programming (Loops)


In the following example, we calculate the square of the
entries in a matrix.
>> A = [1 5 -3;2 4 0;-1 6 9];
>> [a b] = size(A);
>> for i = 1 : a
for j = 1 : b % called nested for loop
A2(i,j) = A(i,j)^2;
end
end
>> A2
A2 =
1 25 9
4 8
0
1 36 81

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

MATLAB Programming (Branching with if)


An if ... end statement consists of an if statement and a
boolean expression followed by one or more statements. It is
delimited by the end statement. The syntax of an if
statement in MATLAB is:
if <expression>
% statement(s) will execute if the boolean
% expression is true
<statement>
end
If the expression evaluates to true, then the block of code
inside the if statement will be executed. If the expression
evaluates to false, then the first set of code after the end
statement will be executed.

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

MATLAB Programming (Branching with if)


Flow Diagram:

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Relational Operators

Relational operators for arrays perform element-by-element


comparisons between two arrays and return logical array of the
same size, with elements set to logical 1 (true) where the
relation is true and elements set to logical 0 (false) where it is
not.
< : Less than
<= : Less than or equal to
> : Greater than
>= : Greater than or equal to
== : Equal to
= : Not equal to

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

MATLAB Programming (Branching with if)

Example: create a script file and type the following code:


a = 10;
% check the condition using if statement
if a < 20
% if condition is true then print the following
fprintf(a is less than 20\n);
end
fprintf(value of a is : %d\n,a)

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

MATLAB Programming (Branching with if)


An if statement can be followed by an optional else
statement, which executes when the expression is false. The
syntax of an if ... else ... end statement in MATLAB is:
if <expression>
% statement(s) will execute if the boolean
% expression is true
<statement(s)>
else
<statement(s)>
% statement(s) will execute if the boolean
% expression is false
end
If the boolean expression evaluates to true, then the if block of
code will be executed, otherwise else block of code will be
executed.
Dr. Mahmoud A. M. Albreem

MATLAB Workshop

MATLAB Programming (Branching with if)


Flow Diagram:

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Relational Operators

Example: type the following code:


>> a = 100; b = 200;
>> if (a>=b)
max = a
else
max = b
end
When you execute the code, it produces following result:
max =
200

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

MATLAB Programming (Branching with if)

An if statement can be followed by an (or more) optional


elseif ... and an else statement, which is very useful to test
various condition. When using if ... elseif ... else
statements, there are few points to keep in mind:
1

An if can have zero or one elses and it must come after any
elseifs.
An if can have zero to many elseifs and they must come
before the else.
Once an elseif succeeds, non of the remaining elseifs or elses
will be tested.

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

MATLAB Programming (Branching with if)


if...elseif...else Synatx:
if <expression 1>
% Executes when the expression 1 is true
<statement (s)>
elseif <expression 2>
% Executes when the expression 2 is true
<statement (s)>
elseif <expression 3>
% Executes when the expression 3 is true
<statement (s)>
else
% Executes when the none of the above
% condition is true
<statement (s)>
end

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

MATLAB Programming (Branching with if)


Example: create a script file and type the following code in it,
a = 100;
% check the boolean condition
if a == 10
% if condition is true then print the following
fprintf(Value of a is 10\n);
elseif(a == 20)
% if else if condition is true
fprintf(Value of a is 20\n);
elseif a == 30
% if else if condition is true
fprintf(Value of a is 30\n);
else
% if none of the conditions is true
fprintf(None of the values are matching \n);
fprintf(Exact value of a is: %d\n,a);
end
Dr. Mahmoud A. M. Albreem

MATLAB Workshop

MATLAB Programming (Branching with if)

Nested if statements: It is always legal in MATLAB to nest


if-else statements which means you can use one if or elseif
statement inside another if or elseif statement(s).
Synatx: the syntax for a nested if statement is as follows:
if <expression 1>
% Executes when the boolean expression 1 is true
if <expression 2>
% Executes when the boolean expression 2 is
% true
end
end

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

MATLAB Programming (Branching with if)


Example: create a script file and type the following code in it.
a = 100;
b = 200;
% check the boolean condition
if (a == 100)
% if condition is true then check
% the following
if (b == 200)
% if condition is true then print
% the following
fprintf(Value of a is 100 and b is 200\n);
end
end
fprintf(Exact value of a is : %d\n,a);
fprintf(Exact value of b is : %d\n,b);

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Switch statement
A switch block conditionally executes one set of statements
from several choice. Each choice is covered by case
statement. An evaluated switch expression is a scalar or
string. The switch block tests each case until one of the cases
is true. A case is true when:
1
2
3

For numbers, eq(case expression,switch expression).


For strings, strcmp(case expression,switch expression).
For objects that support the eq function,
eq(case expression,switch expression).
For a cell array case expression, at least one of the elements of
the cell array matches switch expression, as defined above for
numbers, strings and objects.
When a case is true, MATLAB executes the corresponding
statements and then exits the switch block. The otherwise
block is optional and executes only when no case is true.

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Switch statement

Syntax: the syntax of switch statement in MATLAB is:


switch <switch_expression>
case <case_expression>
<statements>
case <case_expression>
<statements>

otherwise
<statements>

end

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Switch statement
Example: create a script file and type the following code in it,
grade = B;
switch(grade)
case A
fprintf(Excellent!\n);
case B
fprintf(Well done\n);
case C
fprintf(Well done\n);
case D
fprintf(You passed\n);
case F
fprintf(Better try again\n);
otherwise
fprintf(invalid grade\n);
end
Dr. Mahmoud A. M. Albreem

MATLAB Workshop

MATLAB Programming (Branching with while)

We introduced the command for, which begins a loop - a


sequence of commands to be executed multiple times. When
you use for, you effectively specify the number of times to
run the loop in advance. Some times you want to keep
running the commands in a loop until a certain condition is
met, without deciding in advance on the number of iterations.
In MATLAB, the command that allows you to do so is while.
The while loop repeatedly executes statements while
condition is true.

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

MATLAB Programming (Branching with while)

The syntax of a while loop in MATLAB is:


while <statement>
<statement>
end
The while loop repeatedly executes program statement(s) as
long as the expression remains true.

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

MATLAB Programming (Branching with while)


Example: create a script file and type the following code:
a = 10;
% while loop execution
while (a < 20)
fprintf(value of a: %d\n,a);
a = a + 1;
end
When you run the file, it displays the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Dr. Mahmoud A. M. Albreem

MATLAB Workshop

Anda mungkin juga menyukai