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

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

 채택된 답변

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 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개)

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

릴리스

R2019b

질문:

2021년 6월 13일

댓글:

2021년 6월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by