Code and Output

Code 7.1.1:

clear all

a = 'a'
b = 1
c = 1.00
d = round(c)
e = single(d)
f = uint8(e)
g = true
h = false
i = 'abcde'
j = 'ABCDE'
k = i - j
l = int8(k)

whos

Output 7.1.1:

a =
a
b =
     1
c =
     1
d =
     1
e =
     1
f =
    1
g =
     1
h =
     0
i =
abcde
j =
ABCDE
k =
    32    32    32    32    32
l =
   32   32   32   32   32

  Name      Size            Bytes  Class      Attributes

  a         1x1                 2  char                
  b         1x1                 8  double              
  c         1x1                 8  double              
  d         1x1                 8  double              
  e         1x1                 4  single              
  f         1x1                 1  uint8               
  g         1x1                 1  logical             
  h         1x1                 1  logical             
  i         1x5                10  char                 
  j         1x5                10  char                
  k         1x5                40  double              
  l         1x5                 5  int8                

Code 7.1.2:

help datatypes

Output 7.1.2:

  Data types and structures.

Data types (classes)
  double          - Convert to double precision.
  logical         - Convert numeric values to logical.
  cell            - Create cell array.
  struct          - Create or convert to structure array.
  single          - Convert to single precision.
  uint8           - Convert to unsigned 8-bit integer.
  uint16          - Convert to unsigned 16-bit integer.
  uint32          - Convert to unsigned 32-bit integer.
  uint64          - Convert to unsigned 64-bit integer.
  int8            - Convert to signed 8-bit integer.
  int16           - Convert to signed 16-bit integer.
  int32           - Convert to signed 32-bit integer.
  int64           - Convert to signed 64-bit integer.   

Code 7.1.3:

double_value = 2
class(double_value)

single_value = single(double_value)
class(single_value)

Output 7.1.3:

double_value =
2
ans =
double

single_value =
2
ans =
single

Code 7.1.4:

sum = 0
while sum ~= 1
    fprintf('Not there yet...\n')
    sum = sum + 1/99;
    fprintf('%f\n',sum)
end

Code 7.1.5:

sum = 0
while sum ~= 1
    fprintf('Not there yet...\n')
    sum = sum + 1/99;
    fprintf('%17.15f\n',sum)
    if sum > 1.05
        break
    end
end

Output 7.1.5:

[... 95 lines of output omitted]
Not there yet...
0.969696969696968
Not there yet...
0.979797979797978
Not there yet...
0.989898989898988
Not there yet...
0.999999999999998
Not there yet...
1.010101010101008
Not there yet...
1.020202020202018
Not there yet...
1.030303030303028
Not there yet...
1.040404040404039
Not there yet...
1.050505050505049
[And so on, ad infinitum...]

7.2 Converting Characters to Numbers and Vice Versa

Code 7.2.1:

de = double('!')
dq = double('Let''s go!')

Output 7.2.1:

de =
33
dq =
76   101   116    39   115    32   103   111    33

Code 7.2.2:

de_lettered = char(de)
dq_lettered = char(dq)

Output 7.2.2:

de_lettered =
!
dq_lettered =
Let's go!

Code 7.2.3:

for i = 1:8
for j = (i:11:91)
    thiscode = j+31;
    fprintf('%5.0f %s',thiscode,char(thiscode));
end
fprintf('\n');
end

Output 7.2.3:

   32     43 +   54 6   65 A   76 L   87 W   98 b  109 m  120 x
33 !   44 ,   55 7   66 B   77 M   88 X   99 c  110 n  121 y
34 "   45 -   56 8   67 C   78 N   89 Y  100 d  111 o  122 z
35 #   46 .   57 9   68 D   79 O   90 Z  101 e  112 p
36 $   47 /   58 :   69 E   80 P   91 [  102 f  113 q
37 %   48 0   59 ;   70 F   81 Q   92 \  103 g  114 r
38 &   49 1   60 <   71 G   82 R   93 ]  104 h  115 s
39 '   50 2   61 =   72 H   83 S   94 ^  105 i  116 t

Code 7.2.4:

