How to count instances of values in a table?

42 views (last 30 days)
Hayley Rogers
Hayley Rogers on 30 Dec 2022
Answered: Voss on 31 Dec 2022
How can I make the following code more efficient? This current version takes incredibly long to run on my large table. The goal of the code is to assign the position each row appears in a table, where the table dates are sorted from newest to oldest.
For example, if
%input data sample
call_summary =
6×3 table
Symbol Date BDTE
______ ______ ______
AAPL 12/16/2022 7
AAPL 12/16/2022 14
AAPL 12/09/2022 7
AAPL 12/09/2022 14
AAPL 12/09/2022 21
AAPL 12/02/2022 7
AAPL 12/02/2022 21
%current code below
call_height = height(call_summary);
count_call = zeros(call_height,1);
parfor h = 1:call_height
count_call(h) = sum((call_summary.Symbol == call_summary{h,'Symbol'}).*(call_summary.BDTE == call_summary{h,'BDTE'}).*(call_summary.Date >= call_summary{h,'Date'}));
end
%output data sample
count_call =
6×1 table
Count
______
1 %First occurance of BDTE = 7 for AAPL, where dates sorted newest to oldest
1 %First occurance of BDTE = 14 for AAPL, where dates sorted newest to oldest
2 %Second occurance of BDTE = 7 for AAPL, where dates sorted newest to oldest
2 %Second occurance of BDTE = 14 for AAPL, where dates sorted newest to oldest
1 %First occurance of BDTE = 21 for AAPL, where dates sorted newest to oldest
3 %Third occurance of BDTE = 7 for AAPL, where dates sorted newest to oldest
2 %Second occurance of BDTE = 21 for AAPL, where dates sorted newest to oldest

Answers (1)

Voss
Voss on 31 Dec 2022
call_summary = table( ...
{'AAPL';'AAPL';'AAPL';'AAPL';'AAPL';'AAPL';'AAPL'}, ...
{'12/16/2022';'12/16/2022';'12/09/2022';'12/09/2022';'12/09/2022';'12/02/2022';'12/02/2022'}, ...
[7;14;7;14;21;7;21], ...
'VariableNames',{'Symbol','Date','BDTE'})
call_summary = 7×3 table
Symbol Date BDTE ________ ______________ ____ {'AAPL'} {'12/16/2022'} 7 {'AAPL'} {'12/16/2022'} 14 {'AAPL'} {'12/09/2022'} 7 {'AAPL'} {'12/09/2022'} 14 {'AAPL'} {'12/09/2022'} 21 {'AAPL'} {'12/02/2022'} 7 {'AAPL'} {'12/02/2022'} 21
count_call = zeros(size(call_summary,1),1);
g = findgroups(call_summary(:,{'Symbol','BDTE'}));
for ii = 1:max(g)
count_call(g == ii) = 1:nnz(g == ii);
end
disp(count_call);
1 1 2 2 1 3 2

Categories

Find more on Thermal Analysis in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!