Library Functions... 1.Old functions 2.Vocabulary 3.Rounding numbers 4.Generating random numbers 5.mod() 6.Properties of mod() 7.Ex1: even or odd? 8.Ex2:

Slides:



Advertisements
Similar presentations
Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
Advertisements

MATLAB Examples. CS 1112 MATLAB Examples Find the number of positive numbers in a vector x = input( 'Enter a vector: ' ); count = 0; for ii = 1:length(x),
CMSC 104, Version 9/011 Arithmetic Operators Topics Arithmetic Operators Operator Precedence Evaluating Arithmetic Expressions In-class Project Incremental.
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Introduction to Computing Science and Programming I
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.
Announcements Next Tuesday (March 12 th ). Department meeting. – Ms. Liron’s office hours start at 2:15pm TAKE NOTES! fill in the blanks! 1.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
1 Pendahuluan Pertemuan 5 Matakuliah: H0062/Teori Sistem Tahun: 2006.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
 2007 Pearson Education, Inc. All rights reserved C Functions.
CHAPTER 3: CORE PROGRAMMING ELEMENTS Introduction to Computer Science Using Ruby (c) 2012 Ophir Frieder et al.
Programmer Defined Functions Matthew Verleger. Windows It’s estimated that Window’s XP contains 45 million lines of code (and it’s over 10 years old).
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 3 Variables, Calculations, and Colors Starting Out with Games.
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
Lecture for Week Spring.  Numbers can be represented in many ways. We are familiar with the decimal system since it is most widely used in everyday.
Functions 1 parameter, 2 return-values "Conversion of time format" One problem. 5 steps to solve it. 1.
1 Lecture 3 Part 1 Functions with math and randomness.
Matlab tutorial course Lesson 2: Arrays and data types
C Programming Lecture 3. The Three Stages of Compiling a Program b The preprocessor is invoked The source code is modified b The compiler itself is invoked.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Lecture 4 Input/Output Conditional Statements 1. Data Types 2. Input/Outputs 3. Operators 4. Conditionals 1.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
General Programming Introduction to Computing Science and Programming I.
Developing a Solution How to create the computer-based solution for a real-world problem. 1.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
PYTHON. Python is a high-level, interpreted, interactive and object- oriented scripting language. Python was designed to be highly readable which uses.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
Presenting results to the USER in a professional manner 1. semicolon, disp(), fprintf() 2. Placeholders 3. Special characters 4. Format-modifiers Output.
1 Functions 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing 6. Projects 1 and 2.
1 Lab of COMP 406 Teaching Assistant: Pei-Yuan Zhou Contact: Lab 1: 12 Sep., 2014 Introduction of Matlab (I)
Agenda  Commenting  Inputting Data from Keyboard (scanf)  Arithmetic Operators  ( ) * / + - %  Order of Operations  Mixing Different Numeric Data.
Input, Output, and Processing
Arithmetic Operators Topics Arithmetic Operators Operator Precedence
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 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 11 Conditional.
1. Exam Topics Difference between computers and calculators John creates a new device. It will compute the orbit of all the planets in the solar system.
1 Week 2: Variables and Assignment Statements READING: 1.4 – 1.6 EECS Introduction to Computing for the Physical Sciences.
Keeping it Neat: Functions and JavaScript Source Files Chapter 7.
Review for Exam2 Key Ideas 1. Key Ideas: Boolean Operators (2 > 3) || (3 < 29.3) A.True B.False C.Impossible to determine (22 > 3) && (3 > 29.3) A.True.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
1. Example 1 – Averages 2. Example 2 – Rolling Dice 3. Example 3 – Number Analysis 4. Example 4 - Divisibility ( while ) Additional Examples on for Loops.
Library Functions... 1.Old functions 2.Vocabulary 3.Rounding numbers 4.Generating random numbers 5.mod() 6.Properties of mod() 7.Ex1: even or odd? 8.Ex2:
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Functions.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
Asking the USER for values to use in a software 1 Input.
Lecture 5 1.What is a variable 2.What types of information are stored in a variable 3.Getting user input from the keyboard 1.
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.
Asking the USER for values to use in a software 1 Input.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
1 Chapter 3 – Examples The examples from chapter 3, combining the data types, variables, expressions, assignments, functions and methods with Windows controls.
1 CS1371 Introduction to Computing for Engineers Control Statements 9/4/2003.
Topic Review for Exam 1 0.Infrastructure: You must be able to use MATLAB, Blackboard Exams, and Blackboard submissions 1. Computer Developing algorithms.
Lecture 6: Output 1.Presenting results in a professional manner 2.semicolon, disp(), fprintf() 3.Placeholders 4.Special characters 5.Format-modifiers 1.
1 Lecture 3 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 3 Friday 03 Oct 2014 EGR 115 Introduction to Computing for Engineers.
Computer Programming for Engineers
Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1.
MATLAB Constants, Variables & Expression Nafees Ahmed Asstt. Professor, EE Deptt DIT, DehraDun.
Practice Programming Exam 1 Review: Part 2 1. Programming Example Bags Fly Fee!!! 2 XYZ is a commercial airline that asked you to create a MATLAB program.
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
Computer Science Up Down Controls, Decisions and Random Numbers.
Chapter 3 Arrays and Vectors
MATLAB: Structures and File I/O
Chapter 5 - Functions Outline 5.1 Introduction
Few More Math Operators
Matlab Basics.
Presentation transcript:

