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

Post on 26-Dec-2015

230 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

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

• Structure for loops is for index = [matrix]

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

kend

• 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?

• 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

• 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

continue

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

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

endenddisp(count)

Example

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

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

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

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

While loops

Khairul anwar

• 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

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?

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

• Most for loops can also be coded as while loops

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

a(k)=k^2end

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

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

answer

A=0;while A<10

A=A+3

end

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)

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

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.

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)

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

Hint

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

• Press ctrl c to exit the calculation manually

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.

Exercise 2

Consider the following matrix of values:

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

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)

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

• 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

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

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

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

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

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

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

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

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

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)

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

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.

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

Figure A

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

Table of data marker, line type and colors

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

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

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

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

Thank you

top related