Sum of elements in a matrix using the sum function by matlab

I have 3 matrices that are the same size. I want to calculate the sum of all elements of a matrix by element. How can I implement it with matlab function using sum function? And if I only want to sum the first and third matrices without the second matrix, how to do it - Note that the number of my matrices can be more than 10? This is my matrix

A(:,:,1)=randint(5,5,10);
A(:,:,2)=randint(5,5,10);
A(:,:,3)=randint(5,5,10);
% Output look like
B=A(:,:,1)+A(:,:,2)+A(:,:,3);
%% How to use sum function for above task

%% If I want to sum only first and third matrix, how to do it?

      

+3


source to share


1 answer


Try to sum(A,3)

sum over the third dimension and if you want to keep certain "matrices" just use normal indexing:



sum(A(:,:,[1,3]),3)

      

+4


source







All Articles