matlab - Averaging a row of a cell array dependent on a string in another row -
i've got cell-array:
times = {'plot' 'plot' 'plot' 'plot' 'plot' 'hist' 'plot' 'plot' 'plot' 'plot' ; [0.0042] [0.0026] [0.0032] [0.0054] [0.0049] [0.0106] [0.0038] [0.0026] [0.0030] [0.0026]}
now want create average each type in first row , save new cell this:
result = {'hist' 'plot' ; [0.0106] [0.0036]; [ 1] [ 9]}
the first row types, second row averages , third row number of elements.
i solved problem code:
labels = unique(times(1,:)); result = cell(3,numel(labels)); = 1 : numel(labels) result(1,i) = labels(i); times2avg = cell2mat(times(2,strcmp(times(1,:), labels(i)))); result{2,i} = mean(times2avg); result{3,i} = numel(times2avg); end
my question whether there easier or more ideal solution problem.
with combination of unique
, accumarray
can achieve want.
%// example data times = { 'plot' 'plot' 'plot' 'plot' 'hist' 'plot'; [1] [2] [3] [4] [5] [6] } %// extract data data = [times{2,:}] %// types , locations [types, ~, subs] = unique(times(1,:)) %// calculate average values avgs = accumarray(subs(:),data(:),[],@mean) %// count occurences nums = accumarray(subs(:),data(:),[],@numel) %// gather output result = [types; num2cell(avgs.'); num2cell(nums.')]
result = 'hist' 'plot' [ 5] [3.2000] [ 1] [ 5]
Comments
Post a Comment