J.L
J.L

Reputation: 13

How to sum a cell in Matlab

I am a new learner in Matlab and now want to add up a cell of column elements in Matlab, somehow "sum" function didn't work and it shows "Undefined function 'sum' for input arguments of type 'cell'", is there anyone know how to do it? MANY THANKS!:)

my data is like this: '218148' '106856' '255673' '156279' '175589' '310762' '87128' '123339' '149070' '104556' '206346' '216278' '235786'

Upvotes: 1

Views: 779

Answers (2)

EBH
EBH

Reputation: 10440

Your cells are strings so you first have to convert them to numeric:

C = { '218148' '106856' '255673' '156279' '175589' '310762' '87128'...
    '123339' '149070' '104556' '206346' '216278' '235786' '236087'...
    '99137' '123335' '130021' '101655' '98159' '102047' '824411' '63290'};
Csum = sum(str2double(C));

the result:

Csum =
     4123952

Upvotes: 3

Giezi
Giezi

Reputation: 140

You can call the content of your cells like this:

your_cell{:}

If all values are numeric, you can then group this result as a vector:

[your_cell{:}]

you can then easily sum this result:

sum([your_cell{:}])

A small example:

c{1} = 1;
c{2} = 3;
c{3} = 6;
sum([c{:}])

result:

ans =
    10

Upvotes: 1

Related Questions