Sum of elements in 2D matrix greater tha 150

2 views (last 30 days)
I wouls like to find the sum of elements in a 2D matrix (254*318) with elements value greater than 150. but I get the code run but the answer is wrong if nayone could find the erro would be very helpful.R_10M is the name of the matrix
for a = 1:254
for b = 1:318
if (R_10M(a,b) > 150)
value = sum(sum(R_10(a,b)));
end
end
end
  2 Comments
dileesh pv
dileesh pv on 14 Dec 2020
The loops in MATLAB is generally slow. MATLAB is pretty good with opearating on matrices. For a faster and efficient execution use the inherent strengths of MATLAB.
This can be done in a single step;
s = sum( R_10M (R_10M >150));
A detailed example code is given below;
R_10M = round(rand(254,318)*300); % Matrix with random entry
s = sum (R_10M (R_10M >150)); % Required sum
% Above line of code can be deconstructed into two steps as given below
a1= (R_10M >150); % Generate the logical array where the non-zero entries
% are at the indices of elements whose values are higher than 150
s1=sum(R_10M(a1)); % sum up the elements corresponding to the non-zero
% entries in the logical array a1
This is exactly what John D'Errico has suggested. I just added little detailed explanation to it.
John D'Errico
John D'Errico on 14 Dec 2020
@dileesh pv
Thank you for the explanations. I should have done that in my answer.

Sign in to comment.

Accepted Answer

VBBV
VBBV on 12 Dec 2020
Edited: VBBV on 12 Dec 2020
for a = 1:254
for b = 1:318
if (R_10M(a,b) > 150)
value(a,b) = R_10M(a,b); % use row and column indices for values matrix required before summing,
end
end
end
V = sum(sum(value)); % singular value
VV = sum(value); % vector of summed values
What you intend to sum of values > 150 in your matrix R_10, needs further specific conditions e.g. summing row wise or column wise ? or both (like you are doing inside if condition) ?
  3 Comments
VBBV
VBBV on 12 Dec 2020
Ok. Did you get any error after changing to R_10M ?

Sign in to comment.

More Answers (1)

John D'Errico
John D'Errico on 12 Dec 2020
Edited: John D'Errico on 12 Dec 2020
Time to learn to use MATLAB as it is designed to be used.
value = sum(R_10M(R_10M > 150));
One line. No loops are necessary.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!