How to write a for loop to iterate through subjects IDs and their associated reaction times and create histogram

5 次查看(过去 30 天)
I have a data set of several thousand values.
There are 10 unique subj_indx, 1 through 10. Each one represents an experimental subject. Each subject has a bunch of reaction times, rt.
I want to create a for loop that will go through this dataset and generate a histogram of the reaction time data for each subject.
I don't know where to start other than:
rt=subject_data.rt;
for id = 1:length(subj_idx)%loop for each unique id value
%rtIdx = 1:length(rt)
currentid = rt(rtIdx);
rtIdx = 0;
and I'm not sure even that's correct.

采纳的回答

Paul
Paul 2022-9-19
Hi Rania,
Check out the splitapply function and workflow. Example with an array, but I think you can make it work with a table
x = [ones(100,1) rand(100,1);2*ones(100,1) rand(100,1)]; % example data
splitapply(@(x) histogram(axes(figure),x),x(:,2),findgroups(x(:,1)))
If you want to pretty-up the histograms, I think splitapply can be used with a user-defined function just as easily.
  3 个评论
Paul
Paul 2022-9-19
编辑:Paul 2022-9-19
"I want to create a for loop that will go through this dataset and generate a histogram of the reaction time data for each subject."
That's exactly what the code in the Answer does. think of x(:,1) as the subj_idx and x(:,2) as the rt. A histogram was created for all of the rt data corresponding to subj_idx == 1 and a second histrogram for subj_idx == 2. Maybe this will clarify with a table as an example?
subj_idx = [ones(100,1);ones(100,1)*2];
rt = rand(200,1);
T = table(subj_idx,rt); % example table
splitapply(@(x) histogram(axes(figure),x),T.rt,findgroups(T.subj_idx))
Here's the same data with nicer plots
splitapply(@(rt,subj_idx) myfunc(rt,subj_idx),T.rt,T.subj_idx,findgroups(T.subj_idx))
function myfunc(rt,subj_idx)
figure;
histogram(rt)
title("RT histogram of subj_idx" + double(unique(subj_idx)));
xlabel('RT')
ylabel('Occurences')
end

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Histograms 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by