mean of tables in cells

2 views (last 30 days)
Jan Lettner
Jan Lettner on 28 Nov 2018
Edited: Adam Danz on 23 Jun 2019
Hello everyone
For a project, I made some measurements, which I want to edit in Matlab. Since the table height is of different length, I want to fill the rest of the tables with NaN. But that doesn't work like I want to. Tables are stored in cells.
for k=1:length(Values)
while height(Values{1,k}) < 51
E = NaN*ones(1,2);
Values{1,k} = [Values{1,k};E];
end
end
The other problem occurs, when I want to calculate the mean.
for k=1:length(Values)
A(k)=mean(Values{1,k}(:,2));
end
I get this error:
Error using sum
Invalid data type. First argument must be numeric or logical.
Error in mean (line 127)
y = sum(x, dim, flag) ./ mysize(x,dim);
Error in mittelwertbildung_22a (line 8)
A(k)=mean(Values{1,k}(:,2));
The first value is definitely a numeric value. So I don't know, where the problem is. I appreciate every help I can get. Thanks in advance guys
  3 Comments
Guillaume
Guillaume on 28 Nov 2018
Are your Values{k} actual matlab tables or are they plain matrices. The code you've posted would not work with actual tables.
A few notes:
  • don't use 2D notation if your cell array is a vector. Use Values{k} instead of Values{1, k}. The former will work whether Values is a column or row vector, the latter will error. It's also shorter to type.
  • E= NaN*ones(1, 2), is a slower way of generating E = NaN(1, 2). To make your code future proof it would be better to make that NaN matrix the same width as the matrix you're appending it to, so even better would be
E = NaN(1, size(Values{k}, 2));
  • I'd recommend you use numel instead of length. Then it really doesn't matter whether Values is a row cell array, a column cell array or even a ND cell array.
With regards to your question, what is the output of
cellfun(@isnumeric, Values)
Fabrice Lambert
Fabrice Lambert on 23 Jun 2019
I have a similar problem. Using the OP's example, Values{1,k}(:,2) is a table, so not a valid input for mean. However, mean(Values{1,k}{:,2}) does not work either. How do you (one line) extract data from a table within a cell to do statistics on them, without using table2array etc.?

Sign in to comment.

Answers (1)

Adam Danz
Adam Danz on 23 Jun 2019
Edited: Adam Danz on 23 Jun 2019
You can adapt this functional demo to your needs and if it doesn't work with your data, please tell us how your data differ from the demo data.
Values = {table((1:20)',(1:20)'); table((1:22)',(1:22)')};
dth = 26; %desired table height (51 in your case)
A = zeros(size(Values));
for k = 1:length(Values)
nanpad = array2table(nan(26-height(Values{k}),width(Values{k})), ...
'VariableNames',Values{k}.Properties.VariableNames);
Values{k} = [Values{k};nanpad];
A(k) = mean(Values{k}{:,2},'omitnan');
end

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!