for loop khairul anwar. loops are used when you need to repeat a set of instructions multiple times....

56
For loop Khairul anwar

Upload: egbert-warner

Post on 26-Dec-2015

230 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

For loop

Khairul anwar

Page 2: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

• Loops are used when you need to repeat a set of instructions multiple times.

• Two type of loops; for loops and while loops• How to choose:– for loops if you know how many times you need to

repeat the loops– while loops if you need to keep repeating the

instructions until a criterion is met

Page 3: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

• Structure for loops is for index = [matrix]

commands to executedend• Example (open new script file)for k=[1,3,7]

kend

Page 4: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

• Example (open new script file)for k=1:3

a=5^kend• In command windows you should get

a=5,25,125• What happens here?

Page 5: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

• A common way to use a for loop is in defining a new matrix.for k=1:5

a(k)=k^2end• In command windowa=1a=1 4a=2 4 9a=3 4 9 16a=1 4 9 16 25

Page 6: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

• Another common use for loop is to combine with an if statement and determine how many times something is true.

• Example: in the list of test scores shown below, how many are above 90?

Test scores:76, 45, 98, 97

Page 7: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

continue

scores=[76,45,98,97];count=0;for k=1:length(scores)

if scores(k)>90count=count+1;

endenddisp(count)

Page 8: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Example

• Create a table that convert angle value from degrees to radians, from 0 to 360 degrees in increment of 10 degrees.

Page 9: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

• Open script fileclear,clc%use for loop for the calculationfor k=1:36

degree(k)=k*10;radians(k)=degree(k)*pi/180;

end%create tabletable=[degree;radians];%send table to command windowsdisp('Degrees to Radians')disp('Degrees Radians')fprintf('%8.0f %8.2f\n', table)

Page 10: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Exercise 1

Consider the following matrix of values:

X=[45,23,17,34,85,29]How many values are greater than 30? Hint: use count and if statement

Page 11: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Exercise 2

• Use for loop to sum the elements of the matrix in exercise 1. Check your answer with calculator or sum function.

• Hint: use count

Page 12: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

While loops

Khairul anwar

Page 13: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

• The big difference between while and for loops is – MATLAB decides how many times to repeat the

loops– While loops continue until the criteria are met

• The format iswhile criteria

command to be executedend

Page 14: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Simple example

h=0;while h<3

k=h+1

end• What do you think will happens if we execute

this coding?• How about you try it yourself and see what

happens?

Page 15: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

What happens is

• The coding continue to loops until k=2 but the answer has k=3.

• Why is that?• Because the respond is k=h+1

Page 16: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

• Most for loops can also be coded as while loops

• Remember this example in for loopsfor k = 1:5

a(k)=k^2end

Page 17: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Change for loops to while loops

• You need to add some information in the for loops command for it to be while loops

k=0;while k<3

k=k+1;a(k)=5^k;

end• What you coded is the first three powers of 5

Page 18: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Next example

• Find the first multiple of 3 that is greater than 10

Step 1: provide initial value of A (any other letter is acceptable)Step 2: use while loops. Set the criteriaStep 3: add suitable commands to increase valueStep 4: end your coding

Page 19: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

answer

A=0;while A<10

A=A+3

end

Page 20: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Incorporate if statement

• Counting score with while loopsscores = [76,45,98,97];count=0;k=0;while k<length(scores)

k=k+1;if scores (k) > 90

count=count+1;end

enddisp(count)

Page 21: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Explanation

• Variable count is used to calculate how many values greater than 90

• Variable k is to calculate how many times the loop is executed

Page 22: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Another common use of while loop

• Error checking of user input• Example: A program where we prompt user to input positive value and calculate the log base 10 of input value. If the input is negative, prompt user to enter positive value again.

Page 23: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

MATLAB code

x=input('enter a positive value of x =');while x<=0 disp('log(x) is not defined for negative number') x=input('enter a positive value of x =');end

y=log10(x);fprintf('The log base 10 of %f is %f\n',x,y)

Page 24: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Q&A

• If a positive value is entered, does it execute while loops?

No, since x is not less than 10• If instead negative value is entered, does it

execute while loops?• What happens if while loops are executed?Error message send to command window to prompt user to enter positive value

Page 25: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Hint

• If you encounter endless loops and the “busy” indicator is display

• Press ctrl c to exit the calculation manually

Page 26: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Exercise 1

• Discuss with your partnerCreate a table that converts degrees to radians, from 0 to 360 degrees, in increments of 10 degrees. Apply while loops for coding.

Page 27: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Exercise 2

Consider the following matrix of values:

How many values are greater than 30? (use a counter)

Page 28: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Switch and case

• Used when exists option path for given variable

• Similar, to if/else/elseif• Example: you want to create a function that

tells the user what airfare is to one of the three different cities– Option is penang (rm345), johor (rm150) and

kuantan (stay home and study)

Page 29: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

clc;city=input('enter the name of a city:','s')switch city case 'penang' disp ('rm345') case 'johor' disp ('rm150') case 'kuantan' disp('stay home and study') otherwise disp('not on file')end

Page 30: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

• Menu function is often used in conjunction with a switch/case structure• By referring to previous example add menu function into the previous

coding.clc;city=menu('select city from menu:','penang','johor','kuantan')switch city case 1 disp ('rm345') case 2 disp ('rm150') case 3 disp('stay home and study') end

