CS 221 Lecture. Tuesday, 13 September 2011

Similar documents
} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

CS 221 Lecture. Tuesday, 4 October There are 10 kinds of people in this world: those who know how to count in binary, and those who don t.

CS 221 Lecture. Tuesday, 11 October 2011

MATLAB TUTORIAL WORKSHEET

Math 98 - Introduction to MATLAB Programming. Fall Lecture 1

Midterms Save the Dates!

Lecture 1: Hello, MATLAB!

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

An Introduction to MATLAB

Computer Organization and Levels of Abstraction

Computer Organization and Levels of Abstraction

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

Chapter 17. Fundamental Concepts Expressed in JavaScript

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

1 Overview of the standard Matlab syntax

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

CS1 Lecture 3 Jan. 18, 2019

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

CS Introduction to Programming Fall 2016

9. Elementary Algebraic and Transcendental Scalar Functions

CS1 Lecture 3 Jan. 22, 2018

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CS1150 Principles of Computer Science Boolean, Selection Statements

Math 55 - Spring 04 - Lecture notes # 1 - Jan 20 (Tuesday)

Branches, Conditional Statements

Boolean Logic & Branching Lab Conditional Tests

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Computer Vision. Matlab

function [s p] = sumprod (f, g)

MATLAB. Devon Cormack and James Staley

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

CSE 115. Introduction to Computer Science I

CS1 Lecture 5 Jan. 25, 2019

61A Lecture 3. Friday, September 5

Introduction to Programming for Biology Research

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Chapter 3: Programming with MATLAB

CIS 110: Introduction to Computer Programming

Physics 2660: Fundamentals of Scientific Computing. Lecture 5 Instructor: Prof. Chris Neu

CME 193: Introduction to Scientific Python Lecture 1: Introduction

QUIZ: What value is stored in a after this

7 Control Structures, Logical Statements

CS 360 Programming Languages Interpreters

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

CS 3512, Spring Instructor: Doug Dunham. Textbook: James L. Hein, Discrete Structures, Logic, and Computability, 3rd Ed. Jones and Barlett, 2010

Lecture Transcript While and Do While Statements in C++

Matlab for FMRI Module 1: the basics Instructor: Luis Hernandez-Garcia

LECTURE 1. What Is Matlab? Matlab Windows. Help

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Information Science 1

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Fall 2014 MAT 375 Numerical Methods. Introduction to Programming using MATLAB

LAB 2: Linear Equations and Matrix Algebra. Preliminaries

Information Science 1

Outline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

Information Science 1

ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I

Optimization Problems and Wrap-Up. CS 221 Lecture 14 Tue 6 December 2011

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2015

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Expressions and Casting

Control Structures. March 1, Dr. Mihail. (Dr. Mihail) Control March 1, / 28

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

CS 31: Intro to Systems C Programming. Kevin Webb Swarthmore College September 13, 2018

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

COMS 1003 Fall Introduction to Computer Programming in C. Bits, Boolean Logic & Discrete Math. September 13 th

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

HCA Tech Note 600. User Implemented Device Classes for Class Creators

Short Version of Matlab Manual

Outline. Review of Last Week II. Review of Last Week. Computer Memory. Review Variables and Memory. February 7, Data Types

You just told Matlab to create two strings of letters 'I have no idea what I m doing' and to name those strings str1 and str2.

4 Operations On Data 4.1. Foundations of Computer Science Cengage Learning

Step by step set of instructions to accomplish a task or solve a problem

HW3: CS 110X C Domain Information. Final Version: 1/29/2014

MATLAB Operators, control flow and scripting. Edited by Péter Vass

Matrices. A Matrix (This one has 2 Rows and 3 Columns) To add two matrices: add the numbers in the matching positions:

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #06 Loops: Operators

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Note that in this definition, n + m denotes the syntactic expression with three symbols n, +, and m, not to the number that is the sum of n and m.

COMP combinational logic 1 Jan. 18, 2016

Control Structures in Java if-else and switch

15-122: Principles of Imperative Computation, Fall 2015

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

CA4003 Compiler Construction Assignment Language Definition

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Scilab Programming. The open source platform for numerical computation. Satish Annigeri Ph.D.

Lab of COMP 406. MATLAB: Quick Start. Lab tutor : Gene Yu Zhao Mailbox: or Lab 1: 11th Sep, 2013

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Course Outline Introduction to C-Programming

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Announcements. 1. Forms to return today after class:

UNIT- 3 Introduction to C++

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

EL2310 Scientific Programming

Lecture 5. Logic I. Statement Logic

Admin. ! Assignment 3. ! due Monday at 11:59pm! one small error in 5b (fast division) that s been fixed. ! Midterm next Thursday in-class (10/1)

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

AMATH 352: MATLAB Tutorial written by Peter Blossey Department of Applied Mathematics University of Washington Seattle, WA

