Lesson 4: Basic Algorithm Tools If, While Do For Loop, Else, Switch Case Today's Lesson Basic Algorithm Tools What's an algorithm? What good are they? Simple Functions Logic Operators Loops (while, for) Logic (if/then, switch/case) Okay, so what's an Algorithm? Informally: A set of steps to get you from State A to State B. Formally: A type of effective method in which a list of well-defined instructions for completing a task will, when given an initial state, proceed through a well-defined series of successive states, eventually terminating in an end-state. Informal Example: Read in my Data, Load the middle 10 columns of data, Save those columns to a file (.csv, .tsv,.txt) So what Good is an Algorithm? All programs are Algorithms. Sketching out an informal Algorithm will help you write actual programs. Breaking your thinking into steps can assist in checking your program for errors. What do I need to start? A good mental image of what you want to accomplish. What is the input? (i.e. your data) What output do you want? (i.e. a subset of your data) Some basic tools: Very simple Matlab formulas Conditional Operators Loops Conditional statements Playing With Conditional Operators In your command window, type: A = 34 B = 76 C = ‘hello’ D = ‘Hello’ Now, try these examples: A<B A>B A == B A ~= B isequal(C,D) ~false true & false The Situation • Just finished an experiment – Subject walked a line while responding to stimuli – Known data, Age, Accuracy, RT, On Balance • Need for all subjects prior to losing their balance. – Their grouping, based on Reaction Time – Their grade, based on their accuracy Loops Why use loops? Automatically repeat instructions for a large data set While Loops: Repeat instructions while a particular condition is true. For Loops: Repeat instructions for a particular number of times. For i=1:length(infiles) Is i < length(infiles)? Execute Loop Code i=i+1 Exit Loop Move on in code. For Loop while(condition) Is counter < length & person on balance? Execute Loop Instructions Counter = counter + 1 Exit Loop Move on in code While Loops If (condition) Else If age < 65 ageClass = 'Young' ageClass = 'Elder' If (condition) Else If(condition) Else If RTAvg <= 350 Group = 1 Else if RTAvg <= 600 Group = 2 Group = 3 If-Then-Else Block If(condition) elseif(condition)...else If Accuracy < 50 Grade = 0 ElseIf Accuracy < 60 Grade = 1 ElseIf Accuracy < 70 Grade = 2 Grade = 3 If – ElseIf Block Switch and Case %Set an arm length value dependent on subject age switch subjectAge case 10 armLength = 30; case 15 armLength = 35; case 20 armLength = 40; otherwise armLength = 42; end Switch (variable) case...otherwise switch Age case 10 armLength = 30 case 15 armLength = 35 case 20 armLength = 40 otherwise armLength = 42