num1 = 123.456
str1 = '567.890'
strOfNum1 = num2str(num1)
numOfStr1 = str2num(str1)
whos

Output 7.2.4:

num1 =
123.4560
str1 =
567.890
strOfNum1 =
123.456
numOfStr1 =
567.8900
Name           Size            Bytes  Class     Attributes

num1           1x1                 8  double
numOfStr1      1x1                 8  double
str1           1x7                14  char
strOfNum1      1x7                14  char         

Code 7.2.5:

fave = 7;
disp('Your favorite number is ' fave);

Output 7.2.5:

??? Error: File: Number_To_String_01.m Line: 4 Column: 31
Missing MATLAB operator.

Code 7.2.6:

fave = 7;
disp(['Your favorite number is ' int2str(fave) '.']);
disp(strcat('Your favorite number is ', int2str(fave), '.'));

Output 7.2.6:

Your favorite number is 7.
Your favorite number is7.

Code 7.2.7:

disp(num2str([1:5].^2,'%d\t'))
disp(num2str([1:5].^.5,'%g\t'))

Output 7.2.7:

1     4   9   16   25
1     1.41421  1.73205        2  2.23607

Code 7.3.1:

MyMatrix1 = [
'oranges'
'bananas']

MyMatrix2 = [
  'apples'
  'oranges']

Output 7.3.1:

MyMatrix1 =
oranges
bananas

Error using vertcat
Dimensions of matrices being concatenated are not consistent.

Code 7.3.2:

MyCells = {
'apples'
'oranges'}
for i = 1:2
 thisword = MyCells{i}
end

whos

Output 7.3.2:

MyCells =
'apples'
'oranges'
thisword =
apples
thisword =
oranges
Name          Size            Bytes  Class     Attributes

MyCells       2x1               250  cell
i             1x1                 8  double
thisword      1x7                14  char     

Code 7.3.3:

c = {[ 1 2 3]
[4 5 6 7]
['rats mice']; [' voles']
[1 3]}
c_second_row = c{2}
c_second_row_middle_numbers = c{2}(2:3)
c_third_row = c{3}
c_third_row_second_character = c{3}(2)

Output 7.3.3:

c =
[1x3 double]
[1x4 double]
'rats mice'
' voles'   
[1x2 double]
c_second_row =
 4     5     6     7
c_second_row_middle_numbers =
 5     6
c_third_row =
rats mice
c_third_row_second_character =
a

Code 7.3.4:

Names_and_Numbers = {
'Bob' [90 95]
'Jane' 100
}
Name1 = cell2mat(Names_and_Numbers(1,1))
Numbers1 = cell2mat(Names_and_Numbers(1,2))

Output 7.3.4:

Names_and_Numbers =
'Bob'     [1x2 double]
'Jane'    [       100]
Name1 =
Bob
Numbers1 =
90    95

Code 7.3.5:

for produce = {'Apple' 'Artichoke' 'Banana' 'Broccoli'...
'Cherry' 'Cauliflower'}
productName = char(produce); % convert cell to char
switch productName
case {'Apple' 'Banana' 'Cherry'}
fprintf('%s is a fruit.\n', productName);
case {'Artichoke' 'Broccoli' 'Cauliflower'}
fprintf('%s is a vegetable.\n', productName);
end
end

Output 7.3.5:

Apple is a fruit.
Artichoke is a vegetable.
Banana is a fruit.
Broccoli is a vegetable.
Cherry is a fruit.
Cauliflower is a vegetable.

Code 7.3.6:

% Days_In_A_Month
month = input('Type in the month: ','s');
year = input('Type in the year (4 digits): ');
switch month
    % Thirty days hath September,
    % April, June, and November...
    case {'September' 'April' 'June' 'November'}
        no_of_days = 30;
    case 'February'
        if rem(year, 4) == 0 & ...
                (rem(year, 100) ~= 0 | rem(year, 400) == 0)
            no_of_days = 29;
        else
            no_of_days = 28;
        end
    % All the rest have thirty-one
    otherwise
        no_of_days = 31;
end
fprintf('%s %d has %d days.\n', month, year, no_of_days);

Output 7.3.6:

