arrays - Apply function to table conditioned on several variables in Matlab -
i have following 2 tables, data
, members
:
data = table(sort(repmat(datenum(2001,1:5,1).',4,1)),repmat(('a':'d').',5,1),repmat((201:204).',5,1),'variablenames',{'date','id','price'}); data = date id price __________ __ _____ 7.3085e+05 201 7.3085e+05 b 202 7.3085e+05 c 203 7.3085e+05 d 204 7.3088e+05 201 7.3088e+05 b 202 7.3088e+05 c 203 7.3088e+05 d 204 7.3091e+05 201 7.3091e+05 b 202 7.3091e+05 c 203 7.3091e+05 d 204 7.3094e+05 201 7.3094e+05 b 202 7.3094e+05 c 203 7.3094e+05 d 204 7.3097e+05 201 7.3097e+05 b 202 7.3097e+05 c 203 7.3097e+05 d 204 members = table(datenum(2001,1:5,1).',{cell2table({'b','c'});table({'a'});cell2table({'b','d'});cell2table({'a','c'});cell2table({'a','c'})},'variablenames',{'date','memberid'}); members = date memberid __________ ___________ 7.3085e+05 [1x2 table] 7.3088e+05 [1x1 table] 7.3091e+05 [1x2 table] 7.3094e+05 [1x2 table] 7.3097e+05 [1x2 table]
now, apply function, mean
, price
variable each ´date´ , id
s in memberid
on each date. thus, first date, 7.3085e+05, mean of id 2 , 3 - i.e. (202+203)/2 - etc.
i able slow for
loop (my actual tables larger). thinking should possible using varfun
or similar, can't work. ideas?
update
changed id
s text, since how real data is.
approach 1
%// find offsets used linear indexing elements each group off1 = [0 ; find(diff(data.id)<0)] %// store prices , member ids numeric arrays prc = data.price mem_id = members.memberid %// convert each memberid table arrays; add corresponding %// linear indexing offsets , index prc , mean values out = arrayfun(@(n) mean(prc(off1(n)+ char(table2array(mem_id{n}))-'a'+1 )),... 1:numel(mem_id))
approach 2
%// find offsets used linear indexing elements each group off1 = [0 ; find(diff(data.id)<0)] %// store prices , member ids numeric arrays prc = data.price mem_id = members.memberid %// storage output out = zeros(1,numel(mem_id)) %// widths(lengths) of each table in memberid , unique lengths lens = arrayfun(@(n) width(mem_id{n}),1:numel(mem_id)) unqlens = unique(lens,'stable') %// now, have groups of memberid tables uniform %// widths/lengths, can use table2array on tables single %// call within each group , beneficial in performance iter = 1:numel(unqlens) mask = lens==unqlens(iter); %// mask each group mem_id_iter = mem_id(mask); %// member ids grp_ids = reshape(char(table2array(vertcat(mem_id_iter{:}))) - 'a' + 1,[],... unqlens(iter)); %// group ids lin_idx = bsxfun(@plus,off1(mask),grp_ids); %// linear indices out(mask) = mean(prc(lin_idx),2); %// index prc , mean values end
Comments
Post a Comment