Adding values of each element of cell array

조회 수: 25 (최근 30일)
lucksBi
lucksBi 2018년 9월 2일
편집: dpb 2018년 9월 3일
Hi i have following cell array x which contains elements like this:
x{1,1}={0.8,1.4}
x{1,2}= {2.6,2,3.4}
x{1,3}= {1,2}
i want to add values within each cell like in x{1,1}, 0.8 and 1.4 will be added.
Result = {[2.2],[8],[3]}
Thank you

채택된 답변

dpb
dpb 2018년 9월 2일
편집: dpb 2018년 9월 3일
Don't "double-up" cell indexing; makes dereferencing much more complicated than need be...
Define x as
x{1,1}=[0.8,1.4];
x{1,2}= [2.6,2,3.4];
x{1,3}= [1,2];
instead. Then it's simply
>> cellfun(@sum,x)
ans =
2.2000 8.0000 3.0000
>>
If there is some reason (but I can't think of what that could be) that the "cell inside a cell" simply must be, then you've got to do a bit more work...
x{1,1}={0.8,1.4};
x{1,2}= {2.6,2,3.4};
x{1,3}= {1,2};
>> cellfun(@(x) sum([x{:}]),x)
ans =
2.2000 8.0000 3.0000
>>
Remembering to use them and having to write all those extra brackets and curlies is a lot of complexity; just "don't do that!" by nesting and avoid it.
  댓글 수: 1
lucksBi
lucksBi 2018년 9월 3일
Yes i have converted into simple cell array as you suggested. Thanks alot for help.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by