Counting in one column that is conditional on another column

조회 수: 2 (최근 30일)
Mirthand
Mirthand 2021년 4월 2일
댓글: Mirthand 2021년 4월 5일
For each cell (or "trial") in the variable trials (attached):
I'd like to count the number of 1's in column 4 that is dependent on certain conditions in column 2 for each trial.
Conditions saved in their own variable:
Count 1's in column 4 if column 2 is between 0 and 4 (less than 4, not equal to)
Count 1's in column 4 if column 2 is between 4 and 5 (less than 5, not equal to)
Count 1's in column 4 if column 2 is between 5 and 6 (less than 6, not equal to)
Count 1's in column 4 if column 2 is between 6 and 7 (less than 7, not equal to)
Count 1's in column 4 if column 2 is between 7 and end

채택된 답변

per isakson
per isakson 2021년 4월 2일
편집: per isakson 2021년 4월 2일
Does this do what you look for?
%%
limits = { [0;4], [4;5], [5;6], [6;7], [7;inf] };
%% some simple test data
trials = {[ 0, 2, 0, 1, 0, 0, 0
0, 2, 0, 0, 0, 0, 0
0, 5, 0, 1, 0, 0, 0
0, 5, 0, 0, 0, 0, 0
0, 5, 0, 1, 0, 0, 0
0, 5, 0, 0, 0, 0, 0
0, 9, 0, 1, 0, 0, 0 ]};
%%
fh = @(trial,lim) sum( (trial(:,4)==1) & (lim(1)<=trial(:,2) & trial(:,2)<lim(2)), 1 );
%%
counts = zeros( numel(trials), numel(limits) );
for rr = 1 : numel(trials)
for cc = 1 : numel(limits)
counts(rr,cc) = fh( trials{rr}, limits{cc} );
end
end
Inspect
>> counts
counts =
1 0 2 0 1
Yes, sum() can operate on logicals
>> sum([true,true,false])
ans =
2
  댓글 수: 10
Mirthand
Mirthand 2021년 4월 5일
You are right, I need to think carefully about how I want to change column 2 so that it works.
Mirthand
Mirthand 2021년 4월 5일
Thanks for your help again!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Steven Lord
Steven Lord 2021년 4월 2일
Use discretize or findgroups to identify groups based on the values in column 2, then use groupsummary or splitapply to perform group processing on column 4 based on the groups you identified in the first step.
  댓글 수: 1
Mirthand
Mirthand 2021년 4월 2일
Would discretize work if there are zeros?
for example, I still want to group the third row with the group that is 2.
The 7th row, containing zero would also be grouped with 5.
trials = {[ 0, 2, 0, 1, 0, 0, 0
0, 2, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0
0, 5, 0, 1, 0, 0, 0
0, 5, 0, 0, 0, 0, 0
0, 5, 0, 1, 0, 0, 0
0, 0, 0, 0, 0, 0, 0
0, 5, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0
0, 6, 0, 1, 0, 0, 0 ]};

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Software Development Tools에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by