Sum of previous elements in a matrix(dynamic way)

34 ビュー (過去 30 日間)
Gimpy
Gimpy 2012 年 11 月 27 日
Hi, let's say I have the following vector matrix: A=[1 2 3; 4 5 6;7 8 9;10 11 12];
I'm looking for a dynamic way to sum the previous elements(Matrix B the results). I would like to have the variable L to do that.
Example 1: L=1 means I won't to sum all element with their previous, wich give the following result:
B=[5 7 9;11 13 15;17 19 21]
Example 2: L=2 means I won't to sum all element with their 2 previous elements, wich give the following result:
B=[12 15 18;21 24 27]
L need to be dynamic.
A concrete example would be appreciate a an awnser.
Thank you in adavance,

採用された回答

Matt Fig
Matt Fig 2012 年 11 月 27 日
編集済み: Matt Fig 2012 年 11 月 27 日
Say your matrix is like:
A = [1 2 3;
4 5 6;
7 8 9;
10 11 12;
13 14 15;
16 17 18];
% Now find the solution.
L = 3; % This is dynamically set on 1<L<=M.
[M,N] = size(A);
B = zeros(M-L+1,N);
for ii = 1:M-L+1
B(ii,:) = sum(A(ii:ii+L-1,:));
end
.
.
.
.
EDIT
Note that this is exactly what the FILTER function can do:
B = filter(ones(1,L),1,A);
B = B(L:end,:)
  3 件のコメント
Matt Fig
Matt Fig 2012 年 11 月 27 日
Or, a simpler function based on my edit above:
function B = spec_fun(A,L);
% Help
% check A is m-by-n,L is in range, etc.
B = filter(ones(1,L),1,A);
B = B(L:end,:);
Gimpy
Gimpy 2012 年 11 月 29 日
THANK YOU!

サインインしてコメントする。

その他の回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 11 月 27 日
編集済み: Azzi Abdelmalek 2012 年 11 月 27 日
A=[1 2 3; 4 5 6;7 8 9;10 11 12];
out=A(1:end-1,:)+A(2:end,:)

Walter Roberson
Walter Roberson 2012 年 11 月 27 日
編集済み: Walter Roberson 2012 年 11 月 27 日
T = cumsum(A);
T(L+1:end,:) - T(1:end-L)

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by