Averaging a row of a cell array based on a row in another row
I have this array of cells:
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 I want to create an average for each type in the first row and store it in a new cell like this:
result = {'hist' 'plot' ;
[0.0106] [0.0036];
[ 1] [ 9]}
The first line is the types, the second is the averages, and the third is the number of items.
I solved the problem with this code:
labels = unique(times(1,:));
result = cell(3,numel(labels));
for i = 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 now is if there is an easier or more ideal solution to my problem.
+3
source to share
1 answer
With the combination of and, you can achieve what you want. unique
accumarray
%// example data
times = { 'plot' 'plot' 'plot' 'plot' 'hist' 'plot';
[1] [2] [3] [4] [5] [6] }
%// extract data
data = [times{2,:}]
%// get types and their locations
[types, ~, subs] = unique(times(1,:))
%// calculate average values
avgs = accumarray(subs(:),data(:),[],@mean)
%// count occurences
nums = accumarray(subs(:),data(:),[],@numel)
%// gather everything for output
result = [types; num2cell(avgs.'); num2cell(nums.')]
result =
'hist' 'plot'
[ 5] [3.2000]
[ 1] [ 5]
+7
source to share