how to delete rows in cell array

3 Ansichten (letzte 30 Tage)
Elie Elias
Elie Elias am 4 Nov. 2018
Kommentiert: Elie Elias am 4 Nov. 2018
In my cell array, i have rows with random letters and numbers and rows where every element is 1.Those rows are randomly generated so i dont know their position. How can i delete every row of 1 without knowing their position?

Akzeptierte Antwort

Bruno Luong
Bruno Luong am 4 Nov. 2018
Bearbeitet: Bruno Luong am 4 Nov. 2018
>> A=rand(5,3)
A =
0.3012 0.2259 0.9234
0.4709 0.1707 0.4302
0.2305 0.2277 0.1848
0.8443 0.4357 0.9049
0.1948 0.3111 0.9797
>> A(4,:)=1
A =
0.3012 0.2259 0.9234
0.4709 0.1707 0.4302
0.2305 0.2277 0.1848
1.0000 1.0000 1.0000
0.1948 0.3111 0.9797
>> c = num2cell(A)
c =
5×3 cell array
{[0.3012]} {[0.2259]} {[0.9234]}
{[0.4709]} {[0.1707]} {[0.4302]}
{[0.2305]} {[0.2277]} {[0.1848]}
{[ 1]} {[ 1]} {[ 1]}
{[0.1948]} {[0.3111]} {[0.9797]}
Here is the command to remove row(s) with all 1s
>> c(all(cellfun(@(x) isequal(x,1),c),2),:)=[]
c =
4×3 cell array
{[0.3012]} {[0.2259]} {[0.9234]}
{[0.4709]} {[0.1707]} {[0.4302]}
{[0.2305]} {[0.2277]} {[0.1848]}
{[0.1948]} {[0.3111]} {[0.9797]}
>>
  3 Kommentare
Bruno Luong
Bruno Luong am 4 Nov. 2018
Sure. ISEQUAL is generic MATLAB command that return TRUE if and only if the two objects of the arguments are identical. Examples
>> isequal(3,3)
ans =
logical
1
>> isequal(3,'3')
ans =
logical
0
>> isequal(3,[3 1])
ans =
logical
0
>>
>> isequal(3,'3')
ans =
logical
0
CELLFUN will apply ISEQUAL to each element the cell array, and return a matrix of the same size of C where the element TRUE if the elements c{i,j} is equal to 1.
ALL(xxx,2) will returns the logical vector TF with the length equals to number of rows of logical matrix xxx, and true only if a all the columns of a given row is 1, meaning
TF(i)=TRUE if xxx(i,:) are all TRUE.
The last thing to understand is
c(TF,:)=[]
This command removes all the row of C where TF is TRUE.
Put all this together, it does what you ask for.
Elie Elias
Elie Elias am 4 Nov. 2018
thank you!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

per isakson
per isakson am 4 Nov. 2018
Bearbeitet: per isakson am 4 Nov. 2018
Try
%%I assume that your cell array is somewhat similar to this one
cac = { 'a','b','c'
[1],[2],[3]
'a','b','c'
[1],[1],[1]
'a','b','c'
[1],[2],[3]
};
is_one = cellfun( @(element) isnumeric(element) && element==1, cac );
is_row_of_ones = all( is_one, 2 );
cac( is_row_of_ones, : ) = []
which outputs
cac =
5×3 cell array
{'a'} {'b'} {'c'}
{[1]} {[2]} {[3]}
{'a'} {'b'} {'c'}
{'a'} {'b'} {'c'}
{[1]} {[2]} {[3]}
and see the Matlab documentation

Kategorien

Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by