从具有一些空单元格的单元格创建新矩阵而忽略空单元格

时间:2014-03-18 12:32:32

标签: matlab matrix cell

我在Matlab中有一个名为: elem

的单元格
 [36 29]
 []
 [30 29]
 [30 18]
 []
 [31 29]
 []
 []
 [8 9]
 [32 30]

和一个名为: conn

的矩阵
1   2
1   3
1   4
1   5
2   3
2   4
2   5
3   4
3   5
4   5

我想创建2个新矩阵,它们只包含与 elem 的非空单元格相对应的元素,而不使用for循环。 例如,正确的结果将是:

29  36
29  30
18  30
29  31
8   9
30  32

1   2
1   4
1   5
2   4
3   5
4   5

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:2)

inds = ~cellfun('isempty', elem);    %// NOTE: faster than anonymous function
conn = conn(inds,:);
elem = elem(inds);                   %// (preservative)

inds = cellfun('isempty', elem);     %// NOTE: faster than anonymous function
conn(inds,:) = [];
elem(inds  ) = [];                   %// (destructive)

inds = cellfun(@(x)isequal(x,[]), elem)  %// NOTE: stricter; evaluates to false 
conn = conn(inds,:);                     %// when the 'empties' are '' or {}
elem = elem(inds);                       %// or struct([])

inds = cellfun(@(x)isequal(x,[]), elem)  %// "
conn(inds,:) = [];
elem(inds  ) = [];

inds = cellfun(@numel, elem)==2    %// NOTE: even stricter; only evaluates to 
conn = conn(inds,:);               %// true when there are exactly 2 elements 
elem = elem(inds);                 %// in the entry

inds = cellfun(@numel, elem)==2    %// " 
conn(inds,:) = [];
elem(inds  ) = [];

或(如果您只对elem感兴趣)

elem = cell2mat(elem)

elem = cat(1,elem{:})  %// NOTE: probably the fastest of them all

答案 1 :(得分:1)

您的第一个输出可以通过以下方式获得:

cellfun(@fliplr, elem(~cellfun(@isempty, elem)), 'UniformOutput', 0);

请注意我包含了@fliplr,假设您的问题中的元素顺序颠倒是故意的

您的第二个输出可以通过以下方式获得:

conn(~cellfun(@isempty, elem), :);

答案 2 :(得分:0)

conn = [1   2
        1   3
        1   4
        1   5
        2   3
        2   4
        2   5
        3   4
        3   5
        4   5];

elem = { [36 29]
         []
         [30 29]
         [30 18]
         []
         [31 29]
         []
         [8 9]
         [32 30]};

conn(~cellfun(@isempty, elem), :)

答案 3 :(得分:0)

你可以使用@isempty cellfun()函数和逻辑运算符这样:

EmptyCells=cellfun(@isempty,elem); %Detect empty cells

elem(EmptyCells)=[]; %Remove empty cells

conn=conn(~EmptyCells); %Remove elements corresponding the empty cells in elem

希望有效!