Type in the month: February
Type in the year (4 digits): 2012
February 2012 has 29 days.

Code 7.4.1:

Names_and_Numbers(1).name = 'Bob';
Names_and_Numbers(2).name = 'Jane';
Names_and_Numbers(1).RTs =[90 95];
Names_and_Numbers(2).RTs = [100];
Names_and_Numbers

Output 7.4.1:

Names_and_Numbers =
1x2 struct array with fields:
    name
    RTs

Code 7.4.2:

trials = [
1 2 200
2 2 300
1 1 400
]

Output 7.4.2:

trials =
1     2   200
2     2   300
1     1   400

Code 7.4.3:

%Initialize struct fields and values
trial(1).side = 'left';
trial(1).brightness = 'bright';
trial(1).duration = 200;

trial(2).side = 'right';
trial(2).brightness = 'bright';
trial(2).duration = 200;

trial(3).side = 'left';
trial(3).brightness = 'dim';
trial(3).duration = 400;

%Examine struct values
trial
t3 = trial(3)
t2_side = trial(2).side
t_durations = [trial(:).duration]

Output 7.4.3:

trial =
1x3 struct array with fields:
    side
    brightness
    duration
t3 =
          side: 'left'
    brightness: 'dim'
      duration: 400
t2_side =
right
t_durations =
   200   200   400

Code 7.4.4:

subject(1).RTs = [
500 400 350
450 375 325
];
subject(1).errors = [
10 8 6
4 3 2
];
subject(2).RTs = [
600 500 450
550 475 425
500 425 400
];
subject(2).errors = [
10 8 6
4 3 2
3 2 1
] ;
subject(2).debrief = true;
subject(2).comment = 'That was a really cool experiment!';

subject

s1 = subject(1)
s2 = subject(2)

Output 7.4.4:

subject =
1x2 struct array with fields:
    RTs
    errors
    debrief
    comment
s1 =
        RTs: [2x3 double]
     errors: [2x3 double]
    debrief: []
    comment: []
s2 =
        RTs: [3x3 double]
     errors: [3x3 double]
    debrief: 1
    comment: [1x34 char]

Code 7.4.5:

outfilename = 'RTdata.txt';
outfile = fopen(outfilename,'wt');
% print header line
fprintf(outfile,'sub\tRT\tErrors\n');
% print data table
for subjectnumber = 1:2
     fprintf(outfile,'%3d\t%5.1f\t%3.1f\n',subjectnumber,...
     mean(subject(subjectnumber).RTs(:)),...
     mean(subject(subjectnumber).errors(:)));
end
type('RTdata.txt')

Output 7.4.5:

sub   RT   Errors
1   400.0    5.5
2   480.6    4.3

Code 7.4.6:

% dealexample.m
clear
clc
% Initializing fields of a struct
[mystruct(1:8).initiallyZeroVariable] = deal(0);
[mystruct.initiallyEmpty] = deal([]);
[mystruct.random] = ...
    deal(randi(10),randi(10),randi(10),randi(10),...
         randi(10),randi(10),randi(10),randi(10));
[mystruct.integers] = deal(8,7,6,5,4,3,2,1);
ms_1 = mystruct(1)
ms_2 = mystruct(2)
ms_8 = mystruct(8)

Output 7.4.6:

ms_1 =
initiallyZeroVariable: 0
       initiallyEmpty: []
               random: 9
             integers: 8
ms_2 =
initiallyZeroVariable: 0
       initiallyEmpty: []
               random: 7
             integers: 7
ms_8 =
initiallyZeroVariable: 0
       initiallyEmpty: []
               random: 4
             integers: 1

Code 7.4.7:

% Reading field of struct to cell array using deal
[TheIntegersCellArray{1:length(mystruct)}] = ...
     deal(mystruct(:).integers)
% Converting cell array to matrix using cell2mat
TheIntegerMatrix = cell2mat(TheIntegersCellArray)

Output 7.4.7:

TheIntegersCellArray =
[8]    [7]    [6]    [5]    [4]    [3]    [2]    [1]
TheIntegerMatrix =
 8     7     6     5     4     3     2     1

Code 7.4.8:

