Sum of elements in an array over x
Ältere Kommentare anzeigen
Hello all,
I am looking to find the sum of elements in an array which exceed a certain value, e.g. 0.05.
I have this array: [0.023 0.056 0.053 0.034 0.021 0.075 0.088]
As you can see, 4 elements are over 0.05. However, I don't want to know 'how many elements' are over 0.05, I want to find the cumulative sum of the elements which match my criteria.
In this case: 0.056 + 0.053 + 0.075 + 0.088.
Total = 0.272
Can anyone help?
kind regards,
Jacob
2 Kommentare
Jacob Merriman
am 10 Jun. 2020
Bearbeitet: Jacob Merriman
am 10 Jun. 2020
Turlough Hughes
am 10 Jun. 2020
As a point of clarification, you are looking to add elements where each individual element exceeds a value of 0.05?
Akzeptierte Antwort
Weitere Antworten (1)
Image Analyst
am 10 Jun. 2020
In general, this will do it. You need to use combnk() to get all possible combinations of elements added together. Then check the sum of each combination:
v = [0.023 0.056 0.053 0.034 0.021 0.075 0.088]
threshold = 0.05;
counter1 = 1;
counter2 = 1;
rowSum = 0;
for k = 1 : length(v)
indexes = combnk(1 : length(v), k); % Get all combinations.
[rows, columns] = size(indexes);
rowSum = rowSum + rows;
for row = 1 : rows
% For this particular combination...
thisRow = indexes(row, :);
theSum(counter1) = sum(v(thisRow));
% See if this sum is more than the threshold
if theSum(counter1) > threshold
fprintf('These %d elements sum to more than %.2f\n ', length(thisRow), threshold);
fprintf('%.3f + ', v(thisRow(1 : end-1)));
fprintf('%.3f = %.3f\n', v(thisRow(end)), theSum(counter1));
counter2 = counter2 + 1;
end
counter1 = counter1 + 1;
end
end
histogram(theSum)
grid on;
caption = sprintf('Histogram of sums after %d combinations', rowSum);
title(caption, 'FontSize', 20);
xlabel('Sum', 'FontSize', 20);
ylabel('Count', 'FontSize', 20);

You'll see 124 (counter2) lines in the command window printing out the sums that are more than your threshold, like these:
These 6 elements sum to more than 0.05
0.023 + 0.056 + 0.034 + 0.021 + 0.075 + 0.088 = 0.297
These 6 elements sum to more than 0.05
0.023 + 0.053 + 0.034 + 0.021 + 0.075 + 0.088 = 0.294
These 6 elements sum to more than 0.05
0.056 + 0.053 + 0.034 + 0.021 + 0.075 + 0.088 = 0.327
These 7 elements sum to more than 0.05
0.023 + 0.056 + 0.053 + 0.034 + 0.021 + 0.075 + 0.088 = 0.350
Kategorien
Mehr zu Matrix Indexing finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!