addition of elements in a matrix

조회 수: 2 (최근 30일)
Subrat kumar sahoo
Subrat kumar sahoo 2012년 8월 16일
Hi I have a matrix, e.g. "A" whose dimension is 3*20. I need to obtain a 3*4 matrix ("B") out of it, wherein every fifth element in a row is added together. That means the new matrix B11= A11+A15+A110+A120 and so on. Since the actual dimension of A is really huge, I need to do this in a loop. Any help will be appreciated.
Thanks, Subrat

채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 8월 16일
편집: Andrei Bobrov 2012년 8월 16일
Can so?
A = randi(30,3,20);
B = sum(reshape(A,size(A,1),4,[]),3);
OR
B2 = squeeze(sum(reshape(A,size(A,1),5,[]),2));
  댓글 수: 1
Subrat kumar sahoo
Subrat kumar sahoo 2012년 8월 16일
편집: Subrat kumar sahoo 2012년 8월 16일
Thanks Andrei, This works, but could you tell me what is the role of number 3 in output of 'B', i.e the dimensions of A. I realized that it works with that number, when the row numbers are changed from number 3 to lets say 3000 in 'A = randi(30,3,20);' I am not aware of using sum with dim other than 1 or 2. So is it associated anyway with the row numbers given in 'A'? Thanks, Subrat

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

추가 답변 (1개)

Wayne King
Wayne King 2012년 8월 16일
Does this work for you?
A = randn(3,20);
B = zeros(3,4);
first = 1:5:size(A,2);
last = 5:5:size(A,2);
kk = 1;
for nn = 1:length(first)
tmp = A(:,first(nn):last(nn));
B(:,kk) = sum(tmp,2);
kk = kk+1;
end

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by