how to delete rows in cell array

3 次查看(过去 30 天)
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?

采纳的回答

Bruno Luong
Bruno Luong 2018-11-4
编辑:Bruno Luong 2018-11-4
>> 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 个评论
Bruno Luong
Bruno Luong 2018-11-4
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.

请先登录,再进行评论。

更多回答(1 个)

per isakson
per isakson 2018-11-4
编辑:per isakson 2018-11-4
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

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by