Sum N many of the same array, which are each offset by an integer M
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Patrick Bevington
am 27 Nov. 2019
Bearbeitet: Turlough Hughes
am 27 Nov. 2019
I have an array A = [1; 2; 3; 2; 1] and I would like to make an new array B, which is equal to the sum of N many of A, where array N+1 is off set by M many interfers from array N.
Say N = 3 and M = 1, the new array would be B = [1+0+0; 2+1+0; 3+2+1, 2+3+2; 1+2+3; 0+1+2; 0+0+1].
I need A to be an array of any size and I would like to have control over the size of N and M. A will always be 1D in this case
I have attched a picutre of the problem excel. In one case M = 1 and the other M = 2. In both cases N = 3.
Thanks for any help you can offer
0 Kommentare
Akzeptierte Antwort
David Hill
am 27 Nov. 2019
function B = movSum(A,n,m)
B=A;
for k=2:n
B=[B;zeros(m,1)]+[zeros((k-1)*m,1);A];
end
end
0 Kommentare
Weitere Antworten (1)
Turlough Hughes
am 27 Nov. 2019
Bearbeitet: Turlough Hughes
am 27 Nov. 2019
The following should do the job:
N = 3; M = 2; % Inputs
A_t = [1:N N-1:-1:1]'; %single vector 1,2,3,...,N,...,3,2,1
A = zeros((N-1)*M+length(A_t),N); % Preallocate memory for A with zeros
for c = 1:N
A(c*M-1:c*M-2+length(A_t),c) = A_t; % Insert A_t and offset by additional M rows each time
end
The results are then:
A
B=sum(A,2)
0 Kommentare
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices 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!