brucezepplin
brucezepplin

Reputation: 9752

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 i.e.

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?

Upvotes: 0

Views: 7784

Answers (2)

Shai
Shai

Reputation: 114796

In case you have NaNs 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

Upvotes: 0

Not Bo Styf
Not Bo Styf

Reputation: 411

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

results in

B = [6 15]

B = [7 15]

Upvotes: 2

Related Questions