I want find the sum of all the elements of the matrix, how to do it?(with sum() function)

624 views (last 30 days)
hp on 27 Dec 2017
Answered: Steven Lord on 4 Mar 2020
I need to find the sum of half of the rows and all the columns... if i write only sum(a) it will give as below .. actually i need a single value of sum of pixels...
>> z=sum(a)
z(:,:,1) =
1898 1531 1367 1713
z(:,:,2) =
1734 1093 1145 1724
z(:,:,3) =
1793 1171 1199 1830
if i write as below i am getting single value but,
>> z=sum(a(:))
z =
18198
i need only sum of half of the rows and all the columns...
>> z=sum(a(1:mid-0f-row-,1:allcolums)
if i write above code it gives 1row multiple column values, that i dont need.. i have to get single value after summing those pixels as shown in the image by brown area... first half rows and all the columns covering those rows.. and should get single value for summing that area pixel values... thank you..

Hiranmay Das on 4 Mar 2020
sum(sum(X))
Above code would do the job.

Matt J on 27 Dec 2017
Edited: Matt J on 27 Dec 2017
z=sum( reshape( a( 1:mid-0f-row-,1:allcolums,:) [],1 ) );

Steven Lord on 4 Mar 2020
This wasn't an option at the time the question was originally asked, but if you're using release R2018b or later you can use the capability introduced in that release to specify either a vector of dimensions or the option 'all' to sum over multiple (or all) dimensions of an array.
A = magic(4);
sum(A, 'all')