Sum of Cell Array [Besides for loop]

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.

 採用された回答

Walter Roberson
Walter Roberson 2013 年 4 月 15 日

3 投票

T = testvalue;
T(cellfun(@isempty,T)) = {0};
sum( cell2mat(T), 2)

2 件のコメント

RDG
RDG 2013 年 4 月 15 日
Elegant solution. Thank you!
Eduardo Gil
Eduardo Gil 2020 年 9 月 2 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangePerformance and Memory についてさらに検索

タグ

質問済み:

RDG
2013 年 4 月 15 日

コメント済み:

2020 年 9 月 2 日

Community Treasure Hunt

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

Start Hunting!

Translated by