Asked by Thar
on 2 Oct 2018

Dear all,

I want to find mean values of data per day. My data are cells (one cell with 12 columns per day). I did it:

for i=1:size(U(:,1),1);

id{i,1}=[find(data(:,1)==U(i,1) & data(:,2)==U(i,2))];

Z{i,1}=data(id{i,1},1:12);

m{i,1}=cellfun(@mean,[Z{i,1}(1:12)],'un',0);

end

until z works good and the problem is when calculate the mean values m.

Any ideas???

Thank you.

I took the error: Error using cellfun Input #2 expected to be a cell array, was double instead.

Answer by Guillaume
on 2 Oct 2018

Edited by Guillaume
on 2 Oct 2018

I think the explanation that I was asking for is that you have a matrix data whose first column is years and second column days (maybe ?) and you want to average all the other columns by day and year. If so, there are much easier ways to achieve this than what you have done, but first let's start by correcting your code:

z = cell(size(U, 1), 1); %I'm reusing your variable names despite them being very poor names

for i = 1:size(U, 1)

id = data(:, 1) == U(i, 1) & data(:, 2) == U(i, 2);

z{i} = data(id, :);

end

m = cell2mat(cellfun(@(rows) mean(rows, 1), Z, 'UniformOutput', false))

There are many ways the above could be improved but let's focus on the proper way of doing what you want, which does not involve loops. First option is to use findgroups and splitapply:

id = findgroups(data(:, 1), data(:, 2));

m = splitapply(@(rows) mean(rows, 1), data, id)

That's all!

The second option would be to convert your matrix into a table which has the added benefit of labelling the columns:

t = array2table(data, 'VariableNames', {'year', 'day', 'var3', 'var4', 'var5', 'var6', 'var7', 'var8', 'var9', 'var10', 'var11', 'var12'}) %replace by adequate names

m = varfun(@mean, t, 'GroupingVariables', {'year', 'day'})

Again, very simple.

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## Guillaume (view profile)

Direct link to this comment:https://ch.mathworks.com/matlabcentral/answers/421767-error-using-cellfun-input-2-expected-to-be-a-cell-array-was-double-instead#comment_616758

## Thar (view profile)

Direct link to this comment:https://ch.mathworks.com/matlabcentral/answers/421767-error-using-cellfun-input-2-expected-to-be-a-cell-array-was-double-instead#comment_616775

Sign in to comment.