MATLAB Answers

0

Summing elements of an array

Asked by Gian Carpinelli on 13 Apr 2018
Latest activity Commented on by Stephen Cobeldick on 13 Apr 2018
Hi, so for example I have P such that: P =
3×1 cell array
[1]
[2]
[3].
The matrix P can be a n x 1 cell array, where n is any positive integer, and can only hold numbers. Ive tried to sum these numbers using sum(P) but keep getting the error ' Undefined function 'sum' for input arguments of type 'cell'. '. Any ideas on how I could do this? thank-you.

  1 Comment

@Gian Carpinelli: why are you storing numeric data in a cell array? It would be simpler to store it in a numeric array.

Sign in to comment.

2 Answers

KL
Answer by KL
on 13 Apr 2018
Edited by KL
on 13 Apr 2018

sum([P{:}])
But why would you store it in cell array? If they are all numeric, better use a numeric array.

  0 Comments

Sign in to comment.


M
Answer by M
on 13 Apr 2018

You can use either
sum(cell2mat(P))
or
sum([P{:}])

  0 Comments

Sign in to comment.