Sum of elements in 2D matrix greater tha 150
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Sasidharan Subramani
le 12 Déc 2020
Commenté : John D'Errico
le 14 Déc 2020
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 commentaires
dileesh pv
le 14 Déc 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
John D'Errico
le 14 Déc 2020
@dileesh pv
Thank you for the explanations. I should have done that in my answer.
Réponse acceptée
VBBV
le 12 Déc 2020
Modifié(e) : VBBV
le 12 Déc 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 commentaires
Plus de réponses (1)
John D'Errico
le 12 Déc 2020
Modifié(e) : John D'Errico
le 12 Déc 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.
0 commentaires
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!