我在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
非常感谢任何帮助。
答案 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
希望有效!