add elements in a matrix

9 次查看(过去 30 天)
sasso samer
sasso samer 2016-4-11
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
I have this code
for k1 = 1:2
for k2 = 1:3
S(k1,k2) = sum(a(k1,3+k2:3:end),2);
end
end
but it adds the first 3 number only, i want it to continue till the end of the matrix

回答(1 个)

Azzi Abdelmalek
Azzi Abdelmalek 2016-4-11
编辑:Azzi Abdelmalek 2016-4-12
A=[1 2 3 3 1 2 2 1 3;3 2 1 1 3 2 2 3 1];
ff=numel(A(1,1:3:end))-1;
[n,m]=size(A);
[ii,jj]=ndgrid(1:n,1:m);
AA=[A A];
out=arrayfun(@(x,y) sum(AA(x,y+3:3:y+ff*3)),ii,jj)

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by