Sum of Cell Array [Besides for loop]

조회 수: 1 (최근 30일)
RDG
RDG 2013년 4월 15일
댓글: Eduardo Gil 2020년 9월 2일
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일
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개)

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by