How to calculate the frequency of a binary event (0 or 1) on a weekday basis over the last 10 years?

3 views (last 30 days)
I have a single column Logical matrix with 0 and 1's and a single column weekday char matrix with weekday names. I want to calculate how may times I get a 1 for each weekday for the entire period of both matrices (both are about 10 years). Then the same for 0. Then Id like to visualise it. Any ideas?

Answers (3)

Azzi Abdelmalek
Azzi Abdelmalek on 28 May 2015
n=20
a=randi([0 1],n,1)
b={'monday';'tuesday';'Wednesday';'Thursday';'friday'}
w=b(randi(5,n,1))
v=[num2cell(a) w]
[ii1,jj1,kk]=unique(v(:,2))
out1=[ii num2cell(accumarray(kk,a))]
out0=[ii num2cell(accumarray(kk,~a))]

Andrei Bobrov
Andrei Bobrov on 28 May 2015
t = datenum([2015 2 14;2015 8 15]);
[N,S] = weekday((t(1):t(2))');
O = rand(numel(N),1) > .5;
% ones
out1 = accumarray(N,O);
% zeros
out0 = accumarray(N,~O);
[~,b] = unique(N);
out = [cellstr(S(b,:)), num2cell([out1,out0])]

Walter Roberson
Walter Roberson on 28 May 2015
Letting Lvec be the logical column vector, and letting Wvec be the character column vector, then
dayorder = 'MTWJFSD'; %the day characters in the order you want to present
%need to translate day characters into bin numbers for counting. But
%potentially some day characters do not appear at all, and potentially
%some wrong characters appear. We could first check for validity and then
%bin against the known characters, but the validity check can give us bin
%numbers as a side-effect, so might as well use them. The bin numbers
%will not match the order of the days, but we can find the map between the
%two at the same time we are checking if any entries were invalid
[unique_daychar, ia, binnum] = unique(Wvec);
[tf, ordermap] = ismember(unique_daychar, dayorder);
unknown_days = unique_daychar(~tf);
if ~isempty(unknown_days)
error(sprintf('Unknown day codes in input: %s', unknown_days(:).'));
end
%so know we have bin numbers with the bins in an arbitrary order (actually
%in the order the characters sort into), and we have a mapping between that
%arbitrary order and our desired presentation order. We can do stats in
%either order. It's just easier to present the output if we do the stats
%in presentation order. That's why we map the bin numbers that we send into
%the counting routine, so that the counts come out in presentation order
stats = accumarray([1+Lvec, ordermap(binnum)], 1, [2, length(dayorder)]);
%the rest is just visualization, make it as pretty as you like
fprintf('Day order: %s\n', dayorder);
fprintf('Counts for 0:\n');
fprintf('%5d', stats(1,:));
fprintf('\nCounts for 1:\n');
fprintf('%5d', stats(2,:));
fprintf('\n');

Categories

Find more on Startup and Shutdown 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!