1 / 54

Day 3 review

Day 3 review. Logic and Flow control If Switch While Let's fire up Matlab. Day 4 plan. a couple of exercises on flow control. Tables. Functions. Exercise. Write a program that asks user for a password, until user gets it right. use “strcmp” strcmp(string1,string2).

sbess
Télécharger la présentation

Day 3 review

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Day 3 review • Logic and Flow control • If • Switch • While • Let's fire up Matlab.

  2. Day 4 plan a couple of exercises on flow control. Tables. Functions.

  3. Exercise Write a program that asks user for a password, until user gets it right. use “strcmp” strcmp(string1,string2)

  4. strcmp: string comparison Strings are not Matrices, nor are they mathematical expressions so we cannot do: if (name=='alejo') %it works only if the two are the same length... we use strcmp to compare two strings. strcmp(name,'alejo') which returns 1 if true and zero if false. (it also allows you to find multiple instances of a string in a cell array).

  5. pwdverify.m pwd='secret'; attempt=input('what''s the pwd?','s'); while ~strcmp(pwd,attempt) clear attempt; attempt=input('invalid pwd, please try again. ','s'); end;

  6. the "find" command A very useful command! It can save you some time wasted on for loops… Allows you to efficiently look for a value inside a matrix. For instance, do you want to find all the RTs in your data file that are below 150 ms?

  7. find FINDS a specific value in an array (or matrix) and returns the indeces in which it is located SYNTAX:indeces = find(expression); returns indeces for which expression is true.

  8. the "find" command RT might be a 10000 rows variable with RT values. Let's imagine: RT = [ 50 100 250 350 85 450 550 650 79 120 200 4000]; then badRTIndeces = find(RT <150) and badRTs=RT(find(RT < 150)); % or badRTs=RT(badRTIndeces) How would you change this code to find RTs<150 and RTs>1000? find( (RT < 150) | (RT > 1000)) %% You can also OMIT the find command Try: badRT=RT(RT<150) And badRTIndeces=(RT<150)

  9. the "find" command How would you change this code to find RTs<150 and RTs>1000? 1 . find( (RT < 150) | (RT > 1000)) 2. find( (RT < 150) & (RT > 1000)) % | is logical OR % & is logical AND

  10. the "find" command Alter the code so as to obtain a new vector of RTs that has NO invalid RTs WITHOUT using a for loop. • badRT=find(RT<150 | RT > 1000) • TrimRT=RT • TrimRT(badRT)=[] Or TrimRT=RT(RT>=150 & RT <= 1000)

  11. the “isempty" command When FIND does not find ANY indeces, it returns an empty matrix. TRY: A=[1 2 3;1 4 8]; B=find(A==1) C=find(A==1000) ISEMPTY(X) returns TRUE if the matrix X is empty. TRY: if isempty(C)'it worked' else 'im screwed' end

  12. Exercise Write a program that • finds all RTs smaller than 150 and larger than 1000 • calculates the average RT of the “valid” RTs • reports the proportion of rejected RTs For the data, create the following vector: data=rand(1000,1) .* 1100; USING A FOR LOOP!!

  13. Exercise With a for loop: sz=size(data); counter=0; mean=0; for i=1:sz(1) if data(i) > 150 if data (i)<1000 mean=mean+data(i); else counter=counter+1; end; else counter=counter+1; end end; mean=mean/(sz(1)-counter); rejected=counter/sz(1);

  14. Exercise Write a program that • finds all RTs smaller than 150 and larger than 1000 • calculates the average RT of the “valid” RTs • reports the proportion of rejected RTs For the data, create the following vector: data=rand(1000,1) .* 1100; WITHOUT A FOR LOOP

  15. Exercise Without a for loop: data=rand(1000,1) .* 1100; badRT=find(RT<150 | RT > 1000); TrimRT=RT; if ~isempty(badRT) %although technically... TrimRT(badRT)=[]; meanRT=mean(TrimRT); else meanRT=mean(data); end proportionReject=(1-length(TrimRT))/length(data);

  16. Exercise (2) Create a variable called Trial that has the numbers 1 to 1000 in increments of 1 (in one column) Create a variable called Condition that has the numbers 0 and 1, alternating, 1000 times (in one column). NOW WE HAVE DATA TO STORE!! Trial=[1:1000]'; Condition=mod(Trial,2);

  17. TABLES Are super useful and convenient ways of using Matlab to handle “tabular” (i.e, named) data and do many of the things you usually do with tables (like sorting) but also the regular things you do with matrices (like extracting subsets of data, etc…) To create a table use functions: table array2table cell2table struct2table Let's try table first.

  18. TABLES DataTable=table(Trial,Condition); DataTable=[DataTable table(data)]; %concatenates Check out your work space. You can try sorting by condition SortedData=sortrows(DataTable,'Condition');

  19. TABLES You can access a subset of values in the DataTable For instance, get all the RTs after the first 5 trials, with the corresponding condition SubsetData=DataTable(6:end,{'Condition','data'}) Compare to SubData=DataTable{6:end,{'Condition','data'}} Here { } allows us to access values inside and turn it into a matrix. ( ) keeps the table as a table.

  20. TABLES You can also refer to columns by their name using a “.” and you will get to use the values inside that column. DataTable.data (equivalent to DataTable{:,'data'} So you can try doing things like finding all RTs larger than 150 in condition 0 rows = (DataTable.data>150 & DataTable.Condition==0) goodtrial=DataTable.Trial(rows) goodmeanRT=mean(DataTable.data(rows))

  21. SAVING TABLES writetable(T) So try: writetable(DataTable) Open 'DataTable.txt' You can try different “delimiters” (default is , ) writetable(DataTable,'Delimiter', ' ') (space delimiter)

  22. RowNames Sometimes, we can have Unique Identifiers for each row, for instance, SubjectID (but there can only be one row per identifier). We can create a special column with SubjecID as the RowName. And we will have to remember to save the RowName to the file, if we will be needing it! Example: SubID = {'ss01';'ss03';'ss22';'ss15';'sstry'}; Age = [38;43;38;40;49]; Height = [71;69;64;67;64]; Weight = [176;163;131;133;119]; MeanRT = [500; 505; 600; 671; 0]; T = table(Age,Height,Weight,MeanRT,'RowNames',SubID) writetable(T,'mySumData.dat','WriteRowNames',true) Open 'mySumData.dat' What would happen if you did not specify 'WriteRowNames'?

  23. Read Tables readtable allows you to “import” the data in a file that is organized as a series of columns (like a data file). Table = readtable(filename) So try: NewTable=readtable('mySumData.dat') If you add ,'ReadRowNames',true it will add RowNames to the file And if there are NO NAMES for the columns, you should say so: Readtable('mySumData.dat','ReadVariableNames',false) Each column will be called in order Var1 Var2 Var3…

  24. Read Tables It Works with Excel Tables And you can also directly access a specific range in the spreadsheet with the command 'Range' T = readtable('summary.xls', 'Range','C2:E6',... 'ReadVariableNames',false) Will read columns C D and E and rows 2, 3, 4, 5 and 6 Other nice things: ('TreatAsEmpty', 'WHATEVERSTRING') saved as NaN Btw, missing values (two successive operators) are treated as NaN for numbers and '' for strings

  25. Exercise/homework Write a program that asks a user for a new password which must abide by the following rules: 1.Length must be at least 6 characters. 2.Must have at least one digit. 3.Must have at least one Upper case and one Lower case letters. If user enters valid password, say "Ok, password valid" If user enters a password without a digit, say "you forgot to include at least one digit" If passwords does not have at least one Upper and one lower case letter, say "you forgot to include at least one upper case and one lower case letter“ Create a Table and write it to a file in memory with the following information “AttemptNumber” “AttemptedPassword”, and “ErrorCode”

  26. Exercise/Homework What flow control statements should we use and for which instructions? - Since we don't know how many times it will take for the user to come up with a good password : "while" - To check on the appropriateness of a possible pwd: "if" - Since there are three types of feedback: "switch“ (maybe)

  27. Exercise/Homework UTpwd.m %This program asks for a new password from the user %the password must have at least one digit, one lower caps %and one upper caps letter and be at least 6 characters long. %Known bugs: program crashes if input is not %Programmed by Alejandro Lleras %Last updated: September 7, 2006 invalid=true; while (invalid) end; 'Success. Thanks!'

  28. Exercise/Homework UTpwd.m %This program asks for a new password from the user %the password must have at least one digit, one lower caps %and one upper caps letter and be at least 6 characters long. %Known bugs: program crashes if input is not %Programmed by Alejandro Lleras %Last updated: September 7, 2006 invalid=true; while (invalid) pwd = input('Please enter an uptight password: ','s'); pwd_sz = length(pwd); if (pwd_sz > 6) %if it passes the size test then we check for… end; end; 'Success. Thanks!'

  29. Exercise/Homework invalid=true; while (invalid) pwd = input('Please enter an uptight password: ', 's'); pwd_sz = length(pwd); if (pwd_sz > 6) %if it passes the size test then we check for… if ("pwd has a number") %if it also passes the number test then… end; end; end; 'Success. Thanks!'

  30. Exercise/Homework invalid=true; while (invalid) pwd = input('Please enter an uptight password: ); pwd_sz = length(pwd); if (pwd_sz > 6) %if it passes the size test then we check for… if ("pwd has a number") %if it also passes the number test then… if ("pwd has a lowercase") if ("pwd has an uppercase ") invalid=false; %break would work too end; end; end; end; end; 'Success. Thanks!'

  31. Functions - can take input (passing variables) - can return outputs. • variables are internal. • NAME OF M-FILE AND FUNCTION HAVE TO BE THE SAME.

  32. Functions Example: - First thing: we have to identify the script as a function, with the keyword function At the top of the m file we type: function output = nameoffunction(passvar1,passvar2…); Then you can write your program, like a normal script.

  33. function output = nameoffunction(passvar1,passvar2,…); output will hold the value that will be returned by the function (if any). Outputs can be of any type. You can give it any name you want. passvar1, passvar2… are the passing variables (aka arguments) for the function. You can pass as many arguments as you'd like.

  34. Passing variables These are values that constrain the execution of the function. For example: function DrawSquare(x_left,y_top,size); {x_left,y_top, size} will be the values you'll probably need to draw a square.

  35. Passing variables In your code, you will use the passing variables by referring to them by the name you specified on the function statement. When you call the function in your program, you simply specify values, or use other variables to PASS the values.

  36. Example: Take the function: function rdow = scramble(word); %these are your help lines %that you use to explain your code name_sz = length(word); neworder = randperm(name_sz); rdow=word(neworder); %% That's it!! SAVE IT AS scramble.m

  37. Example: Now go to the command prompt and use your new function: > myname = 'alejo'; > newname = scramble(myname); here, myname is passing the value 'alejo' to the function 'scramble'. Note, we did NOT use 'word'. word is internal to the function.

  38. Example: Now try: > scramble(myname); %don't have to assign the result to any variables. > scramble('alejo'); %don't need a variable to pass the value.

  39. Example: Now try: > scramble alejo > scramble myname > WHEN INPUT IS STRING, Matlab allows you to call the function without quotes and without parenthesis.

  40. OTHER types of variables GLOBAL variables: If you want more than one function to share a single copy of a variable, declare it as global. You need to do so on every function using the variable. > function h = falling(t); > global GRAVITY >function headache = hangover(num_drinks,num_heartbreaks); >global GRAVITY

  41. OTHER types of variables GLOBAL variables: - If you want the workspace to see this variable, also declare it on the command line (or script). - Declaration has to happen BEFORE you use the variable. - CAPITALIZE global variables…

  42. OTHER types of variables GLOBAL variables: - ARE NOT ERASED from memory when MATLAB exits the function… so values are retained from one use to the next. - AYE!!! memory!!

  43. AYE!!! memory!! Modify scramble as such: function rdow = scramble(word); global GRAVITY GRAVITY = 9.81; t=GRAVITY.*3; rdow = shuffle(word); RUN IT. WORKSPACE???

  44. AYE!!! memory!! Now type: > GRAVITY WHAT HAPPENS??? > global GRAVITY WHAT's on your workspace? > GRAVITY

  45. AYE!!! MEMORY!!! SO BEWARE OF MEMORY USE with GLOBAL variables. GRAVITY exists! Even if you have no evidence that it does! And it can weigh you memory! (hah!)

  46. Persistent Variables If you want a function to keep accessing a variable, every time you run it, declare the variable as persistent. In other words, Matlab will NOT erase it upon exiting the function, so it will be able to access it again.

  47. Persistent Variables Only the function in which you declare a persistent variable can use it (unlike GLOBAL variables). Only work for functions. To use: > persistent variable_name > clear functionname %to eraseclear all editing the function

  48. Persistent Variables Initializing a persistent variable: > function runSum(inc) > persistent TOTSUM > > if isempty(TOTSUM) TOTSUM = 0; > end > TOTSUM = TOTSUM + inc;

  49. let's explore Call the function a few times. > runSum(1) > runSum(34) > runSum(100) > WHAT's going on in your workspace?

  50. let's explore Declare on your workspace: > global TOTSUM > runSum(1009) > TOTSUM

More Related