Selection Statements. Pseudocode

Prerequisites: Read all chapters through Chapter 4 in the textbook before attempting this lab. Read through this entire assignment before you begin.

Transcription:

CS 221 Lecture Tuesday, 13 September 2011

Today s Agenda 1. Announcements 2. Boolean Expressions and logic 3. MATLAB Fundamentals

1. Announcements First in-class quiz: Tuesday 4 October Lab quiz: Thursday 29 September Excel fundamentals Excel conditionals Basic MATLAB computations Homework Assignment 1 available on web site Due next Wednesday, 21 September, 11:59 pm Grading rubric available by Thursday Lab 2 is due Thursday Remember: Bring your textbook to lab!

2. Boolean Expressions and Logic

Learning Arithmetic & Algebra Remember when you learned... Whole number arithmetic: whole numbers (0, 1, 2,...) Operators: addition (+); subtraction ( ); multiplication ( ); division ( ) addition/subtraction facts (5+7=12, 9-4=5) big numbers, carrying/borrowing multiplication tables multiplying multi-digit numbers long division (with remainders) fractions

Learning Arithmetic & Algebra Integer Arithmetic: integers (..., -2, -1, 0, 1, 2,...) Operators: addition (+); subtraction ( ); multiplication ( ); division ( ) addition/subtraction facts; multiplying/dividing positive/negative numbers

Learning Real Algebra Real Arithmetic: Real numbers (0, 1, 2,...) Operators... Laws/properties: Commutative: a + b = b + a, a b = b a Associative: (a + b) + c = a + (b + c) (a b) c = a (b c) Distributive: multiplication distributes over addition a (b + c) = (a b) + (a c) Identity (Unit): 0 + a = a, a 0 = a 1 a = a, a 1 = a Zero: 0 a = 0

Boolean Algebra Only two values: true and false Operators: unary negation: NOT (Excel) ~ (MATLAB) ~false = true, ~true = false conjunction (MATLAB) false false = false false true = false true false = false true true = true disjunction (MATLAB) false false = false false true = true true false = true true true = true

Boolean Algebra Laws/Properties: Disjunction and Conjunction are Associative and Commutative: a b = b a, a b = b a (a b) c = a (b c) (a b) c = a (b c) Distributive: AND, OR distribute over each other a (b c) = (a b) (a c) a (b c) = (a b) (a c) Identity (Unit): true a = a, false a = a Zero: false a = false, true a = true

Conditionals in Programming Both Excel and MATLAB use Boolean Expressions to define conditionals: IF(<boolean expr>,<value if true>,<value if false>) if first argument evaluates to true, value is 2 nd arg, else (evaluates to false) 3 rd arg. if <boolean expr> <statement> end if boolean expr evaluates to true, execute the statement, else (evaluates to false) skip it. Conditionals allow the result of the computation to vary with the data

An Example: HVAC Control The Delta Room oversees heating and cooling operations of most buildings on campus Sensors in buildings report temperature, thermostat settings, and other information Equipment is controlled via outputs from the system

Example: HVAC Control of an Office Control System Inputs: temperature sensor (degrees F) thermostat setting (degrees F) occupancy sensor (boolean) true = occupied false = unoccupied schedule override (boolean) true = override is in effect false = no override current time Control System Outputs: fan control ( ON / OFF ) heating control ( ON / OFF ) cooling control ( ON / OFF )

Example: HVAC Control of an Office Schedule: Normal operating hours are 7 a.m. to 11 p.m. Policy: Cooling unit is ON whenever the temperature is above the thermostat setting, the office is occupied, and the current time is during normal operating hours or the schedule override is on; otherwise OFF. Heating unit is ON whenever the temperature is below the thermostat setting, the office is occupied, and the current time is during normal operating hours or the schedule override is on; otherwise OFF. Fan is ON whenever heating or cooling unit is on.

Modeling the Logic Variable/cell for each input and output Values of output variables depend on input variables Use assignment: output = f(input) Cooling unit should be on if: temperature is above the thermostat setting, the office is occupied, and the current time is during normal operating hours or the schedule override is on This has the form: X and Y or Z (X and Y) or Z vs. X and (Y or Z)...Does it matter?

Truth Tables A way to compute the value of a boolean expression A matrix with: One column for each boolean subexpression, plus one for the whole expression One row for each possible combination of subexpression values Examples:

Parsing the Specification

Parsing the Specification Yes, it matters! The specification is ambiguous Alas, this is not unusual with natural-language specifications We have to look for clues to the correct interpretation Schedule override suggests that the override only applies to the schedule So the expression should be false whenever the first condition (temp out of range and occupied) is false The correct interpretation is

