take line sum of part of matrix
Mostrar comentarios más antiguos
Hi all!
I'm trying to use (as always) vectorized commands but came to a problem which looks quite simple at the beginning. Let me give you an example.
A = [1, 2, 54, 4, 5, 6; ...
1, 2, 88, 4, 5, 6; ...
1, 2, 0, 4, 5, 6; ]; % identical rows except for column 3
b = [5;2;6];
The values in b give the last column in A I want to build the line-sum for: My result should give me
c = ??? = [1+2+54+4+5;
1+2;
1+2+0+4+5+6];
Thank you for your help!
Respuesta aceptada
Más respuestas (3)
Another:
% Given data
A = [1, 2, 54, 4, 5, 6;...
1, 2, 88, 4, 5, 6;...
1, 2, 0, 4, 5, 6];
b = [5;2;6];
% The method
R = size(A,1); % Just to be general.
S = cumsum(A,2); % The cumulative sum.
S = S((1:R).' + (b-1)*R) % The desired values.
Thomas
el 25 de Sept. de 2012
A = [1, 2, 54, 4, 5, 6; 1, 2, 88, 4, 5, 6; 1, 2, 0, 4, 5, 6; ];
b = [5;2;6];
for ii=1:length(b)
sumA(ii)=sum(A(ii,1:b(ii)));
end
sumA
Andrei Bobrov
el 25 de Sept. de 2012
A = [1, 2, 54, 4, 5, 6; ...
1, 2, 88, 4, 5, 6; ...
1, 2, 0, 4, 5, 6; ];
b = [5;2;6];
s = size(A);
q = zeros(s);
q((b - 1)*s(1) + (1:s(1))') = 1;
i1 = bsxfun(@times,fliplr(cumsum(fliplr(q),2)),(1:s(1))');
t = i1>0;
out = accumarray(i1(t),A(t));
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!