Adding elements with specific distance in a matrix
Show older comments
I have a matrix like this
1 2 3 3 1 2 2 1 3
3 2 1 1 3 2 2 3 1
What i want to do is a 3x9 matrix that contains this
cell (1,1) . (1 + 3 + 2) - 1 .... 1(the first element) + 3(the fourth element) + 2(the 7th element) - 1(my initial cell)
cell (1,2) . (2 + 1 + 1) - 2 .... 2(the second element) + 1(the fifth element) + 1(the 8th element) - 2(my initial cell)
and so on... cell (1,5) . (1 + 2 + 1)-1 .... 1(the 5th element) + 2(2nd element) + 1(8th element) - 1(initial cell)
It's like calculating the total of all the numbers where the indices are separated by 3
output = 5 2 5 3 3 6 4 3 5
3 6 3 5 5 2 4 5 3
Answers (1)
Andrei Bobrov
on 11 Apr 2016
t =[1 2 3 3 1 2 2 1 3
3 2 1 1 3 2 2 3 1];
s = size(t);
M = reshape(t,s(1),3,[]);
i3 = nchoosek(1:3,2);
X = sum(reshape(M(:,:,i3(end:-1:1,:)),s(1),3,2,[]),3);
out = reshape(X(:,:,:,end:-1:1),s(1),[]);
Categories
Find more on Elementary Math in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!