Why do I get: Error using sum Invalid data type. First argument must be numeric or logical?

3 次查看(过去 30 天)
Hi,
I have a cell array called "pre_data" with 1 column and 27 rows. Each element in the column contains a cell with 21 colums and a varying number of rows.
I want to scan the columns in the cells of pre_data. For each seperate column, if there are values in a column that are above 3 standard deviations of that column, then I want the row cointaining that value to be removed.
For that I have written the following piece of code:
pre_data_clean = cell(size(pre_data));
% iterate over each cell in pre_data
for i = 1:length(pre_data)
data_pre = pre_data{i}; % get the data in the current cell
means_pre = cellfun(@mean, data_pre, 'UniformOutput', false); % calculate the means of each column
stds_pre = cellfun(@std, data_pre, 'UniformOutput', false); % calculate the standard deviations of each column
% remove values that are above 3 standard deviations from the mean
for j = 1:size(data_pre{1}, 2) % iterate over each column
for k = 1:length(data_pre) % iterate over each row in each cell
data_pre{k}(:, j) = data_pre{k}(:, j) .* (abs(data_pre{k}(:, j) - means_pre{k}(j)) <= 3*stds_pre{k}(j));
end
end
pre_data_clean{i} = data_pre; % save the cleaned data to pre_data_clean
end
The code seems to me like it works. But when I apply the code for other cell arrays that I have (balls_data, between_data, baskets_data or post_data), similar to "pre_data", then I continue to get error messages like this:
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);
Is this because the cell arrays have empty cells? If so, how can I fix this code?
Thank you!

回答(1 个)

Walter Roberson
Walter Roberson 2023-3-14
You generally have cell arrays that contain cell arrays. However, in some places some of the entries are not cell arrays and are instead [] which is an empty double array.
Example fix:
baskets_data(cellfun(@isempty,baskets_data)) = {{}};
  7 个评论
lil brain
lil brain 2023-3-16
Thank you!
I have one last question. I just tried editing the code by making it scan for values above 1 SD... but nothing is removed which I think is not what would happen. Is the code performing correctly because it seems odd to me that not one value is above 1 SD.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by