4 Introduction to Programming in MATLAB®
4.1. Programming basics: getting started 4.1.1. Program styles First, we invite the reader to see the short manual (13 pages) MATLAB® Programming Style Guidelines by Richard Johnson1, which describes the code-writing conventions used in MATLAB®. These conventions are fairly simple: the variables must be written in lowercase and uppercase letters as follows: proportions, responseTime, etc. The constants must be written in uppercase: CONSTANT, MAX_NUMBER, etc. The names of the variables must be made explicit: subjectNum for the subject number, nSubjects for the number of subjects and not i, j or k. The names of functions are written in lowercase: responsetimecalcfunction, etc. The programs must be modularized as much as possible. A program that involves going to the Moon would comprise takeoff.m, navigate.m and land.m, with each of the .m files listing a set of MATLAB® commands. Modularity makes the code readable and allows calculations and variables that are not currently relevant to be hidden. 4.1.2. Length of programs When writing a program, the code must be optimized so that it is not too long, as the greater the number of lines of code, the greater the chance of For a color version of the code appearing in this chapter, see www.iste.co.uk/mathy/ experiments.zip. 1 http://www.datatool.com/downloads/matlab_style_guidelines.pdf.
66
Experiments and Modeling in Cognitive Science
there being an error. Another suggestion, in contrast to the first, is that a very elegant and short piece of code is sometimes not very easy to read. It is better to make a slightly longer code in order to make it more understandable. Clarity is key – not elegance. One last tip for the road: “if it ain’t broke, don’t fix it” – meaning that if the code is working, there is no point in trying to rewrite it to make it better and run the risk of breaking a program that was working fine before! 4.1.3. Emergency stop, stop a program from running If we run a program and its execution lasts longer than anticipated, we can stop it by pressing Ctrl + c. However, if this does not have the desired effect, we can still use the extreme last resort: Ctrl + Alt + Del (option + command + esc on Mac) to open the task manager. 4.1.4. Initiation Download the .m program corresponding to this chapter and open it in MATLAB®. MATLAB® contains sub-windows. Keep the default window organization. In case we accidentally move our windows, we can go back to this handy layout in the menu Desktop/Desktop Layout/Default. The code starts with an annotated heading using the % symbol. Any line of code starting with % is not read by MATLAB®. This symbol can be used extensively to annotate the code and make it clearer. We highly recommend using this technique to annotate our code as much as possible. These comments can be of great help when we (or another user) reread the program. All parts of the program (called cells) are marked by the word “code”. The result of the executed code is marked by the word “output”. The “output” section lets us to read this manual in order to pick up the reasoning by MATLAB® programming without having MATLAB® available. The programmer must give a description of his/her program in a heading, such as: % This program helps to learn how to use MATLAB® % Creation 03/03/06. Updated 08/09/12. Author: F. Mathy.
Introduction to Programming in MATLAB®
67
To learn MATLAB® step by step, we recommend testing the code cell by cell. In the menu, choose Cell/Enable cell mode. A cell starts with %% (two % symbols, followed by a space). When we place the cursor on a cell, the cell is highlighted in yellow. Click on Cell/Evaluate Current Cell in the menu to run the portion of program contained in the cell. Observe the results and then test the following cell. To run the entire file, click on Debug/Save File and Run.
4.1.5. Help Type “help commandname” to get the description of a command, for example “help clear” or “help clc”, in the Command Window and then press enter. Another way of getting help is to click on the icon in the top menu. This menu also contains a number of useful tips and demonstrations (videos, MATLAB® files, PDF files) that can be tested by typing “demo” into the Command Window.
4.1.6. Variable reset and screen reset Before starting, it is important to remove any possible residual variables and, for extra clarity, delete the content of the Command Window: Code: clear all % Clears all variables. clc % Clears the content of the Command Window. % We could have written the two commands on one line as follows: clear all, clc % The comma combines several commands. Output >>
68
Experiments and Modeling in Cognitive Science
4.1.7. Constants It is possible to manually assign a value to a constant: Code: A=1.20 B= 1.30 ; % The ‘;’ helps speed up execution of the code as it stops the results from being printed on the screen. MATLAB® stills remembers all of the calculations carried out. Output A= 1.2000 >>
Note that the two constants A and B are stored in the workspace. We can copy-paste “C = A+B” in the Command Window or pass directly to the next cell. Code: clc C =A+B Output C= 2.5000 >>
4.1.8. Formats Numbers with decimal points can sometimes be too long and unreadable. The short/long format command lets us control how they are presented on the screen. The long format command sets a long type display format, while the short format command displays rounded values, while maintaining the exact value in memory. To test this, we can check the value of pi in the short format (3.1416) with the value of the constant 3.1416, using the operator ==.
Introduction to Programming in MATLAB®
69
If the answer is 0, then, despite the short format, the exact values have indeed been kept in the memory. Code: clear all, clc A=pi; format long % sets a long type display format. A format short % sets a short type display format. A B=3.1416 A==B % tests whether the values of A and B are equal to each other. Output A= 3.141592653589793 A= 3.1416 B= 3.1416 ans = 0
4.2. Matrices Matrices are data tables on which operations can be carried out. To define a matrix, we must use the “[]” symbols in order to set the start and end limits of its elements, a space (or comma) to separate the values of a single row and the symbol “;” to separate the rows. Some functions allow particular matrices to be generated. For example, the function magic(n) creates a matrix of dimension n by n based on the magic square for which the sums of each column, each row and each diagonal are equal to each other. The function randn(m,n) randomly selects m rows of n numbers (i.e. n columns) from a normal distribution of z scores (the z scores are normally distributed, with an average of 0 and a standard deviation of 1).
70
Experiments and Modeling in Cognitive Science
Code: clear all, clc a=[7 9 11] % Here we manually write all of the values (7, 9, 11) of a. b=[7:11] % Here we attribute to b all of the values from 7 to 11, by increasing steps of 1. c=[7:2:11] % We can specify the increment, here 2. d=[7 8 9;4:6;1:3] % ‘;’ specifies the rows in matrix d. The spaces define the columns. e=[c c] % Creates matrix e by horizontal concatenation of c. f=[c;c] % Same with vertical concatenation. g=e’ % Transposes the data. % If we try g=e’’ we get the same e by double transposition Output a= 7
9
11
7
8
9
7
9
11
8 5 2
9 6 3
7
9
11
7 7
9 9
11 11
b= 10
11
7
9
c=
d= 7 4 1 e=
f=
g= 7 9 11 7 9 11 >>
11
Introduction to Programming in MATLAB®
71
4.2.1. Sum and randn commands The following program calculates simple sums and generates 1,000 random numbers using a Gaussian distribution. Finally, we shall draw a histogram of randomly chosen numbers. Code: clear all, clc a=magic(5) % Creates a 5 by 5 matrix along the principal of the magic square for which the sum of each column, each row and each diagonal, is the same. sumColumns=sum(a) % Sums the columns of matrix a. sumRows=sum(a’) % Sums the rows of a. sumDiagonal=sum(diag(a)) % Sums the elements of the main diagonal of a. c=randn(1,1000) % Randomly chooses 1 row of 1000 numbers (i.e. 1000 columns) from a normal distribution of z scores (z scores are normal distributed, mean 0 and sd 1). hist(c) % Generates a histogram of the distribution of matrix c. Output a= 17 23 4 10 11
24 1 8 15 5 7 14 16 6 13 20 22 12 19 21 3 18 25 2 9
sumColumns = 65
65
65
65
65
65
65
65
sumRows = 65
65
sumDiagonal = 65 >>
72
Experiments and Modeling in Cognitive Science
4.2.2. Manipulating matrices Some examples of simple operations that can be carried out on matrices (a data set, e.g. a table of several measurements made with several participants, is a matrix) are provided. We shall see that we can selectively extract or modify one or several elements of a matrix, in specific positions, columns or rows of the matrix. In this way, it becomes easy to calculate column or row means (average scores per subject or by item, for example) or to calculate an overall mean or one that depends on more specific criteria. EXAMPLE 4.1.– Code: %% clear all, clc a=magic(5) aTransposed=a’ a = aTransposed’ chosen1=a(6) % Creates the variable chosen1, equal to the element in sixth position (following an order by column) of matrix a.
Introduction to Programming in MATLAB®
73
chosen2=a(1:9) % Creates the matrix chosen2 from elements 1 to 9 (following an order by column) of matrix a. chosen3=a(:) % Creates the matrix chosen3 from all of the elements of matrix a gathered into a single elements column, resulting in what is called a vector. chosen4=a([1 2 9]) % Selects specific elements of a. meanByCol=mean(a) % Provides the means of each of the columns by default. grandMean=mean(mean(a)) % In order to obtain the mean of all of the elements of a, we can calculate the mean of the means of the columns. grandMeanSimpler=mean(a(:))% Or more simply by calculating the mean of the vector of a. copy_Of_a=a; line1=copy_Of_a(1,:) % Provides the first row, equivalent to copy_Of_a(1,[1:5]) col1=copy_Of_a(:,1) % Provides the first column. copy_Of_a(1,1)=0 % Assigns the value of 0 to the first element. copy_Of_a(:,1)=[] % Erases the first column. Output a= 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 aTransposed = 17 23 4 10 11 24 5 6 12 18 1 7 13 19 25 8 14 20 21 2 15 16 22 3 9 a= 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 chosen1 = 24 chosen2 = 17
23
4
10
11
24
5
6
12
74
Experiments and Modeling in Cognitive Science
chosen3 = 17 23 4 10 11 24 5 6 12 18 1 7 13 19 25 8 14 20 21 2 15 16 22 3 9 chosen4 = 17
23
12
meanByCol = 13
13
13
13
13
grandMean = 13 grandMeanSimpler = 13 line1 = 17
24
1
8
15
Introduction to Programming in MATLAB®
75
col1 = 17 23 4 10 11 copy_Of_a = 0 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 copy_Of_a = 24 1 8 15 5 7 14 16 6 13 20 22 12 19 21 3 18 25 2 9 >>
EXAMPLE 4.2.– Results from three participants Let us take the example of a test in which three participants have completed six trials each. It is very easy to automatically carry out score calculations for the modalities that we are interested in. In this way, we can get the mean scores of three participants for each trial, all of the scores from first participant alone, their mean for all of the trials or even the scores and mean for a single trial. Code: format short clear all, clc results =[1 2 3 1 2 3 % scores from the 1st participant 2 2 2 2 2 2 % scores from the 2nd participant 4 5 4 5 4 5]; % scores from the 3rd participant meanByTrial = mean(results) % scores firstParticipantOnly = results(1,:) meanFirstParticipantOnly = mean(firstParticipantOnly) firstTrialOnly = results(:,1) meanFirstTrialOnly =mean(firstTrialOnly)
76
Experiments and Modeling in Cognitive Science
Output meanByTrial = 2.3333
3.0000
3.0000
2.6667
2.6667
3.3333
firstParticipantOnly = 1
2
3
1
2
3
meanFirstParticipantOnly = 2 firstTrialOnly = 1 2 4 meanFirstTrialOnly = 2.3333 >>
4.3. Basic functions 4.3.1. Find function This function can help to automatically find the position of the elements that verify a given condition. Thus, find(matrix==1) looks for all of the elements of the matrix that equal one and gives their position. Code: clear all, results=[1 2 4
clc 2 3 1 2 3 2 2 2 2 2 5 4 5 4 5];
find(results==3) % Gives the position of all elements equal to 3, reading by column (by default) [row,colonne]=find(results==3) % Position of the elements equal to 3 by row and column. results(find(results==3)) = 3.1 % Looks for all of the scores equal to 3 and replaces them with 3.1. Note that this vectorization techniques allows us to carry out the operation without using loops.
Introduction to Programming in MATLAB®
77
Output ans = 7 16 line = 1 1 column = 3 6 results = 1.0000 2.0000 4.0000 >>
2.0000 2.0000 5.0000
3.1000 2.0000 4.0000
1.0000 2.0000 5.0000
2.0000 2.0000 4.0000
3.1000 2.0000 5.0000
4.3.2. Size and length functions Some tricks can help to assess different size parameters of a matrix. The function size() gives us the length of the matrix in columns and rows, and the function length() gives us the biggest of these two numbers. Code: clear all, clc results=[1 2 3 1 2 3 2 2 2 2 2 2 4 5 4 5 4 5]; size_results=size(results) % Gives the number of rows and columns by default. number_Of_Rows=size(results,1) % 1 is an extra parameter that specifies that we only want the number of rows of the results matrix. number_Of_Columns=size(results,2) % 2 to get the number of columns. max_size=length(results) % Gives the longest of the lengths, either the number of rows or the number of columns.
78
Experiments and Modeling in Cognitive Science
Output size_results = 3
6
number_Of_Rows = 3 number_Of_Columns = 6 max_size = 6
4.3.3. Random numbers distributed randomly: rand function In this example, we generate a random distribution uniformly distributed between 0 and 1 and then test its uniformity by calculating the means by column and by row and the grand mean. Code: clear all, clc distribution1=rand(10,4) meansByColumn_distribution1=mean(distribution1) meansByRows_distribution1=mean(distribution1’) grandMean_distribution1=mean(mean(distribution1)) Output distribution1 = 0.8308 0.5853 0.5497 0.9172 0.2858 0.7572 0.7537 0.3804 0.5678 0.0759
0.0540 0.5308 0.7792 0.9340 0.1299 0.5688 0.4694 0.0119 0.3371 0.1622
0.7943 0.3112 0.5285 0.1656 0.6020 0.2630 0.6541 0.6892 0.7482 0.4505
0.0838 0.2290 0.9133 0.1524 0.8258 0.5383 0.9961 0.0782 0.4427 0.1067
Introduction to Programming in MATLAB®
79
meansByColumn_distribution1 = 0.5704
0.3977
0.5207
0.4366
meansByRows_distribution1 = 0.4407 0.1988
0.4141
0.6927
0.5423
0.4609
0.5318
0.7183
0.2899
0.5239
grandMean_distribution1 = 0.4814 >>
4.3.4. Normally distributed random numbers: randn function In this example, we generate a normally distributed random distribution and then test its normality by calculating the means by column as well as the grand mean. Code: d2=randn(10,4) meansD2=mean(d2) grandMeanD2=mean(meansD2) Output d2 = 0.5377 1.8339 -2.2588 0.8622 0.3188 -1.3077 -0.4336 0.3426 3.5784 2.7694
-1.3499 0.6715 0.8884 3.0349 -1.2075 -1.1471 0.7254 0.7172 -1.0689 -0.0631 1.6302 -0.8095 0.7147 0.4889 -2.9443 -0.2050 1.0347 1.4384 -0.1241 0.7269 0.3252 1.4897 -0.3034 -0.7549 1.4090 0.2939 1.3703 1.4172 -0.7873 -1.7115
meansD2 = 0.6243
0.7049
grandMeanD2 = 0.3036 >>
0.3265 -0.4414
80
Experiments and Modeling in Cognitive Science
4.4. Comparison tests We can use the different relational operators: greater than >, greater than or equal to >=, less than <, less than or equal to <=, equal to == or even, different from ~= in order to compare the elements of two matrices between themselves. We note that the notation == corresponds to an equality comparison, while = corresponds to the attribution of a value to a variable. The test carried out by this type of operator compares the elements one to one, giving the value of 1 (test passed) or 0 (test failed) for their respective positions. Code: e1=[1:5] e2=[5:-1:1] differents=(e1~=e2) % Compares the 2 matrices and gives the value of 1 when their elements are different for the same position. equals=(e1==e2) greaterThanOrEqualTo=(e1>=e2) Output e1 = 1
2
3
4
5
4
3
2
1
0
1
1
1
0
0
e2 = 5
differents = 1
1
equals = 0
0
greaterThanOrEqualTo = 0 >>
0
1
1
1
Introduction to Programming in MATLAB®
81
4.5. Logical operators We can also use different logical operators in MATLAB®, such as “logical AND”, represented by “&”, the “inclusive OR” represented by “|”, the “exclusive OR” represented by “xor” and “Not equal to” represented by “~=”. The logical operators can be applied to matrices of the same size, printing for each position the result of the logical test: 1 or 0. Code: clear all, clc result1=[0 0 1 result2=xor([0 result3=[0 0 1 result4= ([0 0
1] | [0 1 0 1 1],[0 1] & [0 1 1 1]~= [0
0 1 0 1
1] % Logical OR 0 1]) % Logical exclusive OR 1] % Logical AND 0 1]) % Not equal to
Output result1 = 0
1
1
1
1
0
0
1
1
0
result2 = 0
1
result3 = 0
0
result4 = 0
1
>>
4.6. Text or character strings In programming, we sometimes have to deal with data in a text format, whether to simply store it or to use and modify it. For example, a program can save data entered by users, such as their name, age, etc.
82
Experiments and Modeling in Cognitive Science
Code: clear all, clc name=input(‘Please enter your name > ‘,’s’); % the input function asks the user to submit a response to a message shown on the screen. The parameter “s” records the subject response as a string (hence the “s”). sentence=[‘Hello ‘,name]; disp(sentence) age=input(‘Please enter your age > ‘) ; fprintf(‘You’’re young! I mean it... %d is young!\n’, age) % “%d” waits for a whole number. “\n” results in a line break. Output Please enter your name > Adam Hello Adam Please enter your age > 80 You’re young! I mean it... 80 is young! >>
4.6.1. Character strings OR character matrices Character strings are represented by a group of characters, letters, numbers or other characters that are marked by “apostrophes”. MATLAB® knows to integrate these as character strings, from which it is then possible to extract, modify or delete elements (alone or in groups). We can also concatenate several character strings together, which joins them into a new string. Code: clear all, clc myMiniAlphabet=‘abcdefg’ %Each letter is an element of a matrix of letters. myMiniAlphabet(8:9)=‘hi’ myMiniAlphabet(9)=‘‘ string1=‘Adam’,string2=‘Joe ‘ %Note that we add a space after Joe so that string1 and string2 are the same length. strings=[string1 string2] % Since string1 and string2 are matrices, they can be concatenated into a new matrix of 8 columns. strings2=[string1;string2] % This also works with 2 rows and 4 columns. string1=‘Adam’,string2=‘Joe’ strings=[string1 string2] % The new matrix has 7 columns.
Introduction to Programming in MATLAB®
Output myMiniAlphabet = abcdefg myMiniAlphabet = abcdefghi myMiniAlphabet = abcdefgh string1 = Adam string2 = Joe strings = AdamJoe strings2 = Adam Joe string1 = Adam string2 = Joe strings = AdamJoe >>
83
84
Experiments and Modeling in Cognitive Science
4.7. Cells and structures MATLAB® not only lets us create and carry out operations on matrices but also allows us to manipulate cells and structures. Cells {} can be viewed as boxes in which we can place whatever we want, whether text, numbers, matrices or even other cells. Code: clear all, clc string1=‘Adam’,string2=‘Ed’ strings_onSeparateLines={string1;string2} % the brackets {} allow us to define the content of the cell myCell={strings_onSeparateLines; [1 1000]; ‘XXX’} myCell{1,2}=‘0000’ content_of_myCell_row2_col1=myCell{2,1} first_element_of_myCell_line2_col1=myCell{2,1}(1) Output string1 = Adam string2 = Ed strings_onSeparateLines = ‘Adam’ ‘Ed’ myCell = {2x1 cell} [1x2 double] ‘XXX’ myCell = {2x1 cell} ‘0000’ [1x2 double] [] % Note: the brackets [] indicate an empty cell ‘XXX’ [] content_of_myCell_row2_col1 = 1
1000
Introduction to Programming in MATLAB®
85
first_element_of_myCell_line2_col1 = 1 >>
4.8. Control structures Although the following examples are simple, the most important goal is to try to predict the results. Code: clear all, clc for num=1:4 num2=num-1 end num=[1:4] num2=num-1 test=[1 2 4] for i=test j=i-1 end j=[] for i=test j=[j,i-1] end
4.9. Nested loops Code: k=[] for i=test for j=test k=[k,j+i] end end i=1 while i<5 i=i+1; disp(i) end
86
Experiments and Modeling in Cognitive Science
total=10 switch total case 10 disp(‘The total is ten.’) case 20 disp(‘The total is twenty.’) otherwise disp(‘I don’t know what the total is.’) end Output num2 = 0 num2 = 1 num2 = 2 num2 = 3 num = 1
2
3
4
1
2
3
2
4
num2 = 0 test = 1 j= 0 j= 1
Introduction to Programming in MATLAB®
j= 3 j= [] j= 0 j= 0
1
0
1
j= 3
k= [] k= 2 k= 2
3
2
3
5
2
3
5
3
2
3
5
3
4
2
3
5
3
4
k=
k=
k=
k= 6
87
88
Experiments and Modeling in Cognitive Science
k= 2
3
5
3
4
6
5
2
3
5
3
4
6
5
6
2
3
5
3
4
6
5
6
k=
k= 8
i= 1 2 3 4 5 total = 10 The total is ten. >>
NOTE.– In MATLAB®, it is better to avoid loops whenever possible in order to go faster. For example, we can manipulate matrices and get the same result as if we had written a loop. It is recommended to “vectorize” as much as possible to accelerate the execution of the program (and to make it more readable), as in the following example: % loops should be avoided: n=1:10 x=n*pi % is better than a loop like ‘for n=1:10 etc.’ % instead of % for n=1:10 % x(n)=n*pi % end
Introduction to Programming in MATLAB®
89
4.10. Create functions We can now think about creating our own function with MATLAB®. This function can be called from any MATLAB® program. Let us imagine that we want to create a function that can simultaneously sum and multiply two variables x1 and x2. These two variables are the input arguments of the function. A function without arguments is called a script or a procedure. A script is a command list that relies on no particular input values. A function waits for input values. Displaying a black screen for 1 s would require a script and not a function, for example. The border between the two is not always clear. We could very well write a function that displays a black screen on one of the two screens connected to a computer by sending an argument corresponding to the screen number. Code: clear all, clc x1=1; x2=1; [y1,y2]= addmult(x1,x2) % This command calls the function addmult which waits for two input arguments (x1,x2) and two output arguments [y1,y2]. Note that we named the function addmult when we saved the .m file. Its name is not explicit enough as its true function is to add and multiply up to 3 numbers. Its name should reflect its true function, but here the choice of name only reflected the idea that 1) it only refers to Chapter 5 and 2) it is pointless and absurd. Output y1 = 2 y2 = 1
In MATLAB®, open addmult in order to study its code. The code is as follows: % Chap.4 addmult (dummy function) % (Useless function created for educational purposes!) % GOAL: sum and multiply up to 3 numbers. % Within a function, ‘nargin’ and ‘nargout’ are the number % of input arguments and the number of output arguments respectively. function
90
Experiments and Modeling in Cognitive Science
[additionResult,multiplicationResult]=addmult(firstNumber,seco ndNumber,thirdNumber) %Addition switch nargin %To setup the default non-specified values case 0 firstNumber=0;secondNumber=0; thirdNumber=0; case 1 secondNumber=0; thirdNumber=0; case 2 thirdNumber=0; end additionResult=firstNumber+secondNumber+thirdNumber; %Multiplication switch nargin %To parameter the non-specified values by default case 0 firstNumber=1;secondNumber=1; thirdNumber=1; case 1 secondNumber=1; thirdNumber=1; case 2 thirdNumber=1; end multiplicationResult=firstNumber*secondNumber*thirdNumber;
% Note that variables additionResult multiplicationResult firstNumber secondNumber and thirdNumber % do not appear in the workspace. Also, because we created the % function, we were free to choose the names of the variables. For example, % instead of firstNumber, we could have chosen firstNum or 1stNum, etc. % Note that this function should be called additionandmultiplication, and % not notes2.
We note that nargin is a parameter that is testable by the function itself, which shows how many input elements have been given by the user. If the user simply types addmult, then the function has no input parameters and nargin is worth 0 automatically. If the user types addmult(23), then the function uses an input parameter (23) and nargin is worth 1. Depending on nargin, we can improve the applicability of the function to all possible cases of use. For this, we must associate sections of code: here, for example, we would need to use the neutral values of 0 for addition and 1 for multiplication in order for the function to work with only one input argument.
Introduction to Programming in MATLAB®
91
Another try: [y1Other,y2Other]= addmult (3,3,3) % The function works with 3 input arguments. Output y1Other = 9 y2Other = 27 >>
If addmult had only one output argument, then we would have written: y = addmult(x1,x2). CAUTION.– a good programmer is aware of the existing functions available! The function addmult is not very powerful, as it is limited to three input arguments. Why then create a function that, moreover, inexplicably mixes addition and multiplication? We would be better off using the following two prebuilt functions: Code: clear all, clc y1 = sum([1 1]) y2=prod([1 1]) Output y1 = 2 y2 = 1 >>
92
Experiments and Modeling in Cognitive Science
4.11. Summary The following is a summary program that lets us simulate the random draw of x samples by n subjects, associate a randomly selected IQ to the x × n measures, automatically correct scores, do statistics and so on. In MATLAB®, open the script simuqi.m and run it using the “Play” button (green triangle); type simuqi into the Command Window or insert the command simuqi in another script.m. These are the three ways of calling a script. Code: %% IQ simulation % Generate x samples of n scores and eventually simulate the central limit theorem. % IQs are randomly drawn from a normal distribution of mean 100 and standard % deviation 15. clear all, clc MEAN_IQ=100; STD_IQ=15; nSamples=input(‘Please enter the number of samples > ‘) ; nSubjects=input(‘Please enter the number of subjects per sample > ‘) ; data=randn(nSubjects,nSamples); data=MEAN_IQ+ data*STD_IQ; sampleMeans=mean(data); iq_freq_classes=hist(sampleMeans,9) % We request the numbers of the histogram for 9 classes, without drawing the histogram; the command hist(sampleMeans, 9) (without iq_freq_classes= the previous one) lets us draw the histogram. standardError_predicted=STD_IQ/sqrt(nSubjects) standardError_real=std(sampleMeans) Output Please enter the number of samples > 50 Please enter the number of subjects per sample > 100 iq_freq_classes = 3
1
9
12
13
standardError_predicted = 1.5000 standardError_real = 1.5629
6
3
2
1
Introduction to Programming in MATLAB®
93
Going further: run the program several times with increasing values for nSamples and nSubjects in order to verify the central limit theorem. The dispersion should approach: standard error = 15/root(nSubjects), with 15 here being the standard deviation. 4.12. Programming tips in MATLAB® – We want to define the virtual areas of an image. The image size is 210 pixels. How can we overlay a grid of six vertical fields at equidistance? The solution for the width is: Code: linspace(0,210,7) Output ans = 0
35
70 105 140 175 210
We used seven terminals in order to get six gaps of 35. – To get a list of all of the variables, we use the command: Code: whos
If we want this list to become a variable, then we can save the content of whos: Code: maVariable = whos
This allows us to carry out all sorts of calculations on the list of variables, for example the total amount of memory space needed on a computer for all of the variables.
94
Experiments and Modeling in Cognitive Science
If we already have several variables in our program, then we might be struggling to find a new name for our variable. A practical function is genvarname, which helps us to find a suitable name that is not already used or that is not the name of a pre-existing MATLAB® function. – To copy identical numbers, for example if we want to code data according to experimental conditions, then we can use repmat: >> A = [1 2] A= 1
2
>> B =repmat(A, [10 1]) B= 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
>> B=B(:) B= 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2
Introduction to Programming in MATLAB®
95
– To make comments over several lines: %{ ... %} – To get a list of installed modules: ver – To get a list of functions related to adding: lookfor Example 4.3.– lookfor sum AlphaSum kPsychAssumeTextureNormalized SumAll update position hypot trace cumsum sum summer uiresume uiwait hdf5 dbcont grpstats nansum ranksum >>
- sumImage=AlphaSum(image1, image2) - rc = kPsychAssumeTextureNormalized - [s] = SumAll(in) - UNTITLED1 Summary of this function goes here. - Robust computation of the square root of the sum of squares. - Sum of diagonal elements. - Cumulative sum of elements. - Sum of elements. - Shades of green and yellow colormap. - Resume execution of blocked M-file. - Block execution and wait for resume. - Summary of MATLAB® HDF5 capabilities. - Resume execution. - Summary statistics by group. - Sum, ignoring NaNs. - Wilcoxon rank sum test for equal medians.
– As recommended above, loops must be avoided to accelerate the execution of the program (and to make it more readable): %loops should be avoided: n=1:10 x=n*pi %is better than a loop like ‘for n=1:10 etc.’ %instead of % for n=1:10 % x(n)=n*pi % end
– Think of the pre-allocated space needed for a variable with zero, one or NaN functions for: %arrays should be preallocated %x=zeros(1,10); n=1:10 x=n*pi