For loop Khairul anwar.

Slides:



Advertisements
Similar presentations
Lab # 03- SS Basic Graphic Commands. Lab Objectives: To understand M-files principle. To plot multiple plots on a single graph. To use different parameters.
Advertisements

Lecture 5.
CSE 123 Plots in MATLAB. Easiest way to plot Syntax: ezplot(fun) ezplot(fun,[min,max]) ezplot(fun2) ezplot(fun2,[xmin,xmax,ymin,ymax]) ezplot(fun) plots.
Introduction to Engineering MATLAB – 11 Plotting - 4 Agenda Multiple curves Multiple plot.
Lecture (4) Plotting & Programming (1) Eng. Osama Talaat 1.
Introduction to Graphing Using MATLAB. Line Graphs  Useful for graphing functions  Useful for displaying data trends over time  Useful for showing.
Matlab Graphics S. Awad, Ph.D. M. Corless, M.S.E.E. E.C.E. Department University of Michigan-Dearborn Introduction to Matlab: 2D Graphics.
Introduction to MATLAB for Biomedical Engineering BME 1008 Introduction to Biomedical Engineering FIU, Spring 2015 Lesson 2: Element-wise vs. matrix operations.
CMPS 1371 Introduction to Computing for Engineers
MATLAB’s extensive, device-independent plotting capabilities are one of its most powerful features. They make it very easy to plot any data at any time.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.
MATLAB - Lecture 22A Two Dimensional Plots / Chapter 5 Topics Covered:
EGR106 Week 6 MATLAB FILES Two Dimensional Plots Multiple Plots
Vectors and Plotting Selim Aksoy Bilkent University Department of Computer Engineering
EGR106 Week 4 Two Dimensional Plots Multiple Plots Plot Formatting Homework.
Introduction to MATLAB for Engineers, Third Edition Chapter 5 Advanced Plotting PowerPoint to accompany Copyright © The McGraw-Hill Companies, Inc.
Introduction to Matlab 332:202 Discrete Mathematics Spring 2007.
An introduction to Plotting in MATLAB Rikard Johansson Department of Biomedical Engineering (IMT) Linköping University
Chapter 5 Review: Plotting Introduction to MATLAB 7 Engineering 161.
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
Plotting II: By the end of this class you should be able to: Create a properly formatted engineering graph Create graphs of a function Place multiple plots.
ENG College of Engineering Engineering Education Innovation Center 1 2D Plots 1 in MATLAB Topics Covered: 1.Plotting basic 2-D plots The plot()
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers Chapter 5 Advanced.
1 Advanced Plotting ผศ. ดร. อนันต์ ผลเพิ่ม Anan Phonphoem
ELG 3120 Signal and System Analysis 1 Introduction to MATLAB TAs Wei Zhang Ozgur Ekici (Section A)(Section B) ELG 3120 Lab Tutorial 1.
MATLAB for Engineers 4E, by Holly Moore. © 2014 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected by Copyright.
CMPS 1371 Introduction to Computing for Engineers CONDITIONAL STATEMENTS.
MAE 1202: AEROSPACE PRACTICUM An Introduction to MATLAB: Part 2 Mechanical and Aerospace Engineering Department Florida Institute of Technology Developed.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers Chapter 5 Advanced.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers Chapter 5 Advanced.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® Chapter 5 Advanced.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Matlab for Engineers Logical Functions and Control Structures Chapter 8.
Recap Sum and Product Functions Matrix Size Function Variance and Standard Deviation Random Numbers Complex Numbers.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
ENG 1181 College of Engineering Engineering Education Innovation Center MATLAB – 2D Plots 1 Go to the class drive: ---> MatLab - Graphing ---> Seed Files.
Matlab Screen  Command Window  type commands  Current Directory  View folders and m-files  Workspace  View program variables  Double click on a.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers Chapter 5 Advanced.
Recap Chapter 5 “Plotting” Two Dimensional Plots Simple x-y Plots Titles, Labels and Grids Multiple Plots.
EGR 106 Lecture 6 2-D Plotting Graphical presentation has become the standard method to show technical information. Engineers use plots to analyze, visualize,
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
1-d Arrays & Plotting.
ELG 3120 Lab 2 TAs Wei Zhang Ozgur Ekici (Section A) (Section B)
MATLAB Jirawat Kanjanapitak (Tae). What is MATLAB A computer program for doing numerical computation including; Arithmetic, Polynomials, Graphics, 2-D.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
1 Lecture 5 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
Introduction to Engineering MATLAB – 9 Plotting - 2 Agenda Formatting plots.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers Chapter 5 Advanced.
NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS ( NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS (PRACTICAL PART) Lab 2 : potting to Matlab Networks.
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
EGR 106 – Week 5 – 2-D Plots Question : Why do engineers use plots? Answer : To analyze, visualize, and present data. Matlab has many useful plotting options.
How to use MATLAB (using M-files) Double click this icon To start Matlab 6.5.
Session III Plotting in MATLAB Rajeev Madazhy Dept of Mechanical Engineering LSU MATLAB Tutorials.
Creating a Plot The plot function can take one or more inputs; e.g. plot (x, y) or plot (y) Note that in the two-argument version, the vectors x and.
Plots and Graphics.
Computer Application in Engineering Design
Repetition Structures Chapter 9
Two-Dimensional Plots
MatLab – Palm Chapter 5 2-D & 3-D Plots
MATLAB DENC 2533 ECADD LAB 9.
Net 222: Communications and networks fundamentals (Practical Part)
Net 222: Communications and networks fundamentals (Practical Part)
MATLAB How to use (using M-files) Double click this icon
MATLAB How to use (using M-files) Double click this icon
MatLab – 2D Plots 2 MATLAB has many built-in functions and commands to create various types of plots. Instructor notes: We start with an example of some.
MATLAB How to use (using M-files)
Plotting Signals in MATLAB
Introduction to Matlab
Presentation transcript:

For loop Khairul anwar

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

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

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?

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 4 9 4 9 16 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)>90 count=count+1; end disp(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 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)

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)

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

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?

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 loops for k = 1:5 a(k)=k^2 end

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

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

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)

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

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=[45 23 17 34 85 33]; 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)

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 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 ([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 file z= 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 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