Breaking It Down Cooling control output: Temperature above thermostat setting temperature > thermostat Office is occupied occupied Note: never occupied equals true For any boolean expression x, x equals true is exactly the same as x Current time is during normal operating hours = Current time is between normal ops start and end Current time > Normal_start AND Current time < Normal_end Override is on override

Computing with Times (and Dates) How to represent dates and times in the computer? Typically time means date and time Possibilities: A 5-tuple of values [year, month, day, hour, minute, second] A string 9/14/11 or 14 September 2011 or 2011.09.14 Number of days (and/or fractions of days, i.e., time) since some epoch Both Excel and MATLAB use this method Both have helpful functions to convert between forms Note: it doesn t much matter what the epoch is, as long as it is reasonably far in the past

Getting the Current Time/Date Excel: function NOW() returns number of days since Jan 1, 1900 A double-precision number Fraction represents the current time MATLAB: special variable now number of days since Jan 1, 0000 A double-precision number One second = 1/86400 day = 0.000011574 day NOTE: the value returned is nowhere near as accurate as its precision would suggest

Comparing Times Excel: HOUR(NOW()) returns the current hour an integer Compare to starting hour and ending hour: AND( HOUR(NOW()) > 7 [start of interval], HOUR(NOW()) < 23 [end of interval]) has to be true MATLAB: Use datevec() to convert serial to vector of values [ year month date hour min sec ] Select 4 th element, compare to start/end hours

Putting It Together Cooling unit control: currenthour: =HOUR(NOW()) duringhours: =AND(currenthour >= starthour, currenthour < endhour)

3. MATLAB Funda s

Using MATLAB As a calculator Example: calculate the volume of a cylinder Volume = r 2 h

MATLAB Script (.m ) Files You can save a sequence of commands in a file for MATLAB to play back any time These are called script files E.g., cylvol.m Invoke by typing the name of the file (without the.m) MATLAB executes the lines in the file one by one, exactly as if you had typed them Note: variables appear in the workspace Note: to suppress output, use semicolon;

What Happens When You Type Something at the Command Line MATLAB first parses what you typed, to determine what kind of thing it is: Expression Assignment expression ( var = expr... ) Evaluate the part on the RHS and change the value of variable on the LHS to the result (print if no ;) Other expression (no assignment) Evaluate the expression and change the value of ans to the result (print if no ;) Note: a variable name is an expression Word (no operators): try each of these in turn Variable name treat as expression (see above) Built-in command: clear, format, clc, etc. Name of a.m file

Path: Where MATLAB Looks for Scripts Path: a list of directories (folders) where MATLAB searches for files with names matching commands you typed Initially includes many MATLAB directories May or may not contain your current directory MATLAB warns if it is not in your path You can modify the Path: Via the Current Directory Window Via command-line: see help path Be Careful about removing folders you may have to restart MATLAB to get them back

Conditionals in MATLAB In Excel, function IF(boolexp,tvalue,fvalue) returns a value that depends on the value of boolexp In MATLAB, the basic if controls whether a command is executed: if <boolexp> <command> % executed iff <boolexp> is true end If <boolexp> evaluates to false (zero), the if does nothing!

Other forms of if-statements if <boolexp> <command1> else <command2> end <boolexp> evaluates to true (nonzero): execute <command1> <boolexp> evaluates to false (zero): execute <command2>

Using if-statements Sometimes you need to test a bunch of conditions: if score >= 90 grade = A ; else if score >= 80 grade = B ; else if score >= 70 grade = C ; else grade = E ; end end end

Using if-statements The elseif form of if-statement just makes this cleaner: if score >= 90 grade = A ; elseif score >= 80 grade = B ; elseif score >= 70 grade = C ; else grade = E ; end Only one end is required Less indentation

A Note About Formatting ALWAYS format your code properly Statements/commands inside an if (or other compound statements) should be indented: if temp > setting control = on ; end Be consistent about the amount you indent A few spaces (2-4) is best Tabs make lines too long Why this is important: Program text is the (only!) carrier of our understanding Use the built-in editor it will (usually) do the right thing

Example: Printing Info About a Number Get a number from the user. Say whether it is negative, zero or positive. Say whether it is an integer. If it is an integer, say whether it is divisible by 2, 3, or 5. Use the disp() function to produce output.

Summary

Take-aways: Boolean Logic Boolean expressions are important for capturing the logic of a problem or situation Boolean algebra is like algebra of real numbers Understanding the logic of a problem requires breaking it down into pieces Variables (input, output, intermediate...) Relationships among variables Conditions involving variables Problem specifications in English may be ambiguous Truth tables can be handy for understanding complicated expressions

Take-aways: MATLAB Scripts (m-files) allow you to re-use computations input() function allows interaction with the user Conditionals control the execution of statements 3 forms: if <boolexp> <command> end if <boolexp> <command1> else <command2> end if <boolexp1> command1> elseif <boolexp2> <command2> else <command3> end Indentation is very important for understanding code