How to remove certain rows of data in a cell array using logical indexing?

16 次查看(过去 30 天)
Hi,
I have a 1x11 cell array and I am trying to clean the data using logical indexing, i.e. remove certain rows in each cell once a simple condition is met. The cells are of different lengths (but always 20 columns) and I want the same conditions to be applied to all, i.e. when certain parameters (representing a number of the columns in each cell) exceed a certain threshold.
What is the best way to approach this? Thus far, I have recevied the 'matrix index is out of range for deletion' error message.
Thanks
Daniel

采纳的回答

the cyclist
the cyclist 2021-6-13
Here is an example where I keep only rows of each matrix where the sum is greater than 1. Perhaps you can adapt it to your specific criterion:
% Set the random seed
rng default
% Create some input data
n = 11;
c_in = cell(1,n);
for ni = 1:n
c_in{ni} = rand(7,2);
end
% Preallocate the output cell array to be the same size as the input
c_out = cell(size(c_in));
% For each cell, keep only the rows that sum to greater than 1
for ni = 1:n
keepRowIndex = sum(c_in{ni},2) > 1;
c_out{ni} = c_in{ni}(keepRowIndex,:);
end
There are slicker ways to do this, using the cellfun function, but better to understand this way first.
  2 个评论
the cyclist
the cyclist 2021-6-14
The equivalent method using cellfun:
c_out = cellfun(@(x)x(sum(x,2)>1,:),c_in,'UniformOutput',false);
This would take the place of the for loop over the cells, and you would also not need the preallocation step.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by