Page 31: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Plotting

• The basic MATLAB plotting is plot(x,y)• xlabel and ylabel commands put label on each

axis respectively• The syntax xlabel(‘text’), where text is the

name of x-axis• title commands puts title on top of the plot• Syntax title(‘text’) where text is the title of the

plot

Page 32: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Example of xy plotting• The following MATLAB session plots y = 0.4 Ö1.8x for

0 £ x £ 52, where y represents the height of a rocket after launch, in miles, and x is the horizontal (downrange) distance in miles.

>>x = [0:0.1:52];>>y = 0.4*sqrt(1.8*x);>>plot(x,y)>>xlabel(’Distance (miles)’)>>ylabel(’Height (miles)’)>>title(’Rocket Height as a Function of Downrange Distance’)

Page 33: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How
Page 34: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

continue

• The axis label and plot title are placed after the plot command

• The order of the xlabel, ylabel and title commands does not matter

Page 35: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Grid and axis command

• grid command display gridlines. Type grid on to activate gridline and grid off to stop plotting gridlines.

• use axis command to override the MATLAB selections for axis limits. The basic syntax is axis([xmin xmax ymin ymax]).

• This command will sets the scaling for the axes to the minimum and maximum values indicated

Page 36: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Example grid and axis• For example to add grid and to change axis limit on the

previous plot to >>x = [0:0.1:52];>>y = 0.4*sqrt(1.8*x);>>plot(x,y)>>xlabel(’Distance (miles)’)>>ylabel(’Height (miles)’)>>title(’Rocket Height as a Function of Downrange Distance’)>> grid on, axis ([0 52 0 5])

Page 37: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Plot of complex number

• The basic syntax is plot(y), where it is equivalent to plot(real(y), imag (y))

• For example, the script filez= 0.1+0.9i;n=[0:0.01:10];plot(z.^n), xlabel(‘real’), ylabel(‘imaginary’)

Page 38: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How
Page 39: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

The function plot command fplot

• fplot command automatically analyzes the function to be plotted and decides how many plotting points to use

• Basic syntax is fplot (‘string’, [xmin xmax]), where ‘string’ is a text that describe the function to be plotted.

• So, what is [xmin xmax] ?• You can also add ([xmin xmax ymin ymax])

Page 40: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Example comparison fplot and plot f=‘cos (tan (x)) - tan (sin(x))’;fplot (f, [1 2])

Page 41: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

continue

• Compare this plot with the previous produce by fplot

x=[1:0.01:2];y= cos (tan (x))-tan (sin (x));plot (x,y)

Page 42: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How
Page 43: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Plotting polynomial

• You can plot polynomial easily using polyval function• To plot the polynomial 3x5 + 2x4 – 100x3 + 2x2 – 7x +

90 over the range –6 £ x £ 6 with a spacing of 0.01, you type

>>x = [-6:0.01:6];>>p = [3,2,-100,2,-7,90];>>plot(x,polyval(p,x)),xlabel(’x’),ylabel(’p’)

Page 44: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How
Page 45: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Subplots

• Use subplot command to obtain several smaller “subplots” in the same figure

• The syntax is subplot (m, n, p). • This command separate the Figure window

into an array of rectangular panes with ‘m’ rows and ‘n’ columns.

Page 46: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Example• The following script file created Figure A, which shows the plots of

the functions y = e-1.2x sin(10x + 5) for 0 £ x £ 5 and y = |x3 - 100| for -6 £ x £ 6.

x = [0:0.01:5];y = exp(-1.2*x).*sin(10*x+5);subplot(1,2,1)plot(x,y),axis([0 5 -1 1])x = [-6:0.01:6];y = abs(x.^3-100);subplot(1,2,2)plot(x,y),axis([-6 6 0 350])

Page 47: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Figure A

Page 48: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Data marker and line type

• y=[0,1,2,3,4,5,6]; x=[0,1,2,3,4,5,6];• To use a small circle, which is represented by

the lowercase letter o, type plot(x,y,’o’) • To connect each data with a straight line, you

must plot the data twice by typing plot(x,y,x,y,’o’)

Page 49: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How
Page 50: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Table of data marker, line type and colors

Page 51: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Example using color marker

• To plot y versus x with green asterisks (*) connected with a red dashed line, you must plot the data twice by typing plot(x,y,’g*’,x,y,’r--’).

Page 52: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Labeling curves and data

• To create a legend, use legend command.• The basic syntax is legend(‘string1’, ’string2’),

where ‘string1’ and ‘string2’ are the text of your choice

x = [0:0.01:2];y = sinh(x);z = tanh(x);plot(x,y,x,z,’--’),xlabel(’x’), ...ylabel(’Hyperbolic Sine and Tangent’),legend(’sinh(x)’,’tanh(x)’)

Page 53: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How
Page 54: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

continue

• Another way to distinguish curves is to place label next to each

• Use gtext command to generate label • The syntax is gtext(‘string’)• you may use more than one gtext command

Page 55: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Example

• The following script file illustrate the use of gtext commands

x=[0:0.01:1];y= tan (x);z= sec (x);plot (x,y,x,z), xlabel (‘x’), ylabel (‘tangent and secant’), gtext (‘tan (x)’), gtext (‘sec (x)’)

Page 56: For loop Khairul anwar. Loops are used when you need to repeat a set of instructions multiple times. Two type of loops; for loops and while loops How

Thank you