ENGR-25_Programming-4.ppt 1 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 1 Bruce Mayer, PE Licensed Electrical.

Slides:



Advertisements
Similar presentations
ENGR-25_Plot_Model-2.ppt 1 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods Bruce Mayer, PE Licensed Electrical.
Advertisements

Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
3-2 What are relational operators and logical values? How to use the input and disp functions. Learn to use if, if-else and else-if conditional statements.
Fall 2004ENGR 111A MatLab – Palm Chapter 4, Part 2 The if and switch structure Class 10.1 Sections: 4.4 and 4.6.
Repeating Actions While and For Loops
Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.
MatLab – Palm Chapter 4, Part 3 For and While Loops
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Week 7 - Programming I Relational Operators A > B Logical Operators A | B For Loops for n = 1:10 –commands end.
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
Chapter 5: Repetition Statements. In this chapter, you will learn about: Basic loop structures while loops Interactive while loops for loops Loop programming.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
Licensed Electrical & Mechanical Engineer
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Selection Programming EE 100. Outline introduction Relational and Logical Operators Flow Control Loops Update Processes.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
ENGR-25_MATLAB_OverView-1.ppt 1 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods Bruce Mayer, PE Licensed Electrical.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
CMPS 1371 Introduction to Computing for Engineers CONDITIONAL STATEMENTS.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
ENGR-25_Programming-3.ppt 1 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods Bruce Mayer, PE Licensed Electrical.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
ITEC113 Algorithms and Programming Techniques
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Algorithm Design.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
ENGR-25_MATLAB_OverView-2.ppt 1 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods Bruce Mayer, PE Licensed Electrical.
Using Java MINISTRY OF EDUCATION & HIGHER EDUCATION COLLEGE OF SCIENCE AND TECHNOLOGY KHANYOUNIS- PALESTINE Lecture 9 & 10 Repetition Statements.
ENGR-25_Programming-4.ppt 1 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 1 Bruce Mayer, PE Licensed Electrical.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
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.
ENGR-25_Prob_2-24_Solution.ppt 1 Bruce Mayer, PE ENGR/MTH/PHYS25: Computational Methods Bruce Mayer, PE Registered Electrical.
Matlab tutorial course Lesson 4: Writing your own functions: programming constructs
Matlab Programming for Engineers
ENG College of Engineering Engineering Education Innovation Center 1 Basic For Loops in MATLAB Programming in MATLAB / Chapter 6 Topics Covered:
ENGR-25_Programming-1.ppt 1 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods Bruce Mayer, PE Registered Electrical.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
Perl Chapter 3 Conditional statements. Control Expressions Control expressions – interpreted as T/F (evaluated as strings or numbers) – simple, relational,
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
1 Structured Programming EEN170 Programming in MATLAB.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Flow control. Conditionals if condition do this stuff end if condition do this stuff else do this stuff end if condition do this stuff elseif condition.
‘C’ Programming Khalid Jamal.
REPETITION CONTROL STRUCTURE
Scripts & Functions Scripts and functions are contained in .m-files
Ch 7: JavaScript Control Statements I.
Chapter 6: Conditional Statements and Loops
JavaScript: Control Statements.
Iteration: Beyond the Basic PERFORM
Types of Flow of Control
3 Control Statements:.
Chapter 6: Repetition Statements
REPETITION Why Repetition?
Presentation transcript:

ENGR-25_Programming-4.ppt 1 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 1 Bruce Mayer, PE Licensed Electrical & Mechanical Engineer Engr/Math/Physics 25 Chp4 MATLAB Programming-4

ENGR-25_Programming-4.ppt 2 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 2 Please HELP Rm 3906A Lab  Please do NOT SAVE ANY Files to the DESKTOP on the computers in Rm3906A Lab  Saving to the machine DeskTop Leads to Clutter and Glitchy Computers  Thank You

ENGR-25_Programming-4.ppt 3 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 3 Learning Goals  Write MATLAB Programs That can MAKE “Logical” Decisions that Affect Program Output  Write Programs that Employ LOOPing Processes For → No. Loops know a priori while → Loop Terminates based on Logic Criteria

ENGR-25_Programming-4.ppt 4 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 4 Loop Structures  The conditional statements ( if, else, elseif ) we learned last time allowed us to determine at run-time whether or not to execute a block of code.  What these Decision Statements Do NOT do is to allow us to execute a block more than once  The TWO Things that Computers Do Better than People STORE Massive Amounts of Data REPEAT operations

