Lecture 4 MATLAB programming (2)

Slides:



Advertisements
Similar presentations
While loops.
Advertisements

1 EMT 101 – Engineering Programming Dr. Farzad Ismail School of Aerospace Engineering Universiti Sains Malaysia Nibong Tebal Pulau Pinang Week 10.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
1 Loops. 2 Often we want to execute a block of code multiple times. Something is always different each time through the block. Typically a variable is.
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
CS107 Introduction to Computer Science Loops. Instructions Pseudocode Assign values to variables using basic arithmetic operations x = 3 y = x/10 z =
Tutorial 12 Working with Arrays, Loops, and Conditional Statements
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Repetition Statements repeat block of code until a condition is satisfied also called loops Java supports 3 kinds of loops: while statement – repeats a.
MATLAB Review Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 4 Loops and Character Manipulation Dr. Ali Can Takinacı İstanbul Technical University Faculty of Naval Architecture and Ocean Engineering İstanbul.
Lecture 12 Another loop for repetition The while loop construct © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
Week 7 - Programming II Today – more features: – Loop control – Extending if/else – Nesting of loops Debugging tools Textbook chapter 7, pages
Loops are MATLAB constructs that permit us to execute a sequence of statements more than once. There are two basic forms of loop constructs: i. while.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
Multi-Dimensional Arrays
Chapter 5 Control Structures: Loops 5.1 The while Loop The while loop is probably the most frequently used loop construct. The while loop is a conditional.
MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014
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.
1 Flowchart notation and loops Implementation of loops in C –while loops –do-while loops –for loops Auxiliary Statements used inside the loops –break –continue.
Looping II (for statement). CSCE 1062 Outline  for statement  Nested loops  Compound assignment operators  Increment and decrement operators.
Chapter 4 Loops Write code that prints out the numbers Very often, we want to repeat a (group of) statement(s). In C++, we have 3 major ways of.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Matlab Programming for Engineers
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
CSCI 161 Lecture 7 Martin van Bommel. Control Statements Statements that affect the sequence of execution of other statements Normal is sequential May.
EGR 115 Introduction to Computing for Engineers Loops and Vectorization – Part 1 Monday 13 Oct 2014 EGR 115 Introduction to Computing for Engineers.
Chapter 8 Loops. For Loop >Executes a block of statements a specified number of times. Form: for loop variable=first:incr:last statements end.
COMP Loop Statements Yi Hong May 21, 2015.
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.
Finishing up Chapter 5. Will this code enter the if statement? G=[30,55,10] if G
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
CSE123 - Lecture 4 Structured Programming- Loops.
Computer C programming Chapter 3. CHAPTER 3 Program Looping –The for Statement –Nested for Loops –for Loop Variants –The while Statement –The do Statement.
Control Structure  What is control Structure?  Types of Controls  Use the control structure in VBScript.  Example Summery.
PH2150 Scientific Computing Skills Control Structures in Python In general, statements are executed sequentially, top to bottom. There are many instances.
CS 170 – INTRO TO SCIENTIFIC AND ENGINEERING PROGRAMMING.
Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)
PHP Condtions and Loops Prepared by Dr. Maher Abuhamdeh.
DEVRY CIS 115 F INAL E XAM 3 Check this A+ tutorial guideline at For more classes visit
ECE Application Programming
Matlab Programming for Engineers
2008/09/22: Lecture 6 CMSC 104, Section 0101 John Y. Park
Loops in Java.
CS1371 Introduction to Computing for Engineers
Think What will be the output?
Scripts & Functions Scripts and functions are contained in .m-files
Java Programming: Guided Learning with Early Objects
Ch 7: JavaScript Control Statements I.
MATLAB DENC 2533 ECADD LAB 9.
Logical Operators and While Loops
Week 8 - Programming II Today – more features: Loop control
For Loops October 12, 2017.
Lecture 5 MATLAB programming (3)
Conditional Construct
CS190/295 Programming in Python for Life Sciences: Lecture 6
Types of Flow of Control
Communication and Coding Theory Lab(CS491)
Loop Statements & Vectorizing Code
Looping III (do … while statement)
Computer programming Lecture 3.
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.
Logical Operators and While Loops
Loop Statements & Vectorizing Code
EECE.2160 ECE Application Programming
CS Problem Solving and Object Oriented Programming Spring 2019
REPETITION Why Repetition?
Looping and Repetition
Presentation transcript:

Lecture 4 MATLAB programming (2) Dr .Qi Ying

