% example solution of exercise 2 problem 2

% read in the data from the file

[lh rt resp wn]=textread('ex2rt.txt','%c%d%c%c');

% create a variable to hold accuracy for each trial
correct=zeros(size(rt));

% one could loop through trials and determine whether each response is correct

%for x=1:400,
%    if resp(x)==wn(x),
%       correct(x)=1;
%    end;
%end;

% and then use this correct indicator variable to index correct trials

% alternatively, one can use find to get this more easily
% determine trial numbers for correct trials in each condition (HW, HN, LW, LN)

HW_trials = find(resp==wn & lh == 'H' & wn == 'W');
HN_trials = find(resp==wn & lh == 'H' & wn == 'N');
LW_trials = find(resp==wn & lh == 'L' & wn == 'W');
LN_trials = find(resp==wn & lh == 'L' & wn == 'N');

% compute means and accuracy for each condition (HW, HN, LW, LN)
% this could be done more efficiently by using an array instead 
% of using separate variables for each condition, but I've done 
% it in the less efficient way here because it's more transparent.

mean_accuracy_HW = size(HW_trials,1)/100;
mean_accuracy_HN = size(HN_trials,1)/100;
mean_accuracy_LW = size(LW_trials,1)/100;
mean_accuracy_LN = size(LN_trials,1)/100;

mean_RT_HW = mean(rt(HW_trials));
mean_RT_HN = mean(rt(HN_trials));
mean_RT_LW = mean(rt(LW_trials));
mean_RT_LN = mean(rt(LN_trials));

std_RT_HW = std(rt(HW_trials));
std_RT_HN = std(rt(HN_trials));
std_RT_LW = std(rt(LW_trials));
std_RT_LN = std(rt(LN_trials));


% print the report

fprintf('Report:\n');
fprintf('Condition\tRT\t\tAccuracy\n');
fprintf('HW\t\t%0.1f (%0.2f)\t%0.2f\n',...
	    mean_RT_HW,std_RT_HW,mean_accuracy_HW);
fprintf('HN\t\t%0.1f (%0.2f)\t%0.2f\n',...
	    mean_RT_HN,std_RT_HN,mean_accuracy_HN);
fprintf('LW\t\t%0.1f (%0.2f)\t%0.2f\n',...
	    mean_RT_LW,std_RT_LW,mean_accuracy_LW);
fprintf('LN\t\t%0.1f (%0.2f)\t%0.2f\n',...
	    mean_RT_LN,std_RT_LN,mean_accuracy_LN);

% plot histogram for each condition

[HW_hist, HW_bins]=hist(rt(HW_trials));
[HN_hist, HN_bins]=hist(rt(HN_trials));
[LW_hist, LW_bins]=hist(rt(LW_trials));
[LN_hist, LN_bins]=hist(rt(LN_trials));

HW_hist=HW_hist/max(HW_hist);
HN_hist=HN_hist/max(HN_hist);
LW_hist=LW_hist/max(LW_hist);
LN_hist=LN_hist/max(LN_hist);

figure;
hold on;
plot(HW_bins,HW_hist,'b');
plot(HN_bins,HN_hist,'r');
plot(LW_bins,LW_hist,'g');
plot(LN_bins,LN_hist,'k');
legend('HW','HW','LW','LN')