Library Functions... 1.Old functions 2.Vocabulary 3.Rounding numbers 4.Generating random numbers 5.mod() 6.Properties of mod() 7.Ex1: even or odd? 8.Ex2: error when not a whole number 1

1. Remember these functions? clc clear sin(), sind() … sqrt(), abs() … input(), fprintf(), disp() 2

2. Official vocabulary variable = functions_name( argument list ); Example: hypotenuse = sqrt(a^2+b^2); 3 1. This is a “function call”. MATLAB “calls upon the execution” of the code behind the keyword. 3. MATLAB “collects” the “return-value” inside this variable. 2. MATLAB is “passing” inputs to the function. 1. MATLAB “calls upon the execution” of sqrt() 2. MATLAB “passes” the result of a^2+b^2” 3. MATLAB “collects” the “return-value”

Various uses While the function’s name is ALWAYS needed, the call may/may not require either one of the other 2 parts. variable = functions_name( arguments); For example… clc and clear require neither fprintf() requires at least 1 argument (the format string), but typically we do not collect the result. 4

Arguments? Collecting return values? 1 or many arguments: – Some functions are versatile in how many arguments they need – When there is a list of arguments, separate each with a comma:, 1 argument: a string age = input(‘Enter your age: ’); 2 arguments: both strings username = input(‘Username: ’, ‘s’); 3 arguments: 1 string and 2 variables fprintf(‘Hello %s! You are %d years old!\n’,… username, age); 5 

Rounding functions Rounding floats to integer *w.r.t = with respect to 6 FunctionDefinitionsExamples round() Rounds *w.r.t 0.5__?__13-7 ceil() Rounds towards +infinity3__?__-6 floor() Rounds towards -infinity212__?__ + - NEW

Examples 7 How many bags of concrete mix are needed to build stairs? Step1: -Givens needed: -Dimensions of one step -How many stairs -How much concrete does one bag of concrete mix make? -Find: -Number of bags needed Civil Eng.

Examples 8 depth width height Civil Eng. Step2

Examples 9 How many bags of concrete are needed to build stairs? Step5: Assuming 6 stairs: 3ft wide, 6in tall, 11in deep totVolume(ft3) = Nb_stairs * width * depth * thick = 6 * 3* 6/12 * 11/12 = 8.25 ft^3 Number of bags = totVolume(ft3)/ volume1bag = 8.25/0.66 = There is a need for ______ bags. Civil Eng.

Try 10 This Convert 5632seconds to a format hrs:min:sec! 5632 secd = hours 3600 (secd/hr) Round down: 1 full hour 5623 sec – 1* 3600 sec = 2023 seconds 2023 secd = minutes 60(secd/min) Round down: 33 full minutes Tonight!

Example2 11 Hrs/Min/Sec 2023 – 33*60 = 43 seconds Conclusion: 5632seconds is also: 01:33:43 The function used to round down is: ________ Best practice: code this mini-example tonight. Allow the user to enter the initial number of seconds.

4. Generating Random Numbers Generating random numbers rand() is another one of those versatile functions x=rand; x=rand(); %some keep the () to remind themselves it is a function-call vs. a variable name. x=rand(1); %avoid, it’s overdoing it… x=rand(2); %a 2-rows by 2-columns matrix x=rand(2,5); %a 2-rows by 5-columns matrix 12 rand Generates one float between 0 and 1 both excluded. rand(n) Generates a matrix with n^2 floats between 0 and 1 both excluded. (used in 2 weeks from now) rand(n,m) Generates an n-row by m-column matrix with floats between 0 and 1 both excluded. (used in 2 weeks from now) 