ENGR-25_Programming-4.ppt 5 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 5 Repetition → LOOPs  A “LOOP” is a Program Structure that REPEATS Until some CONDITION is MET  The NUMBER of Loops may Be Known a priori (ahead of time) –No. of Loops Determined by simple COUNTING Determined Dynamically –No. of Loops Determined by a DECISION statement  The Loop consists of A Condition Test A Repeated Statement-Block

ENGR-25_Programming-4.ppt 6 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 6 Test vs Statement Locations  PreTest Loop  The key feature → we test to see whether or not to continue before executing the body of the loop. i.e., The Loop May Not Execute at All  Good if Potential Zero Executions is Desired  a.k.a. “While DO”

ENGR-25_Programming-4.ppt 7 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 7 Test vs Statement Locations  PostTest Loop  The Key feature → Do Not Test Until the Block Executes at Least Once  Use if Design Calls for at Least-One Repetition  a.k.a. “DO While”

ENGR-25_Programming-4.ppt 8 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 8 Test vs Statement Locations  MidTest Loop  The generalization of both the pre-test and the post-test loops Empty Block-1 → PreTest Loop Empty Block-2 → PostTest Loop

ENGR-25_Programming-4.ppt 9 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 9 for Loop Statement  A PreTested, COUNTED Loop Start k ≤ n? Statements-1 end Statements True False Set k = m Increment k by s No. Repetitions Known  MATLAB Syntax for Counter = Start : Increment: End statements end

ENGR-25_Programming-4.ppt 10 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 10 for Loop Rules  Given for Loop Counting Variable: k=m:s:n The step value s may be negative –Example: k = 10:-2:4 produces k = 10, 8, 6, 4 If s is omitted, the step value defaults to +1 If s is positive, the loop will not be executed if m is greater than n If s is negative, the loop will not be executed if m is less than n If m equals n, the loop will be executed only once If the step value s is not an integer, round-off errors can cause the loop to execute a different number of passes than intended

ENGR-25_Programming-4.ppt 11 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 11 For Loop Example  Construct a 23x11 2D Array filled with RANDOM integer between −99 and +99  Game Plan: Use Nested for Loops along with rand, round, & fix commands Track the No. of Construction Steps  The MATLAB Code

ENGR-25_Programming-4.ppt 12 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 12 The continue Statement  The continue statement passes control to the next iteration of the loop in which it appears, skipping any remaining statements in the body of the loop.  The Following Code Uses a continue x = [10,1000,-10,100]; y = NaN*x; for k = 1:length(x) if x(k) < 0 continue end y(k) = log10(x(k)); end statement to avoid taking the log of a negative number.  The Result: y = 1, 3, NaN, 2

ENGR-25_Programming-4.ppt 13 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 13 Remove continue Statement  Let’s Fine Tune the No-Neg-Log Code by COMMENTING OUT the if- continue Commands x = [10,1000,-10,100]; y = NaN*x; for k = 1:length(x) %if x(k) < 0 %continue %end y(k) = log10(x(k)); end  The Result: y = i

ENGR-25_Programming-4.ppt 14 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 14 Use of a Logical MASK  The use of loops and branching can often be avoided, thus creating simpler and faster programs by using a logical array as a mask that selects elements of another array. Any elements not selected will remain unchanged.  The following session creates the logical array D from the 3x3 numeric array B

ENGR-25_Programming-4.ppt 15 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 15 Use of a Logical MASK cont  Logical Mask Session >> B = [0, -1, 4; 9, -14, 25; -34, 49, 64] B = >> D = (B >= 0) D = Mask Array → a Logical that “masks out” Negative numbers

ENGR-25_Programming-4.ppt 16 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 16 Logical MASK cont >> B(D) = sqrt(B(D)) B = >> B(~D) = B(~D) + 50 B = Negative Values Unchanged → Masked OUT by D(m,n) = 0 Original B = Positive Values Unchanged → Masked OUT by D(m,n) = 1  Logical Mask Session cont

ENGR-25_Programming-4.ppt 17 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 17 Logical Masking Subtlety >> x = [ ] x = >> nn = x>=0 % the logical mask nn = >> y = x(nn) y = >> sqrt1 = sqrt(x(nn)) sqrt1 = >> sqrt2 = x % make starting copy of x sqrt2 = >> sqrt2(nn) = sqrt(sqrt2(nn)) sqrt2 = ONLY the Three Sq-Roots the Three Sq-Roots AND the two NON- Roots

