How can I find the sum of an array with the minimum value excluded?
1 view (last 30 days)
Show older comments
for e.g A = [16 21 54 32 87 12];
I would like to calculate the sum of the array excluding the lowest value, 12.
0 Comments
Answers (2)
Image Analyst
on 6 Nov 2018
You can use masking. Simply find the elements that are not the min and sum all of them. Here is the code:
% Vector
A = [16 21 54 32 87 12 100 12 55 12]
minA = min(A(:))
mask = A ~= minA
theSum = sum(A(mask))
It also works for any dimension of array. Here it is for a matrix:
% Matrix
A = [16 21 54 32 87; 12 100 12 55 12]
mask = A ~= min(A(:))
theSum = sum(A(mask))
This code works even if the min occurs more than once (unlike Stephan's answer).
Stephan
on 6 Nov 2018
Edited: Stephan
on 6 Nov 2018
A = [16 21 54 32 87 12]
B = sum(A) - min(A)
If A is a matrix use:
A = [16 21 54; 32 87 12]
B = sum(sum(A)) - min(min(A))
Best regards
Stephan
2 Comments
Steven Lord
on 6 Nov 2018
If you're using release R2018b or later, use sum(A, 'all')-min(A, 'all') and you don't need to worry about whether A is a vector, matrix, or N-dimensional array.
See Also
Categories
Find more on Matrices and Arrays 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!