简体   繁体   中英

matlab - cellfun sum all elements of each cell

Hi I have populated a cell array using:

D(i) = {dist};

D = reshape(D, w, h)

so that if i have:

 pix1 = D{1,1};   
 pix2 = D{2,2};

I get

pix1 = 
    1 2 3

pix2 =
    4 5 6

What I want to do is sum all the elements in each pix, and then take those results and form a matrix ie

sum(pix1) = 6
sum(pix2) = 15

matrix = 
    6 15

where in this case matrix is a 1X2 matrix (mine is a lot larger).

I am trying to do this using:

field = cellfun(@(dist) sum(dist(:)), D,'UniformOutput', false);

but this just gives me a matrix full of NaN's. Where am I going wrong?

A = {[1 2 4], [4 5 6]};
B = cellfun(@sum, A)

results in

B = [6 15]

B = [7 15]

In case you have NaN s in your cells and you wish to ignore them you may use nansum :

A = {[1, 2, NaN], [3, NaN, 4, 5]; [6, NaN], [10, -3, NaN, 4]};
B = cellfun( @nansum, A )

Results with

B =

    3    12
    6    11

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