How to delete element from cell arrays after comparisons without causing cell arrays to get empty?

萝らか妹 提交于 2020-01-16 18:09:47

问题


I created 1D array which shows words and in which sentences they occur. After that I took the intersection to show which word occurs with which each of other remaining words in sentence:

OccursTogether = cell(length(Out1));
for ii=1:length(Out1)
for jj=ii+1:length(Out1)
OccursTogether{ii,jj} = intersect(Out1{ii},Out1{jj});
end
end
celldisp(OccursTogether)

the output of above code is as below:

OccursTogether{1,1} =

 4 11 14

OccursTogether{1,2} =

 1
OccursTogether{1,3} =

 []
OccursTogether{1,4} =

 1 4 8 14 15 19 20 22

OccursTogether{1,5} =

 4 11

I want to check a single element if its deletion doesn't cause empty set it should be deleted but if its deletion give rise to empty set it should not be deleted.

for example:

step1:Delete 4 from {1,1}and{1,5} it will not be empty so 4 should be deleted.

step2: Delete 14 from {1,1}and{1,4} it will not be empty so 14 should also be deleted.

step3: If i delete 11 from {1,1}and{1,5} it will cause empty set because 4 and 14 are deleted in step 1 and step 2 so it should not be deleted.

Element deletion operations should be carried out for all the cells of the arrays.OccursTogether is declared as 1D cell array.

How can i code to make Comparisons and deletions for all OccursTogether cell array locations?


回答1:


Use the following, where C stands for your OccursTogether cell (shorter, thus easier to read for this answer). The comments in the code explain a bit what the corresponding lines do.

C = cell(3,2);

C{1,1} = [4 11 14];
C{2,1} = 1;
C{2,2} = [1 4 8 14 15 19 20 22];
C{3,2} = [4 11];
celldisp(C)

C = cellfun(@unique, C, 'UniformOutput', false); % remove duplicates from elements of C

numsInCell = unique([C{:}]); % numbers in cell, sorted

for n = numsInCell % loop over numbers in cell
    lSetIs1 = cellfun(@numel,C) == 1; % length of set is 1
    nInSet = cellfun(@(set) any(set==n), C); % set contains n
    nIsUnique = sum(nInSet(:))==1; % n occurs once
    condition = ~nIsUnique & ~any(nInSet(:) & lSetIs1(:)); % set neither contains n and has length of 1, nor n is unique
    if condition % if false for all sets...
        C = cellfun(@(set) set(set~=n), C, 'UniformOutput', false); % ... then remove n from all sets
    end
end

celldisp(C)

Notice I use logical indexing in the line in the for-loop starting with C = cellfun(..., which saves you an additional for-loop over the elements of C. The MATLAB function cellfun performs the function handle in its first argument on the elements of the cell in the second argument. This is a very useful tool that prevents the use of many for-loops and even some if-statements.



来源:https://stackoverflow.com/questions/29318379/how-to-delete-element-from-cell-arrays-after-comparisons-without-causing-cell-ar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!