Presentation is loading. Please wait.

Presentation is loading. Please wait.

For loop Khairul anwar.

Similar presentations


Presentation on theme: "For loop Khairul anwar."— Presentation transcript:

1 For loop Khairul anwar

2 Two type of loops; for loops and while loops How to choose:
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

3 Example (open new script file) for k=[1,3,7] k
Structure for loops is for index = [matrix] commands to executed end Example (open new script file) for k=[1,3,7] k This code return K=1,3,7

4 Example (open new script file)
for k=1:3 a=5^k end In command windows you should get a=5,25,125 What happens here?

5 A common way to use a for loop is in defining a new matrix.
for k=1:5 a(k)=k^2 end In command window a= 1 4

6 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

7 continue scores=[76,45,98,97]; count=0; for k=1:length(scores)
if scores(k)>90 count=count+1; end disp(count)

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

9 Open script file clear,clc %use for loop for the calculation for k=1:36 degree(k)=k*10; radians(k)=degree(k)*pi/180; end %create table table=[degree;radians]; %send table to command windows disp('Degrees to Radians') disp('Degrees Radians') fprintf('%8.0f %8.2f\n', table)

10 Exercise 1 Consider the following matrix of values:
How many values are greater than 30? Hint: use count and if statement Values = [45,23,17,34,85,29]; count=0; for k=1:length(values) if values (k) > 30 count=count+1; end disp(count)

11 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

12 While loops Khairul anwar

13 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 is while criteria command to be executed end

14 Simple example h=0; while h<3 end
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?

15 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

16 Most for loops can also be coded as while loops
Remember this example in for loops for k = 1:5 a(k)=k^2 end

17 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

18 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 criteria Step 3: add suitable commands to increase value Step 4: end your coding

19 answer A=0; while A<10 A=A+3 end

20 Incorporate if statement
Counting score with while loops scores = [76,45,98,97]; count=0; k=0; while k<length(scores) k=k+1; if scores (k) > 90 count=count+1; end disp(count)

21 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

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

23 MATLAB code x=input('enter a positive value of x ='); while x<=0
disp('log(x) is not defined for negative number') end y=log10(x); fprintf('The log base 10 of %f is %f\n',x,y)

24 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

25 Hint If you encounter endless loops and the “busy” indicator is display Press ctrl c to exit the calculation manually

26 Exercise 1 Discuss with your partner
Create a table that converts degrees to radians, from 0 to 360 degrees, in increments of 10 degrees. Apply while loops for coding. k=1; while k<=36 degree(k)=k*10; radians(k)=degree(k)*pi/180; k=k+1; end table=[degree;radians] disp('degree to radians') disp('degrees radians') fprintf('%4.0f %8.2f\n',table)

27 Exercise 2 Consider the following matrix of values: 𝑥=[45,23,17,34,85,33] How many values are greater than 30? (use a counter) x=[ ]; k=0; count=0; while k<length(x) k=k+1; if x(k)>30 count=count+1; end fprintf('%1.0f numbers is greater than 30\n',count)

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

29 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

30 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

31 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

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

33

34 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

35 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

36 Example grid and axis For example to add grid and to change axis limit on the previous plot to 0≤𝑥≤52 𝑎𝑛𝑑 0≤𝑦≤5 >>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 ([ ])

37 Plot of complex number The basic syntax is plot(y), where it is equivalent to plot(real(y), imag (y)) For example, the script file z= i; n=[0:0.01:10]; plot(z.^n), xlabel(‘real’), ylabel(‘imaginary’)

38

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

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

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

42

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

44

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

46 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 = |x | 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([ ]) x = [-6:0.01:6]; y = abs(x.^3-100); subplot(1,2,2) plot(x,y),axis([ ])

47 Figure A

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

49

50 Table of data marker, line type and colors

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

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

53

54 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

55 Example The following script file illustrate the use of gtext commands
y= tan (x); z= sec (x); plot (x,y,x,z), xlabel (‘x’), ylabel (‘tangent and secant’), gtext (‘tan (x)’), gtext (‘sec (x)’)

56 Thank you


Download ppt "For loop Khairul anwar."

Similar presentations


Ads by Google