MATLAB: Reduce one dimension of a array by using sum

for loops

Hello,
Can anyone show me how I can reduce one dimension of the following array without using for loops. Thanks!
A=rand(100,100,100);
for ith = 1:100
for jth = 1:100
B(ith,jth) = sum(A(ith,:,jth))
end
end

Best Answer

If you are summing across the second dimension of your three-dimension array A, the easiest way would be to use the ‘dim’ argument of sum:
B = squeeze(sum(A,2))
Does this do what you want?