rand() and a little bit of algebra: +- What happens to a number k between 0 and 1 if it is added to another number? For example: What can we say about:2+k ? What can we say about:k-4 ? >> The interval shifts left/right k 2 3 k 0 1

rand() and a little bit of algebra: */ What happens to a number k between 0 and 1 if it is multiplied by another number? For example: What can we say about:5*k ? What can we say about:k/2 ? >> The interval grows/shrinks k 0 5 k

rand() and a little bit of algebra What is the range of values K lies within? K = rand*6; K = rand*45-6; K = 2+rand*3.3; K = -6.5+rand/2; K = (rand*3)/2-2; 15 ? ? K

End of algebra So.. Using a combination of arithmetic operators, how would you generate these values (both excluded): k1 = rand_______________________; k2 = rand_______________________; k k2

Conclusion To generate 1 float in the interval: ]a,b[ k = rand*(b-a)+a; This is not a formula worth remembering.. Just remember algebra! 17

What about generating whole numbers? If rand generates one float, how do we generate random numbers? – like dice values: 1-6? (included of course) %roll the die die = ____________; %check if winner if die == 6 fprintf(‘you won!\n’); end 18

Why not round? What happens with we do this: round(6*rand) ()

Useless combinations Realize you’re wasting characters… – ceil(rand) will always generate the value ________. (try it) – floor(rand) will always generate the value ________. (try it) “ceil(rand)” is 10 characters…. “floor(rand)” is 11 characters… WHY BOTHER???? 20

Example1 21 Thermometer A new thermometer is being built. In addition to showing the temperature, the manufacturer also wants to indicate a warning if the temperature is above or equal to 104 degrees Fahrenheit. You are being paid ($$$) to develop the program that will eventually be within the thermometer. It’s been a year, and still no thermometer.. How long are you going to wait???

Example2 22 Rockets0/1’s? How about rockets??? How does software get written? Do we waste a rocket each time? During launch, so many sensors give back information!!! A couple of them are…. -Doors locked? True/False -Oxygen flowing properly? True/False -Fuel being delivered to engine? True/False

1. Modulus The modulus-function calculates the remainder of a long division >> doc mod 23

1. Modulus The modulus-function calculates the remainder of a long division >> doc mod For example: 24 >>result = 77/3 result = >>result = mod(77,3) result = 2 >>

1. Modulus The modulus-function calculates the remainder of a long division >> doc mod For example: 25 >>result = 77/3 result = >>result = mod(77,3) result = 2 >> mod(..) is a function that REQUIRES TWO ARGUMENTS. ( mod(77) is an invalid statement…)

1. Modulus The modulus-function calculates the remainder of a long division >> doc mod For example: 26 >>result = 77/3 result = >>result = mod(77,3) result = 2 >> How is this ever useful…?

2. Properties of mod() If x is evenly divisible by y (i.e no left-overs), mod(x,y) will return 0 “mod” any number with another one “N”, the return-value will be a whole number from 0 to N-1. For example: 27 Mod by 2 mod(2,2)0 mod(3,2)1 mod(4,2)0 mod(5,2)1 mod(6,2)0 mod(15,2)? Mod by 3 mod(3,3)0 mod(4,3)1 mod(5,3)2 mod(6,3)0 mod(7,3)1 mod(26,3)? Mod by 5 mod(2,5)0 mod(5,5)0 mod(6,5)1 mod(7,5)2 mod(8,5)3 mod(9,5)4 mod(10,5)?

2. Properties of mod() If x is evenly divisible by y (i.e no left-overs), mod(x,y) will return 0 “mod” any number with another one “N”, the return-value will be a whole number from 0 to N-1. For example: 28 Mod by 2 mod(2,2)0 mod(3,2)1 mod(4,2)0 mod(5,2)1 mod(6,2)0 mod(15,2)? Mod by 3 mod(3,3)0 mod(4,3)1 mod(5,3)2 mod(6,3)0 mod(7,3)1 mod(26,3)? Mod by 5 mod(2,5)0 mod(5,5)0 mod(6,5)1 mod(7,5)2 mod(8,5)3 mod(9,5)4 mod(10,5)?

2. Properties of mod() If x is evenly divisible by y (i.e no left-overs), mod(x,y) will return 0 “mod” any number with another one “N”, the return-value will be a whole number from 0 to N-1. For example: 29 Mod by 2 mod(2,2)0 mod(3,2)1 mod(4,2)0 mod(5,2)1 mod(6,2)0 mod(15,2)? Mod by 3 mod(3,3)0 mod(4,3)1 mod(5,3)2 mod(6,3)0 mod(7,3)1 mod(26,3)? Mod by 5 mod(2,5)2 mod(5,5)0 mod(6,5)1 mod(7,5)2 mod(8,5)3 mod(9,5)4 mod(10,5)?

Ex1. Even or Odd? Prompt the user for a whole number, then display whether that number is even or odd. Algorithm is rather straightforward! % prompt the user for whole number % if number is odd % Display ‘odd’ % elseif number is even % Display ‘even’ % else %error message 30

Ex1. Even or Odd? Prompt the user for a whole number, then display whether that number is even or odd. Algorithm is rather straightforward! % prompt the user for whole number % if number is odd % Display ‘odd’ % elseif number is even % Display ‘even’ % else %error message 31 But how? What does it mean for a number to be odd?

Ex1. Even or Odd? A number x is odd if the remainder of the division by 2 is equal to 1. – Translate to coding: “If the remainder of the division by 2 is equal to 1.” if mod(x,2) == 1 32

Ex1. Even or Odd? A number x is odd if the remainder of the division by 2 is equal to 1. – Translate to coding: “If the remainder of the division by 2 is equal to 1.” if mod(x,2) == 1 A number x is odd if the remainder of the division by 2 is not equal to 0. – Translate to coding: “If the remainder of the division by 2 is not equal to 0.” if mod(x,2) ~= 0 33 Think about “even” on your own..

Ex1. Even or Odd? % prompt the user for whole number nb = input(‘Enter a WHOLE number: ’); %if number is odd if mod(nb,2) == 1 fprintf(‘%d is odd\n’, nb) elseif mod(nb,2) == 0 %nb is even fprintf(‘%d is even\n’,nb) else disp(‘Number is invalid’) end 34 When would this happen?

Ex1. Even or odd? – issues? The remainder of a division of a float value will never give a 0 or a 1!! The number is neither even, nor odd. 35

Ex1. Even or odd? – issues? The remainder of a division of a float value will never give a 0 or a 1!! The number is neither even, nor odd. Ironically, mod() can be used to fix this issue!!! 36 Let’s apply this to a previous problem that was solved…

Ex2: Check for integers Remember “Who Should Start?” % prompt how many players total totalPlayers = input('How many players (WHOLE number only): '); % generate the one who starts (0-max) startPlayer = ceil(rand*totalPlayers); % continue with game… fprintf('Player #%d will start.\n', startPlayer); Since there are no error-check, the following can happen! 37 Let’s add an error message when an float is entered!...

Check for integers, algorithm %prompt user for total players %if invalid (negative, zero, or not integer) %error message %else %generate 1 st player %continue with game 38

Check for integers, code %prompt user for total players totalPlayers = input('How many players (WHOLE number only): '); %if invalid (negative, zero, or not integer) if totalPlayers<=0 || ???? %error message disp(‘error. Enter a positive WHOLE number only!’); else %input was valid, proceed with code %generate 1 st player startPlayer = ceil(rand*totalPlayers); %continue with game… end 39 Using mod() in your answer, what does it mean for a number to not-be-an-integer?

Check for integers, mod() %prompt user for total players totalPlayers = input('How many players (WHOLE number only): '); %if invalid (negative, zero, or not integer) if totalPlayers<=0 || mod(totalPlayers,1)~=0 %error message disp(‘error. Enter a positive WHOLE number only!’); else %generate 1 st player startPlayer = ceil(rand*totalPlayers); %continue with game… end 40

Key Ideas Vocabulary – Function call – Arguments – Collecting – Return-values – Versatile New notions – Rounding up/down/ or w.r.t 0.5 – Generating random numbers – Generating 1 random float value Manipulating it to desire random range wanted – Generating a zero/one to simulate false/true Examples – Cement for stairs: ceil() – Time formatting:floor() – Temperature:rand() – Rocket:all of the above!! 41

Key Ideas mod() is a built-in function that calculates the remainder of a division >> doc mod to see help window Commonly used to check if a number is divisible by another. – In other word, mod can be used to check if a number is a multiple of another. mod(.., 2) is used to check even/odd mod(.., 1) is used to check whole/decimal number mod(.., N) is used to check if a number is divisible by N 42