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

22 views (last 30 days)
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.

Accepted Answer

the cyclist
the cyclist on 13 Jun 2021
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);
% 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,:);
There are slicker ways to do this, using the cellfun function, but better to understand this way first.

Sign in to comment.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!

Translated by