简体   繁体   中英

Apply function to every pair of cells in a cell array

I have a cell array with 943 cells, each cell contains an array of binary elements. I want to apply a function (eg 'and' operation) on each pair of cells, for example:

and(cell1,cell2), and(cell1,cell3) ..... and(cell1,cell943)
                  and(cell2,cell3) ..... and(cell2,cell943)
.                                                 .
.                                                 .                                                  
.                                                 .
.                                        and(cell942,cell943)

For the efficiency purpose, i don't want to repeat the function on a same pair twice. How can i do this?

This would be a solution using a simple for loop:

A = { [0 1 0 1 0 1 0 1] ;
      [1 1 1 0 1 0 0 1] ;
      [0 0 0 1 1 1 0 1] }

n = numel(A);
combs = nchoosek(1:n,2)

for ii = 1:n
    output{ii,1} = A{combs(ii,1)} & A{combs(ii,2)};
    output{ii,2} = combs(ii,:);
end

returning:

在此输入图像描述

In the first column you have the result of your operation and in the second column the rows involved (of the initial cell array).


Or use arrayfun instead of the loop:

output = arrayfun(@(x) A{combs(x,1)} & A{combs(x,2)},1:n,'uni',0).';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM