addition of elements in a matrix

2 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Andrei Bobrov
Andrei Bobrov il 16 Ago 2012
Modificato: Andrei Bobrov il 16 Ago 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 Commento
Subrat kumar sahoo
Subrat kumar sahoo il 16 Ago 2012
Modificato: Subrat kumar sahoo il 16 Ago 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

Accedi per commentare.

Più risposte (1)

Wayne King
Wayne King il 16 Ago 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

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by