addition of elements in a matrix

1 Ansicht (letzte 30 Tage)
Subrat kumar sahoo
Subrat kumar sahoo am 16 Aug. 2012
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

Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 16 Aug. 2012
Bearbeitet: Andrei Bobrov am 16 Aug. 2012
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 Kommentar
Subrat kumar sahoo
Subrat kumar sahoo am 16 Aug. 2012
Bearbeitet: Subrat kumar sahoo am 16 Aug. 2012
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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Wayne King
Wayne King am 16 Aug. 2012
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

Kategorien

Mehr zu Modeling finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by