MATLAB Answers

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

2 views (last 30 days)
Daniel Rowe
Daniel Rowe on 13 Jun 2021
Commented: Daniel Rowe on 14 Jun 2021
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

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);
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 Comments

Sign in to comment.

More Answers (0)

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by