필터 지우기
필터 지우기

how to sum matrics inside a cell array?

조회 수: 52 (최근 30일)
Kobi
Kobi 2014년 8월 6일
댓글: LD 2017년 11월 26일
i have 4 matrics inside a cell and i need to sum them all currenyly i use this:
R=R{1}+R{2}+R{3}+R{4}
the original R is a cell with 4 matrics

채택된 답변

dpb
dpb 2014년 8월 6일
편집: dpb 2017년 4월 22일
Oh, misunderstood the query...that's simply
S=plus(R{:})
S =
1.3771 0.5139
1.1590 0.7149
>> all(all(S==R{1}+R{2}))
ans =
1
>>
Just used two cells here, but works for any number. As noted elsewhere sizes must be commensurate.
ERRATUM Does NOT work as written for any number of cells; plus isn't as smart as I was thinking it was/is... :(
Instead use
S=sum(cat(3,R{:}),3);
As another poster noted, all cells must contain conformantly-sized arrays.
NB: The result will be class of the content of the cell (default double, of course).
  댓글 수: 5
dpb
dpb 2017년 4월 22일
Hmmm....my bad, had tested only for two cells; I was thinking w/o checking that plus was enabled to handle a variable number of arguments but it isn't...see ERRATUM above Answer--dpb
LD
LD 2017년 11월 26일
Is there other methods to solve this problem? This methods is less efficient then the for-loop

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

추가 답변 (2개)

Evan
Evan 2014년 8월 6일
편집: Evan 2014년 8월 6일
Are all the matrices in your cell array the same size? If so, this should work:
% Get random cell array with n cells. Here n = 3
A = {rand(4) rand(4) rand(4)}
n = size(A,2);
% Get size of matrices in cell.
matSize = size(A{1},1);
B = reshape(cell2mat(A),matSize,[],n);
% Sum 3D matrix along 3rd dimension
C = sum(B,3);
If they're different sizes, this either wont work or we need more information about how you want the different sizes handles (e.g. trimming, padding, etc.).

dpb
dpb 2014년 8월 6일
One way, seems should be better but it's still first cup o' coffee this morning...
>> R={rand(2) rand(3)}
R =
[2x2 double] [3x3 double]
>> sum(cellfun(@(x) sum(x(:)),R))
ans =
8.7056
>>
  댓글 수: 1
Kobi
Kobi 2014년 8월 6일
this is not what i need i need to + sum the matrics like this A=rand(7)+rand(7)+rand(7)+.... and to recive one matrix each and every element in one matrix is added to another corresponding element the only problem is that all of the matrics are inside a cell

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

카테고리

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

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by