ENGR-25_Programming-4.ppt 18 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 18 while Loops  The while loop is used when the looping process terminates because a specified condition is satisfied, and thus the number of passes is not known in advance.  A simple example of a while loop is x = 5; while x < 25 disp(x) x = 2*x - 1; end  Results from the disp statement are 5, 9, and 17.

ENGR-25_Programming-4.ppt 19 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 19 while Loop Statement  A PreTested DYNAMIC Loop Start Logical Decision Statements (MUST Increment Loop Variable) end Statements True False No. Repetitions UNknown  MATLAB Syntax while Logical Expression statements end Set Loop Var Initial value

ENGR-25_Programming-4.ppt 20 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 20 while Loop Statement  For the while loop to function properly two conditions must occur Start Logical Decision Statements (MUST Increment Loop Variable) end Statements True False 1.The loop variable must have a value BEFORE the while statement is executed (initialize) 2.The loop variable must be changed somehow by the statements INSIDE the Loop Set Loop Var Initial value

ENGR-25_Programming-4.ppt 21 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 21 while Loop Build Vector  A simple while loop x = 5;k = 0; while x < 25 k = k + 1 y(k) = 3*x; x = 2*x-1 end  The Results k = 1 x = 9 k = 2 x = 17 k = 3 x = 33 The loop variable x is initially assigned the value 5, and it keeps this value until the statement x = 2*x - 1 is encountered the first time. Its value then changes to 9. Before each pass through the loop, x is checked to see if its value is less than 25. If so, the pass is made. If not, the loop terminates >> y y =

ENGR-25_Programming-4.ppt 22 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 22 Another while Loop Example  Write a.m- file to determine The min. number of terms required for the sum of the series 5k 2 – 2k; k = 1, 2, 3, … to just exceed 10,000. the sum for this number of terms  The.m-file and the Results tot = 0;k = 0; while tot < 10e3 k = k + 1; tot = 5*k^2 - 2*k + tot; end disp('No. terms = ') disp(k) disp('The Sum = ') disp(tot) No. Terms = 18 Sum = 10203

ENGR-25_Programming-4.ppt 23 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 23 Demos: for & while  Prob 4-22 → Evaluate with for Also list the value of the individual Terms  Use while to find the number of terms, q max, such that

ENGR-25_Programming-4.ppt 24 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 24 The switch Structure  The switch structure provides an alternative to using the if, elseif, and else commands. Anything programmed using switch can also be programmed using if structures.  However, for some applications the switch structure produces more readable code than when using the if structure.

ENGR-25_Programming-4.ppt 25 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 25 MATLAB switch Syntax switch input expression (which can be a scalar or string). case value1 statement group 1 case value2 statement group 2... otherwise statement group n end

ENGR-25_Programming-4.ppt 26 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 26 switch Example  This switch Block displays the High School Class-Name that Corresponds to a Given Grade Level grade_level = input('Hi- School Grade Level.: '); switch grade_level case 9 disp(' Freshman') case 10 disp(' Sophomore') case 11 disp(' Junior') case 12 disp(' Senior') otherwise disp(' NOT a Hi-Schl Grade Lvl') end

ENGR-25_Programming-4.ppt 27 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 27 switch Example Results Hi-School Grade Level.: 9 Freshman Hi-School Grade Level.: 11 Junior Hi-School Grade Level.: 13 NOT a Hi-Schl Grade Lvl Hi-School Grade Level.: 10 Sophomore

ENGR-25_Programming-4.ppt 28 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 28 Example: Prob 4.27  Consider an Electrical Diode →  We can MODEL the V-I Behavior of this Device in Several ways V I REAL Behavior IDEAL Model OFFSET Model LINEAR Model

ENGR-25_Programming-4.ppt 29 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 29 Problem-27 cont  The Diode exhibits a form of RECTIFICATION i.e., It allows current to Flow in the FORWARD direction, But NOT in the REVERSE direction –Think of a diode as a “Check-Valve” for Electrical Current”

ENGR-25_Programming-4.ppt 30 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 30 Problem-27 cont  Now Let’s Connect the Diode to A Power Source, V s A Useful Load, R L  Next Assume that V s is a Decaying Sinusoidal, Alternating Current (AC) Voltage-Source modeled mathematically as + V L -