Objectives For loops While loops Loop speed-up Dot operator Array mask

The For Loop The for loop is a loop that executes a block of statements for a specified number of times. for index = expr statement 1 statement 2 … statement n end index is the loop variable, expr is the control expression. body

The For Loop Control expression The control expression is evaluated by MATLAB at the beginning of the loop. Each time a loop is executed, the control variable will be assigned the value in the next column of the control expression. Several typical forms of the control expression first:last (e.g., for ii=1:10) first:increment:last (e.g., for ii=0.5:0.1:1.5) Row vector (e.g., for ii=[5 9 7]) Matrix (e.g., for ii=[1 2 3; 4 5 6])

Example: factorial Write a program to calculate the factorial: N!=1, N=0 N!=N*(N-1)*(N-2)…*3*2*1, N>0 n=input('Please enter N:'); n_factorial=1; for ii=1:n n_factorial=n_factorial*ii; end fprintf(‘The factorial of %d is %d\n’, n, n_factorial);

Good Programming Practice Indent the bodies of loops Don’t modify the loop variable in the loop for ii=1:n n_factorial=n_factorial*ii; end for ii=1:n n_factorial=n_factorial*ii; end for ii=1:n …. ii=5; % WRONG! SHOULD NOT MODIFY ii … end

Exercise Modify the factorial code to calculate s(n)=1+2+3+…+n

The While Loop The while loop is a block of statements that are repeated indefinitely as long as some condition is satisfied. while expression statement 1 statement 2 … end The loop will be repeated is the value of the logical expression is true.

Example: statistical analysis Problem: Enter from the keyboard an arbitrary number of measurements (>0), and calculate the mean and the standard deviation.

Algorithm while done~=true Read a number from the input, save in x if x>0 Increase the number of data points by 1 Calculate sum_x=sum_x+x Calculate sum_x2=sum_x2+x**2 else Set done=true end

One possible solution, but with a bug. Can you find the bug? n=0;sum_x=0;sum_x2=0; % initialize done=false; while done~=true % loop to input data x=input('Enter a number (0 to finish):'); n=n+1; if x>0 % valid data points sum_x=sum_x+x; sum_x2=sum_x2+x^2; else % need to stop done=true; end if n<2 % not enough data points % check number of data points disp('At least 2 numbers are needed.'); else x_bar=sum_x/n; % mean std_dev=sqrt((n*sum_x2-sum_x^2)/(n*(n-1)));% standard deviation disp(['number of data points:',num2str(n)]); % display results disp(['mean=',num2str(x_bar)]); disp(['std_dev=',num2str(std_dev)]);

Break and continue Break: stop the current for or while loop while done~=true x=input('Enter a number (0 to finish):'); if x>0 n=n+1; sum_x=sum_x+x; sum_x2=sum_x2+x^2; else done=true; end while true x=input('Enter a number (0 to finish):'); if x>0 n=n+1; sum_x=sum_x+x; sum_x2=sum_x2+x^2; else break; end

Break and continue Continue: skipping the remaining statements in the loop and move to the top of the loop. In a for loop, the loop control variable will take the next value. for ii=1:5 if ii==3 continue; end fprintf(‘ii=%d\n’,ii); >> test_continue ii = 1 ii = 2 ii = 4 ii = 5

dot operator Can be used to simplify and speed-up for loops x=0:0.1:10; n=length(x); y=zeros(1,n); for i=1:n y(i)=x(i)^2; end plot(x,y); x=0:0.1:10; y=x.^2; plot(x,y);

Array mask Can be used to simplify and speed-up for loops with if constructs a=[1 2 3; 4 5 6; 7 8 9]; for ii=1:size(a,1) for jj=1:size(a,2) if a(ii,jj)>5 a(ii,jj)=sqrt(a(ii,jj)); end a=[1 2 3;4 5 6; 7 8 9]; b=a>5; a(b)=sqrt(a(b));

Array mask a=[1 2 3; 4 5 6; 7 8 9]; for ii=1:size(a,1) for jj=1:size(a,2) if a(ii,jj)>5 a(ii,jj)=sqrt(a(ii,jj)); else a(ii,jj)=a(ii,jj)^2; end a=[1 2 3;4 5 6; 7 8 9]; b=a>5; a(b)=sqrt(a(b)); a(~b)=a(~b).^2;

Exercise Plot the following function: with t in [-9,9]

Study Study the two examples in section 4.4 Fitting a linear curve through data points (linear regression) Trajectories of a projectile