dir
mydir = dir
fprintf('\nFiles found:\n');
for i = 1:length(mydir)
    fname = mydir(i).name;
    if strfind(fname,'step2.mat')
         fprintf(...
         'File named ''%s'' will be processed for step 3.\n',fname);
    end
end

Output 7.4.8:

.                           my_dlm_data.txt
..                          mydata.txt
Apps                        mydata1.txt
DatafromStep1.mat           myexpt_EF_062913_step2.mat
Days_In_A_Month.m           precisionexample.m
DirectoryExample.m          readRTdata.m
SimonDemo.m                 rtdata.txt
SimonDemo2.m                sampledata.txt
SimonDemo3.m                simondata.mat
booleanloopexample.m        syncme.m
daysinMonth.m
garbage.m

mydir =
22x1 struct array with fields:
    name
    date
    bytes
    isdir
    datenum

Files found:
File named 'myexpt_EF_062913_step2.mat' will be processed for step 3.

Code 7.4.9:

thisRT = subject(2).block(3).trials(4).RT;
thisRT = subject(5).block(4).trials(2).RT;

% Analysis loop
for subcount = 1:5
    for blockcount = 1:4
        for trials = 1:10
            thisRT =  subject(subcount).block(blockcount).trials(trialcount).RT;
            % further analysis of thisRT...
        end
    end
    % Output for this subject would go here
end

Code 7.5.1:

'apples' == 'oranges'

apples_to_oranges = strcmp('apples', 'oranges')
apples_to_apples = strcmp('apples','apples')
apples_to_APPLES = strcmp('apples', 'APPLES')
apples_to_APPLES_ignoring_case =  strcmpi('apples','APPLES')

Output 7.5.1:

Error using  ==
Matrix dimensions must agree.

apples_to_oranges =
     0
apples_to_apples =
     1
apples_to_APPLES =
     0
apples_to_APPLES_ignoring_case =
     1

Code 7.5.2:

s = ['How much wood could a wood chuck chuck'...
' if a wood chuck could chuck wood?'];
all_wood_in_s = strfind(s,'wood')
all_could_in_s = strfind(s,'could')
all_should_in_s = strfind(s,'should')
any_wood_in_s = any(strfind(s,'wood'))
any_should_in_s = any(strfind(s,'should'))

Output 7.5.2:

all_wood_in_s =
10    23    45    68
all_could_in_s =
15    56
all_should_in_s =
 []
any_wood_in_s =
 1
any_should_in_s =
 0

Code 7.5.3:

s = ['How much wood could a wood chuck chuck'...
' if a wood chuck could chuck wood?'];
s1 = strrep(s,'wood','cider');
s2 = strrep(s1,'chuck','press');
s2

Output 7.5.3:

s2 =
How much cider could a cider press press if a cider press could press cider?

Code 7.5.4:

infilename = 'myexpt_EF_062913_step2.mat'
outfilename = strrep(infilename, 'step2', 'step3')
fprintf('\n');
inMatName =  'MeanReactionTimes.mat'
outTxtName = strrep(inMatName,'.mat','.txt')

Output 7.5.4:

infilename =
myexpt_EF_062913_step2.mat
outfilename =
myexpt_EF_062913_step3.mat

inMatName =
MeanReactionTimes.mat
outTxtName =
MeanReactionTimes.txt

Code 7.5.5:

infilename = 'RTdata.txt';
infile = fopen(infilename);
firstline = fgetl(infile); %read the header line
headers = textscan(firstline,'%s');
cell_of_headers = headers{1}(1:3)'

