Introduction to Programming in MATLAB Intro MATLAB Peer
Introduction to Programming in MATLAB Intro. MATLAB Peer Instruction Lecture Slides by Dr. Cynthia Lee, UCSD is licensed under a Creative Commons Attribution-Non. Commercial-Share. Alike 3. 0 Unported License. Based on a work at www. peerinstruction 4 cs. org. 1
Conditional Statements • Note: display(arg) prints the value of arg back to you 2
Conditional Statements function [ ] = Print. Age. Info( age ) if (age >= 16) display('Can end if (age >= 18) display('Can end if (age >= 21) display('Can end if (age >= 65) display('Can end drive'); vote'); drink'); collect Social Security'); end How many strings are printed when we type Print. Age. Info(30) in the Command Window? (a) 0 (b) 1 (c) 2 (d) 3 (e) 4 3
Conditional Statements function [ ] = Print. Age. Info( age ) if (age >= 16) display('Can drive'); elseif (age >= 18) display('Can vote'); elseif (age >= 21) display('Can drink'); elseif (age >= 65) display('Can collect Social Security'); end When we type Print. Age. Info(30) in the Command Window, is ‘Can vote’ printed? (a) yes (b) no (c) I don’t know/Other 4
Conditional Statements function [ ] = Hello. Puzzle( x ) if (x >= 3) display(‘Hello!'); else display(‘Hello!’); if (x > 1) display(‘Hello!'); end end How many strings are printed when we type Hello. Puzzule(5) in the Command Window? (a) 0 (b) 1 (c) 2 (d) 3 (e) I don’t know/Other 5
Review/check-up You get a job at the DMV and your boss asks you to write a function Is. Driving. Age as follows: (1) takes one argument, a number giving the age in years, and (2) returns true if the age is 16 or more and false otherwise. Which of the following codes fulfills this request? function [] =Is. Driving. Age(age) function [y] =Is. Driving. Age(age) if (age >= 16) display(‘true’); else y = true; display(‘false’); else end display(‘false’); A end y = false; function [y] =Is. Driving. Age(age) end B end if (age >= 16) y = true; Any of these is fine, it is just personal preference. else y = false; end C D 6
- Slides: 6