Why do I get: Error using sum Invalid data type. First argument must be numeric or logical?
古いコメントを表示
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
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
2023 年 3 月 14 日
Walter Roberson
2023 年 3 月 14 日
You would not incorporate it into the above code that you posted. You would incorporate it into some portion before that, just after you loaded the data.
load baskets_data.mat
baskets_data(cellfun(@isempty,baskets_data)) = {{}};
and similarly for the other data files.
lil brain
2023 年 3 月 15 日
Walter Roberson
2023 年 3 月 15 日
balls_data{19} is {} which is size 0 0.
You have
for j = 1:size(data_balls{1}, 2)
but data_balls is empty so data_balls{1} does not exist.
You should be checking isempty(data_balls) before trying to use data_balls{1}
lil brain
2023 年 3 月 16 日
Walter Roberson
2023 年 3 月 16 日
if isempty(data_balls)
balls_data_clean{i} = data_balls;
continue;
end
lil brain
2023 年 3 月 16 日
カテゴリ
ヘルプ センター および File Exchange で Data Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!