matrix_of_numbers = [];
while ~feof(infile)
    nextline = fgetl(infile);
    nextvalues = textscan(nextline,'%f');
    matrix_of_numbers = [matrix_of_numbers; nextvalues{1}(1:3)'];
end

fclose(infile);
matrix_of_numbers

Output 7.5.5:

cell_of_headers =
'sub'    'RT'    'Errors'
matrix_of_numbers =
1.0000  400.0000    5.5000
2.0000  480.6000    4.3000

Output 7.6.1:

Trial   side stim   comp    Key  Resp.    RT
1  L    L    C  R   error   0.73
2  R    R    C  R   correct 0.79
3  L    R    I  R   correct 0.54
4  R    L    I  L   correct 0.51
5  L    R    I  R   correct 0.44
6  L    L    C  L   correct 0.49
7  R    L    I  R   error   0.39
8  R    R    C  R   correct 0.68
...data from many more trials not shown

Code 7.6.2:

% DoSimon.m
fin = fopen('Simon.txt');
allRTs = [];
%Skip the header line
headerline = fgetl(fin);
while ~feof(fin)
    aline = fgetl(fin);

    %Read in the variables
    cellvalues = textscan(aline,'%d %s %s %s %s %s %f');
    Trnum = cell2mat(cellvalues(1));
    side = char(cellvalues{2});
    stim = char(cellvalues{3});
    comp = char(cellvalues{4});
    Key = char(cellvalues{5});
    Resp = char(cellvalues{6});
    RT = cell2mat(cellvalues(7));

    % Assemble the correct trial RT's
    if strcmp(Resp,'correct')
        allRTs = [allRTs RT];
    end

end
meanRT = mean(allRTs);
fprintf('Mean of correct RTs is %f\n',meanRT);

Output 7.6.2:

Mean of correct RTs is 0.575000

Code 7.7.5:

% Code_7_6_5.m
rng('default')
for n = 1:20
    r1 = randn;
    r2 = mean([r1 r1 randn]) + .4;
    subject(n).score1 = r1;
    subject(n).score2 = r2;
end
subject
checksum1 = sum([subject(:).score1])
checksum2 = sum([subject(:).score2])

Output 7.7.5:

subject =
1x20 struct array with fields:
    score1
    score2
checksum1 =
    4.5867
checksum2 =
   13.5765

Solutions

% Solutions_Chapter_07

% Solutions for selected problems from MATLAB for Behavioral Scientists,
% Second Edition (D. A. Rosenbaum, J. Vaughan, & B. Wyble),
% (c) 2015, Taylor & Francis

% To generate the solution for one problem, copy and run the code for that
% problem in a file or paste it into the Command window. Show the Command
% window to see the results.

% To generate sll the solutions for Chapter 7, save this code as a
% MATLAB script file and run the program.

%
% Problem 7.6.1
% Create a 5×3 cell array, G, in which the first row contains the name
% of one student (Adam, Brad, Charley, David, or Emily) in the first
% column of the cell array; the student's corresponding numerical average
% (90, 92, 96, 95, 88) in the second column of the cell array; and the
% student's letter grade (A-, A-, A, A, B+) in the third column.
%
% Represent the same data as above in a 5×1 struct array,
% studentStruct(1:5), with two fields, name, and average initialized
% as above.  Write a program to compute the letter grade based on
% studentStruct(i).average, and record it in studentStruct(i).letter
% for each student.
clc
commandwindow
fprintf('\n\n          %s\n\n','Output 7.6.1')
fprintf('Cell Array solution:');
G = { 'Adam','Brad','Charley','David','Emily';
    90, 92, 96, 95, 88;
    'A-', 'A-','A','A','B+'}
fprintf('Struct Array solution:');
names = {'Adam','Brad','Charley','David','Emily'};
grades = [90, 92, 96, 95, 88];
for i = 1:5
    studentStruct(i).name = names(i);
    studentStruct(i).grades = grades(i);
end
Student3Before = studentStruct(3)
for i = 1:5
    if studentStruct(i).grades >= 93.5
        studentStruct(i).letter = 'A';
    elseif studentStruct(i).grades >= 90
        studentStruct(i).letter = 'A-';
    elseif studentStruct(i).grades >= 86.5
        studentStruct(i).letter = 'B+';
    elseif studentStruct(i).grades >= 83.5
        studentStruct(i).letter = 'B';
    % Etc. for the rest of the grades...
    end
end
Student3After = studentStruct(3)


% Problem 7.6.2
%
% % Create a cell array, C, whose rows 32 through 127 contain that number
% as an integer in the first column and the character equivalent of that
% number in the second column.
fprintf('Solution left to the student.\n\n');

%
%  Problem 7.6.3
%
% % Use fprintf to print the numbers 65 through 90 in one column, the
% character equivalent of that value in column 2, the numbers 97 through
% 122 in column 3, and the character equivalent of that number in column 4.
fprintf('\n\n          %s\n\n','Output 7.6.3')
for i = 65:90
    fprintf('%4d%2s  %4d%2s\n',i, char(i),i+32,char(i+32));
end

%
% Problem 7.6.4
%
% % Write a program to administer a computerized questionnaire on a topic
% of interest to you. Use a structure data type and allow participants to
% answer with whole sentences or phrases for at least some items. Save the
% data in an external file. Record the time to answer each question.
fprintf('\n\n          %s\n\n','Output 7.6.4')
fprintf('This solution is left to the student\n')

% Problem 7.6.5
% % Generate a data set using Code 7.6.5, and verify the accuracy of your
% program by comparing its checksum output with that in Output 7.6.5.
%
% Code 7.6.5
%
% % Code_7_6_5.m
fprintf('\n\n          %s\n\n','Output 7.6.5')
rng('default')
for n = 1:20
    r1 = randn;
    r2 = mean([r1 r1 randn]) + .4;
    subject(n).score1 = r1;
    subject(n).score2 = r2;
end
subject
checksum1 = sum([subject(:).score1])
checksum2 = sum([subject(:).score2])

% Output 7.6.5
%
% subject =
% 1x20 struct array with fields:
%     score1
%     score2
% checksum1 =
%     4.5867
% checksum2 =
%    13.5765
%
% Now, compute the correlation coefficient between score1 and score2.
CorrelationTable = corrcoef([subject(:).score1],[subject(:).score2])
R_Score1_Score2 = CorrelationTable(1,2)

%
% Problem 7.6.6
%
% Evaluate the difference between score1 and score2 using a correlated
% (within-subjects, or paired-samples) t-test. As a reminder, the
% computational formula for a within-subjects t-test is given below,
% where d = score2 - score1 (for each subject), and n is the number of
% subjects, 20.  If the absolute value of your computed value of t is
% greater than 2.861, the difference between score1 and score2 is
% statistically significant at the .01 level (p < .01, two tailed test,
% with df = 19).  Verify the accuracy of your computation and decision
% using the statistical package of your choice.
fprintf('\n\n          %s\n\n','Output 7.6.6')
differences = [subject(:).score1]-[subject(:).score2];
diffsquared = differences.^2;
n = length(subject)
numerator = sum(differences);
denominator1 = n*sum(diffsquared) - (sum(differences)^2);
denominator2 = n - 1;
denominator = sqrt(denominator1/denominator2);
t = numerator/denominator

Output 7.6.1

Cell Array solution:G = 
    'Adam'    'Brad'    'Charley'    'David'    'Emily'
    [  90]    [  92]    [     96]    [   95]    [   88]
    'A-'      'A-'      'A'          'A'        'B+'   
Struct Array solution:Student3Before = 
      name: {'Charley'}
    grades: 96
Student3After = 
      name: {'Charley'}
    grades: 96
    letter: 'A'
Solution left to the student.

Output 7.6.3

  65 A    97 a
  66 B    98 b
  67 C    99 c
  68 D   100 d
  69 E   101 e
  70 F   102 f
  71 G   103 g
  72 H   104 h
  73 I   105 i
  74 J   106 j
  75 K   107 k
  76 L   108 l
  77 M   109 m
  78 N   110 n
  79 O   111 o
  80 P   112 p
  81 Q   113 q
  82 R   114 r
  83 S   115 s
  84 T   116 t
  85 U   117 u
  86 V   118 v
  87 W   119 w
  88 X   120 x
  89 Y   121 y
  90 Z   122 z

Output 7.6.4

This solution is left to the student

Output 7.6.5

subject = 
1x20 struct array with fields:
    score1
    score2
checksum1 =
    4.5867
checksum2 =
   13.5765
CorrelationTable =
    1.0000    0.8863
    0.8863    1.0000
R_Score1_Score2 =
    0.8863

Output 7.6.6

n =
    20
t =
   -2.9546