Sum of Cell Array [Besides for loop]

1 visualización (últimos 30 días)
RDG
RDG el 15 de Abr. de 2013
Comentada: Eduardo Gil el 2 de Sept. de 2020
I'm having difficulty trying to solve this problem. Suppose:
testvalue = {[1] [] []
[1] [1] [1]
[1] [] []
[1] [1] []}
I want to sum the contents of each row, which should give:
1+nil+nil=1
1+1+1=3
1+nil+nil=1
1+1+nil=1
I tried using for loop but it upon adding cumulative sum with [], the new sum becomes []. Can someone shed some light? Thanks.

Respuesta aceptada

Walter Roberson
Walter Roberson el 15 de Abr. de 2013
T = testvalue;
T(cellfun(@isempty,T)) = {0};
sum( cell2mat(T), 2)
  2 comentarios
RDG
RDG el 15 de Abr. de 2013
Elegant solution. Thank you!
Eduardo Gil
Eduardo Gil el 2 de Sept. de 2020
Brilliant. However, could Matlab be any more cumbersome when it comes to the simple stuff. A spreadsheet would have done this without any need for logic. On the other hand, Matlab is so powerful for other less mundane tasks.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Cell Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by