ENGR-25_Programming-4.ppt 31 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 31 Problem-27 → Plot Vs +VL -+VL - % Bruce Mayer, PE * 08Sep11 % ENGR25 * Problem 4-27 % file = Prob4_27_Vs_plot.m % INPUT SECTION tmax = input('Max time in sec = '); Vmax = input('Max Supply Potential in V = '); %CALCULATION SECTION % use linspace command to generate 500 time pts t = linspace(0,tmax,500); % Use for-Loop to generate plotting vector, vs for k = 1:500 % Calc SUPPLY V-Level vsup = Vmax*exp(-t(k)/3)*sin(pi*t(k)); vs(k) = vsup; end % PLOT SECTION plot(t,vs),ylabel('Load Voltage (V)'),xlabel('Time (sec)'),... title('Ideal-Diode Rectifier'), grid disp('Plot Complete')

ENGR-25_Programming-4.ppt 32 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 32 Problem-27 → Plot Vs +VL -+VL - Diode ON

ENGR-25_Programming-4.ppt 33 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 33 Prob 27 cont  Recall the Ideal-Diode Model →  With This Diode Behavior we Expect Load a Voltage in this form IDEAL Model +VL -+VL -  Write a MATLAB Program to Plot V L vs t for: 0  t  10s

ENGR-25_Programming-4.ppt 34 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 34 Problem-27 → Plot V L Ideal +VL -+VL - % Bruce Mayer, PE * 08Sep11 % ENGR25 * Problem 4-27a % file = Prob4_27a_ideal_diode.m % INPUT SECTION tmax = input('Max time in sec = '); Vmax = input('Max Supply Potential in V = '); % CALCULATION SECTION % use linspace command to generate 500 time pts t = linspace(0,tmax,500); % Use for-Loop to generate plotting vector, vL for k = 1:500 % Calc SUPPLY V-Level at the current t(k) vs = Vmax*exp(-t(k)/3)*sin(pi*t(k)); % chk Fwd or Rev condition by if-else if vs > 0 vL(k) = vs; % diode absorbs NO voltage else vL(k) = 0; % diode BLOCKS ALL Current end end plot(t,vL),ylabel('Load Voltage (V)'),xlabel('Time (sec)'),... title('Ideal-Diode Rectifier'), grid VSVS

ENGR-25_Programming-4.ppt 35 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 35 Problem-27 → Plot V L Ideal IDEAL Model

ENGR-25_Programming-4.ppt 36 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 36 Prob 27 cont  Recall the OffSet-Diode Model →  With This Diode Behavior we Expect Load Voltage in this form +VL -+VL -  Write a MATLAB Program to Plot V L vs t for: 0  t  10s OFFSET Model

ENGR-25_Programming-4.ppt 37 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 37 Problem-27 → Plot V L Offset +VL -+VL - % Bruce Mayer, PE * 08Sep11 % ENGR25 * Problem 4-27b % file = Prob4_27b_offset_diode.m % INPUT SECTION tmax = input('Max time in sec = '); Vmax = input('Max Supply Potential in V = '); % CALCULATION SECTION % use linspace command to generate 500 time pts t = linspace(0,tmax,500); % Use for-Loop to generate plotting vector, vL for k = 1:500 % Calc SUPPLY V-Level at current t(k) vs = Vmax*exp(-t(k)/3)*sin(pi*t(k)); % chk Fwd or Rev condition by if-else if vs > 0.6 vL(k) = vs-0.6; % diode absorbs 0.6V else vL(k) = 0; % diode BLOCKS All current end end plot(t,vL),ylabel('Load Voltage (V)'),xlabel('Time (sec)'),... title('Offset-Diode Rectifier'), grid VSVS

ENGR-25_Programming-4.ppt 38 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 38 Problem-27 → Plot V L Offset OFFSET Model

ENGR-25_Programming-4.ppt 39 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 39 Prob 27 Analysis  Compare Plots Side-by-Side  0.6V Offset has a large affect when the V s amplitude is only 3V OffSet is 20% of amplitude +VL -+VL -

ENGR-25_Programming-4.ppt 40 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 40 Prob 24 Analysis  Plots for 24V amplitude  Makes less difference Note different vertical scales +VL -+VL -

ENGR-25_Programming-4.ppt 41 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 41 All Done for Today Sinusoidal HalfWave Rectifier

ENGR-25_Programming-4.ppt 42 Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods 42 Bruce Mayer, PE Licensed Electrical & Mechanical Engineer Engr/Math/Physics 25 Appendix