How to remove certain rows of data in a cell array using logical indexing?
17 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Daniel Rowe
il 13 Giu 2021
Commentato: Daniel Rowe
il 14 Giu 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
0 Commenti
Risposta accettata
the cyclist
il 13 Giu 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 Commenti
the cyclist
il 14 Giu 2021
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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Matrices and Arrays in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!